three.cjs 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '183dev';
  8. /**
  9. * Represents mouse buttons and interaction types in context of controls.
  10. *
  11. * @type {ConstantsMouse}
  12. * @constant
  13. */
  14. const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
  15. /**
  16. * Represents touch interaction types in context of controls.
  17. *
  18. * @type {ConstantsTouch}
  19. * @constant
  20. */
  21. const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
  22. /**
  23. * Disables face culling.
  24. *
  25. * @type {number}
  26. * @constant
  27. */
  28. const CullFaceNone = 0;
  29. /**
  30. * Culls back faces.
  31. *
  32. * @type {number}
  33. * @constant
  34. */
  35. const CullFaceBack = 1;
  36. /**
  37. * Culls front faces.
  38. *
  39. * @type {number}
  40. * @constant
  41. */
  42. const CullFaceFront = 2;
  43. /**
  44. * Culls both front and back faces.
  45. *
  46. * @type {number}
  47. * @constant
  48. */
  49. const CullFaceFrontBack = 3;
  50. /**
  51. * Gives unfiltered shadow maps - fastest, but lowest quality.
  52. *
  53. * @type {number}
  54. * @constant
  55. */
  56. const BasicShadowMap = 0;
  57. /**
  58. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm.
  59. *
  60. * @type {number}
  61. * @constant
  62. */
  63. const PCFShadowMap = 1;
  64. /**
  65. * Filters shadow maps using the Percentage-Closer Filtering (PCF) algorithm with
  66. * better soft shadows especially when using low-resolution shadow maps.
  67. *
  68. * @type {number}
  69. * @constant
  70. */
  71. const PCFSoftShadowMap = 2;
  72. /**
  73. * Filters shadow maps using the Variance Shadow Map (VSM) algorithm.
  74. * When using VSMShadowMap all shadow receivers will also cast shadows.
  75. *
  76. * @type {number}
  77. * @constant
  78. */
  79. const VSMShadowMap = 3;
  80. /**
  81. * Only front faces are rendered.
  82. *
  83. * @type {number}
  84. * @constant
  85. */
  86. const FrontSide = 0;
  87. /**
  88. * Only back faces are rendered.
  89. *
  90. * @type {number}
  91. * @constant
  92. */
  93. const BackSide = 1;
  94. /**
  95. * Both front and back faces are rendered.
  96. *
  97. * @type {number}
  98. * @constant
  99. */
  100. const DoubleSide = 2;
  101. /**
  102. * No blending is performed which effectively disables
  103. * alpha transparency.
  104. *
  105. * @type {number}
  106. * @constant
  107. */
  108. const NoBlending = 0;
  109. /**
  110. * The default blending.
  111. *
  112. * @type {number}
  113. * @constant
  114. */
  115. const NormalBlending = 1;
  116. /**
  117. * Represents additive blending.
  118. *
  119. * @type {number}
  120. * @constant
  121. */
  122. const AdditiveBlending = 2;
  123. /**
  124. * Represents subtractive blending.
  125. *
  126. * @type {number}
  127. * @constant
  128. */
  129. const SubtractiveBlending = 3;
  130. /**
  131. * Represents multiply blending.
  132. *
  133. * @type {number}
  134. * @constant
  135. */
  136. const MultiplyBlending = 4;
  137. /**
  138. * Represents custom blending.
  139. *
  140. * @type {number}
  141. * @constant
  142. */
  143. const CustomBlending = 5;
  144. /**
  145. * A `source + destination` blending equation.
  146. *
  147. * @type {number}
  148. * @constant
  149. */
  150. const AddEquation = 100;
  151. /**
  152. * A `source - destination` blending equation.
  153. *
  154. * @type {number}
  155. * @constant
  156. */
  157. const SubtractEquation = 101;
  158. /**
  159. * A `destination - source` blending equation.
  160. *
  161. * @type {number}
  162. * @constant
  163. */
  164. const ReverseSubtractEquation = 102;
  165. /**
  166. * A blend equation that uses the minimum of source and destination.
  167. *
  168. * @type {number}
  169. * @constant
  170. */
  171. const MinEquation = 103;
  172. /**
  173. * A blend equation that uses the maximum of source and destination.
  174. *
  175. * @type {number}
  176. * @constant
  177. */
  178. const MaxEquation = 104;
  179. /**
  180. * Multiplies all colors by `0`.
  181. *
  182. * @type {number}
  183. * @constant
  184. */
  185. const ZeroFactor = 200;
  186. /**
  187. * Multiplies all colors by `1`.
  188. *
  189. * @type {number}
  190. * @constant
  191. */
  192. const OneFactor = 201;
  193. /**
  194. * Multiplies all colors by the source colors.
  195. *
  196. * @type {number}
  197. * @constant
  198. */
  199. const SrcColorFactor = 202;
  200. /**
  201. * Multiplies all colors by `1` minus each source color.
  202. *
  203. * @type {number}
  204. * @constant
  205. */
  206. const OneMinusSrcColorFactor = 203;
  207. /**
  208. * Multiplies all colors by the source alpha value.
  209. *
  210. * @type {number}
  211. * @constant
  212. */
  213. const SrcAlphaFactor = 204;
  214. /**
  215. * Multiplies all colors by 1 minus the source alpha value.
  216. *
  217. * @type {number}
  218. * @constant
  219. */
  220. const OneMinusSrcAlphaFactor = 205;
  221. /**
  222. * Multiplies all colors by the destination alpha value.
  223. *
  224. * @type {number}
  225. * @constant
  226. */
  227. const DstAlphaFactor = 206;
  228. /**
  229. * Multiplies all colors by `1` minus the destination alpha value.
  230. *
  231. * @type {number}
  232. * @constant
  233. */
  234. const OneMinusDstAlphaFactor = 207;
  235. /**
  236. * Multiplies all colors by the destination color.
  237. *
  238. * @type {number}
  239. * @constant
  240. */
  241. const DstColorFactor = 208;
  242. /**
  243. * Multiplies all colors by `1` minus each destination color.
  244. *
  245. * @type {number}
  246. * @constant
  247. */
  248. const OneMinusDstColorFactor = 209;
  249. /**
  250. * Multiplies the RGB colors by the smaller of either the source alpha
  251. * value or the value of `1` minus the destination alpha value. The alpha
  252. * value is multiplied by `1`.
  253. *
  254. * @type {number}
  255. * @constant
  256. */
  257. const SrcAlphaSaturateFactor = 210;
  258. /**
  259. * Multiplies all colors by a constant color.
  260. *
  261. * @type {number}
  262. * @constant
  263. */
  264. const ConstantColorFactor = 211;
  265. /**
  266. * Multiplies all colors by `1` minus a constant color.
  267. *
  268. * @type {number}
  269. * @constant
  270. */
  271. const OneMinusConstantColorFactor = 212;
  272. /**
  273. * Multiplies all colors by a constant alpha value.
  274. *
  275. * @type {number}
  276. * @constant
  277. */
  278. const ConstantAlphaFactor = 213;
  279. /**
  280. * Multiplies all colors by 1 minus a constant alpha value.
  281. *
  282. * @type {number}
  283. * @constant
  284. */
  285. const OneMinusConstantAlphaFactor = 214;
  286. /**
  287. * Never pass.
  288. *
  289. * @type {number}
  290. * @constant
  291. */
  292. const NeverDepth = 0;
  293. /**
  294. * Always pass.
  295. *
  296. * @type {number}
  297. * @constant
  298. */
  299. const AlwaysDepth = 1;
  300. /**
  301. * Pass if the incoming value is less than the depth buffer value.
  302. *
  303. * @type {number}
  304. * @constant
  305. */
  306. const LessDepth = 2;
  307. /**
  308. * Pass if the incoming value is less than or equal to the depth buffer value.
  309. *
  310. * @type {number}
  311. * @constant
  312. */
  313. const LessEqualDepth = 3;
  314. /**
  315. * Pass if the incoming value equals the depth buffer value.
  316. *
  317. * @type {number}
  318. * @constant
  319. */
  320. const EqualDepth = 4;
  321. /**
  322. * Pass if the incoming value is greater than or equal to the depth buffer value.
  323. *
  324. * @type {number}
  325. * @constant
  326. */
  327. const GreaterEqualDepth = 5;
  328. /**
  329. * Pass if the incoming value is greater than the depth buffer value.
  330. *
  331. * @type {number}
  332. * @constant
  333. */
  334. const GreaterDepth = 6;
  335. /**
  336. * Pass if the incoming value is not equal to the depth buffer value.
  337. *
  338. * @type {number}
  339. * @constant
  340. */
  341. const NotEqualDepth = 7;
  342. /**
  343. * Multiplies the environment map color with the surface color.
  344. *
  345. * @type {number}
  346. * @constant
  347. */
  348. const MultiplyOperation = 0;
  349. /**
  350. * Uses reflectivity to blend between the two colors.
  351. *
  352. * @type {number}
  353. * @constant
  354. */
  355. const MixOperation = 1;
  356. /**
  357. * Adds the two colors.
  358. *
  359. * @type {number}
  360. * @constant
  361. */
  362. const AddOperation = 2;
  363. /**
  364. * No tone mapping is applied.
  365. *
  366. * @type {number}
  367. * @constant
  368. */
  369. const NoToneMapping = 0;
  370. /**
  371. * Linear tone mapping.
  372. *
  373. * @type {number}
  374. * @constant
  375. */
  376. const LinearToneMapping = 1;
  377. /**
  378. * Reinhard tone mapping.
  379. *
  380. * @type {number}
  381. * @constant
  382. */
  383. const ReinhardToneMapping = 2;
  384. /**
  385. * Cineon tone mapping.
  386. *
  387. * @type {number}
  388. * @constant
  389. */
  390. const CineonToneMapping = 3;
  391. /**
  392. * ACES Filmic tone mapping.
  393. *
  394. * @type {number}
  395. * @constant
  396. */
  397. const ACESFilmicToneMapping = 4;
  398. /**
  399. * Custom tone mapping.
  400. *
  401. * Expects a custom implementation by modifying shader code of the material's fragment shader.
  402. *
  403. * @type {number}
  404. * @constant
  405. */
  406. const CustomToneMapping = 5;
  407. /**
  408. * AgX tone mapping.
  409. *
  410. * @type {number}
  411. * @constant
  412. */
  413. const AgXToneMapping = 6;
  414. /**
  415. * Neutral tone mapping.
  416. *
  417. * Implementation based on the Khronos 3D Commerce Group standard tone mapping.
  418. *
  419. * @type {number}
  420. * @constant
  421. */
  422. const NeutralToneMapping = 7;
  423. /**
  424. * The skinned mesh shares the same world space as the skeleton.
  425. *
  426. * @type {string}
  427. * @constant
  428. */
  429. const AttachedBindMode = 'attached';
  430. /**
  431. * The skinned mesh does not share the same world space as the skeleton.
  432. * This is useful when a skeleton is shared across multiple skinned meshes.
  433. *
  434. * @type {string}
  435. * @constant
  436. */
  437. const DetachedBindMode = 'detached';
  438. /**
  439. * Maps textures using the geometry's UV coordinates.
  440. *
  441. * @type {number}
  442. * @constant
  443. */
  444. const UVMapping = 300;
  445. /**
  446. * Reflection mapping for cube textures.
  447. *
  448. * @type {number}
  449. * @constant
  450. */
  451. const CubeReflectionMapping = 301;
  452. /**
  453. * Refraction mapping for cube textures.
  454. *
  455. * @type {number}
  456. * @constant
  457. */
  458. const CubeRefractionMapping = 302;
  459. /**
  460. * Reflection mapping for equirectangular textures.
  461. *
  462. * @type {number}
  463. * @constant
  464. */
  465. const EquirectangularReflectionMapping = 303;
  466. /**
  467. * Refraction mapping for equirectangular textures.
  468. *
  469. * @type {number}
  470. * @constant
  471. */
  472. const EquirectangularRefractionMapping = 304;
  473. /**
  474. * Reflection mapping for PMREM textures.
  475. *
  476. * @type {number}
  477. * @constant
  478. */
  479. const CubeUVReflectionMapping = 306;
  480. /**
  481. * The texture will simply repeat to infinity.
  482. *
  483. * @type {number}
  484. * @constant
  485. */
  486. const RepeatWrapping = 1000;
  487. /**
  488. * The last pixel of the texture stretches to the edge of the mesh.
  489. *
  490. * @type {number}
  491. * @constant
  492. */
  493. const ClampToEdgeWrapping = 1001;
  494. /**
  495. * The texture will repeats to infinity, mirroring on each repeat.
  496. *
  497. * @type {number}
  498. * @constant
  499. */
  500. const MirroredRepeatWrapping = 1002;
  501. /**
  502. * Returns the value of the texture element that is nearest (in Manhattan distance)
  503. * to the specified texture coordinates.
  504. *
  505. * @type {number}
  506. * @constant
  507. */
  508. const NearestFilter = 1003;
  509. /**
  510. * Chooses the mipmap that most closely matches the size of the pixel being textured
  511. * and uses the `NearestFilter` criterion (the texel nearest to the center of the pixel)
  512. * to produce a texture value.
  513. *
  514. * @type {number}
  515. * @constant
  516. */
  517. const NearestMipmapNearestFilter = 1004;
  518. const NearestMipMapNearestFilter = 1004; // legacy
  519. /**
  520. * Chooses the two mipmaps that most closely match the size of the pixel being textured and
  521. * uses the `NearestFilter` criterion to produce a texture value from each mipmap.
  522. * The final texture value is a weighted average of those two values.
  523. *
  524. * @type {number}
  525. * @constant
  526. */
  527. const NearestMipmapLinearFilter = 1005;
  528. const NearestMipMapLinearFilter = 1005; // legacy
  529. /**
  530. * Returns the weighted average of the four texture elements that are closest to the specified
  531. * texture coordinates, and can include items wrapped or repeated from other parts of a texture,
  532. * depending on the values of `wrapS` and `wrapT`, and on the exact mapping.
  533. *
  534. * @type {number}
  535. * @constant
  536. */
  537. const LinearFilter = 1006;
  538. /**
  539. * Chooses the mipmap that most closely matches the size of the pixel being textured and uses
  540. * the `LinearFilter` criterion (a weighted average of the four texels that are closest to the
  541. * center of the pixel) to produce a texture value.
  542. *
  543. * @type {number}
  544. * @constant
  545. */
  546. const LinearMipmapNearestFilter = 1007;
  547. const LinearMipMapNearestFilter = 1007; // legacy
  548. /**
  549. * Chooses the two mipmaps that most closely match the size of the pixel being textured and uses
  550. * the `LinearFilter` criterion to produce a texture value from each mipmap. The final texture value
  551. * is a weighted average of those two values.
  552. *
  553. * @type {number}
  554. * @constant
  555. */
  556. const LinearMipmapLinearFilter = 1008;
  557. const LinearMipMapLinearFilter = 1008; // legacy
  558. /**
  559. * An unsigned byte data type for textures.
  560. *
  561. * @type {number}
  562. * @constant
  563. */
  564. const UnsignedByteType = 1009;
  565. /**
  566. * A byte data type for textures.
  567. *
  568. * @type {number}
  569. * @constant
  570. */
  571. const ByteType = 1010;
  572. /**
  573. * A short data type for textures.
  574. *
  575. * @type {number}
  576. * @constant
  577. */
  578. const ShortType = 1011;
  579. /**
  580. * An unsigned short data type for textures.
  581. *
  582. * @type {number}
  583. * @constant
  584. */
  585. const UnsignedShortType = 1012;
  586. /**
  587. * An int data type for textures.
  588. *
  589. * @type {number}
  590. * @constant
  591. */
  592. const IntType = 1013;
  593. /**
  594. * An unsigned int data type for textures.
  595. *
  596. * @type {number}
  597. * @constant
  598. */
  599. const UnsignedIntType = 1014;
  600. /**
  601. * A float data type for textures.
  602. *
  603. * @type {number}
  604. * @constant
  605. */
  606. const FloatType = 1015;
  607. /**
  608. * A half float data type for textures.
  609. *
  610. * @type {number}
  611. * @constant
  612. */
  613. const HalfFloatType = 1016;
  614. /**
  615. * An unsigned short 4_4_4_4 (packed) data type for textures.
  616. *
  617. * @type {number}
  618. * @constant
  619. */
  620. const UnsignedShort4444Type = 1017;
  621. /**
  622. * An unsigned short 5_5_5_1 (packed) data type for textures.
  623. *
  624. * @type {number}
  625. * @constant
  626. */
  627. const UnsignedShort5551Type = 1018;
  628. /**
  629. * An unsigned int 24_8 data type for textures.
  630. *
  631. * @type {number}
  632. * @constant
  633. */
  634. const UnsignedInt248Type = 1020;
  635. /**
  636. * An unsigned int 5_9_9_9 (packed) data type for textures.
  637. *
  638. * @type {number}
  639. * @constant
  640. */
  641. const UnsignedInt5999Type = 35902;
  642. /**
  643. * An unsigned int 10_11_11 (packed) data type for textures.
  644. *
  645. * @type {number}
  646. * @constant
  647. */
  648. const UnsignedInt101111Type = 35899;
  649. /**
  650. * Discards the red, green and blue components and reads just the alpha component.
  651. *
  652. * @type {number}
  653. * @constant
  654. */
  655. const AlphaFormat = 1021;
  656. /**
  657. * Discards the alpha component and reads the red, green and blue component.
  658. *
  659. * @type {number}
  660. * @constant
  661. */
  662. const RGBFormat = 1022;
  663. /**
  664. * Reads the red, green, blue and alpha components.
  665. *
  666. * @type {number}
  667. * @constant
  668. */
  669. const RGBAFormat = 1023;
  670. /**
  671. * Reads each element as a single depth value, converts it to floating point, and clamps to the range `[0,1]`.
  672. *
  673. * @type {number}
  674. * @constant
  675. */
  676. const DepthFormat = 1026;
  677. /**
  678. * Reads each element is a pair of depth and stencil values. The depth component of the pair is interpreted as
  679. * in `DepthFormat`. The stencil component is interpreted based on the depth + stencil internal format.
  680. *
  681. * @type {number}
  682. * @constant
  683. */
  684. const DepthStencilFormat = 1027;
  685. /**
  686. * Discards the green, blue and alpha components and reads just the red component.
  687. *
  688. * @type {number}
  689. * @constant
  690. */
  691. const RedFormat = 1028;
  692. /**
  693. * Discards the green, blue and alpha components and reads just the red component. The texels are read as integers instead of floating point.
  694. *
  695. * @type {number}
  696. * @constant
  697. */
  698. const RedIntegerFormat = 1029;
  699. /**
  700. * Discards the alpha, and blue components and reads the red, and green components.
  701. *
  702. * @type {number}
  703. * @constant
  704. */
  705. const RGFormat = 1030;
  706. /**
  707. * Discards the alpha, and blue components and reads the red, and green components. The texels are read as integers instead of floating point.
  708. *
  709. * @type {number}
  710. * @constant
  711. */
  712. const RGIntegerFormat = 1031;
  713. /**
  714. * Discards the alpha component and reads the red, green and blue component. The texels are read as integers instead of floating point.
  715. *
  716. * @type {number}
  717. * @constant
  718. */
  719. const RGBIntegerFormat = 1032;
  720. /**
  721. * Reads the red, green, blue and alpha components. The texels are read as integers instead of floating point.
  722. *
  723. * @type {number}
  724. * @constant
  725. */
  726. const RGBAIntegerFormat = 1033;
  727. /**
  728. * A DXT1-compressed image in an RGB image format.
  729. *
  730. * @type {number}
  731. * @constant
  732. */
  733. const RGB_S3TC_DXT1_Format = 33776;
  734. /**
  735. * A DXT1-compressed image in an RGB image format with a simple on/off alpha value.
  736. *
  737. * @type {number}
  738. * @constant
  739. */
  740. const RGBA_S3TC_DXT1_Format = 33777;
  741. /**
  742. * A DXT3-compressed image in an RGBA image format. Compared to a 32-bit RGBA texture, it offers 4:1 compression.
  743. *
  744. * @type {number}
  745. * @constant
  746. */
  747. const RGBA_S3TC_DXT3_Format = 33778;
  748. /**
  749. * A DXT5-compressed image in an RGBA image format. It also provides a 4:1 compression, but differs to the DXT3
  750. * compression in how the alpha compression is done.
  751. *
  752. * @type {number}
  753. * @constant
  754. */
  755. const RGBA_S3TC_DXT5_Format = 33779;
  756. /**
  757. * PVRTC RGB compression in 4-bit mode. One block for each 4×4 pixels.
  758. *
  759. * @type {number}
  760. * @constant
  761. */
  762. const RGB_PVRTC_4BPPV1_Format = 35840;
  763. /**
  764. * PVRTC RGB compression in 2-bit mode. One block for each 8×4 pixels.
  765. *
  766. * @type {number}
  767. * @constant
  768. */
  769. const RGB_PVRTC_2BPPV1_Format = 35841;
  770. /**
  771. * PVRTC RGBA compression in 4-bit mode. One block for each 4×4 pixels.
  772. *
  773. * @type {number}
  774. * @constant
  775. */
  776. const RGBA_PVRTC_4BPPV1_Format = 35842;
  777. /**
  778. * PVRTC RGBA compression in 2-bit mode. One block for each 8×4 pixels.
  779. *
  780. * @type {number}
  781. * @constant
  782. */
  783. const RGBA_PVRTC_2BPPV1_Format = 35843;
  784. /**
  785. * ETC1 RGB format.
  786. *
  787. * @type {number}
  788. * @constant
  789. */
  790. const RGB_ETC1_Format = 36196;
  791. /**
  792. * ETC2 RGB format.
  793. *
  794. * @type {number}
  795. * @constant
  796. */
  797. const RGB_ETC2_Format = 37492;
  798. /**
  799. * ETC2 RGBA format.
  800. *
  801. * @type {number}
  802. * @constant
  803. */
  804. const RGBA_ETC2_EAC_Format = 37496;
  805. /**
  806. * EAC R11 UNORM format.
  807. *
  808. * @type {number}
  809. * @constant
  810. */
  811. const R11_EAC_Format = 37488; // 0x9270
  812. /**
  813. * EAC R11 SNORM format.
  814. *
  815. * @type {number}
  816. * @constant
  817. */
  818. const SIGNED_R11_EAC_Format = 37489; // 0x9271
  819. /**
  820. * EAC RG11 UNORM format.
  821. *
  822. * @type {number}
  823. * @constant
  824. */
  825. const RG11_EAC_Format = 37490; // 0x9272
  826. /**
  827. * EAC RG11 SNORM format.
  828. *
  829. * @type {number}
  830. * @constant
  831. */
  832. const SIGNED_RG11_EAC_Format = 37491; // 0x9273
  833. /**
  834. * ASTC RGBA 4x4 format.
  835. *
  836. * @type {number}
  837. * @constant
  838. */
  839. const RGBA_ASTC_4x4_Format = 37808;
  840. /**
  841. * ASTC RGBA 5x4 format.
  842. *
  843. * @type {number}
  844. * @constant
  845. */
  846. const RGBA_ASTC_5x4_Format = 37809;
  847. /**
  848. * ASTC RGBA 5x5 format.
  849. *
  850. * @type {number}
  851. * @constant
  852. */
  853. const RGBA_ASTC_5x5_Format = 37810;
  854. /**
  855. * ASTC RGBA 6x5 format.
  856. *
  857. * @type {number}
  858. * @constant
  859. */
  860. const RGBA_ASTC_6x5_Format = 37811;
  861. /**
  862. * ASTC RGBA 6x6 format.
  863. *
  864. * @type {number}
  865. * @constant
  866. */
  867. const RGBA_ASTC_6x6_Format = 37812;
  868. /**
  869. * ASTC RGBA 8x5 format.
  870. *
  871. * @type {number}
  872. * @constant
  873. */
  874. const RGBA_ASTC_8x5_Format = 37813;
  875. /**
  876. * ASTC RGBA 8x6 format.
  877. *
  878. * @type {number}
  879. * @constant
  880. */
  881. const RGBA_ASTC_8x6_Format = 37814;
  882. /**
  883. * ASTC RGBA 8x8 format.
  884. *
  885. * @type {number}
  886. * @constant
  887. */
  888. const RGBA_ASTC_8x8_Format = 37815;
  889. /**
  890. * ASTC RGBA 10x5 format.
  891. *
  892. * @type {number}
  893. * @constant
  894. */
  895. const RGBA_ASTC_10x5_Format = 37816;
  896. /**
  897. * ASTC RGBA 10x6 format.
  898. *
  899. * @type {number}
  900. * @constant
  901. */
  902. const RGBA_ASTC_10x6_Format = 37817;
  903. /**
  904. * ASTC RGBA 10x8 format.
  905. *
  906. * @type {number}
  907. * @constant
  908. */
  909. const RGBA_ASTC_10x8_Format = 37818;
  910. /**
  911. * ASTC RGBA 10x10 format.
  912. *
  913. * @type {number}
  914. * @constant
  915. */
  916. const RGBA_ASTC_10x10_Format = 37819;
  917. /**
  918. * ASTC RGBA 12x10 format.
  919. *
  920. * @type {number}
  921. * @constant
  922. */
  923. const RGBA_ASTC_12x10_Format = 37820;
  924. /**
  925. * ASTC RGBA 12x12 format.
  926. *
  927. * @type {number}
  928. * @constant
  929. */
  930. const RGBA_ASTC_12x12_Format = 37821;
  931. /**
  932. * BPTC RGBA format.
  933. *
  934. * @type {number}
  935. * @constant
  936. */
  937. const RGBA_BPTC_Format = 36492;
  938. /**
  939. * BPTC Signed RGB format.
  940. *
  941. * @type {number}
  942. * @constant
  943. */
  944. const RGB_BPTC_SIGNED_Format = 36494;
  945. /**
  946. * BPTC Unsigned RGB format.
  947. *
  948. * @type {number}
  949. * @constant
  950. */
  951. const RGB_BPTC_UNSIGNED_Format = 36495;
  952. /**
  953. * RGTC1 Red format.
  954. *
  955. * @type {number}
  956. * @constant
  957. */
  958. const RED_RGTC1_Format = 36283;
  959. /**
  960. * RGTC1 Signed Red format.
  961. *
  962. * @type {number}
  963. * @constant
  964. */
  965. const SIGNED_RED_RGTC1_Format = 36284;
  966. /**
  967. * RGTC2 Red Green format.
  968. *
  969. * @type {number}
  970. * @constant
  971. */
  972. const RED_GREEN_RGTC2_Format = 36285;
  973. /**
  974. * RGTC2 Signed Red Green format.
  975. *
  976. * @type {number}
  977. * @constant
  978. */
  979. const SIGNED_RED_GREEN_RGTC2_Format = 36286;
  980. /**
  981. * Animations are played once.
  982. *
  983. * @type {number}
  984. * @constant
  985. */
  986. const LoopOnce = 2200;
  987. /**
  988. * Animations are played with a chosen number of repetitions, each time jumping from
  989. * the end of the clip directly to its beginning.
  990. *
  991. * @type {number}
  992. * @constant
  993. */
  994. const LoopRepeat = 2201;
  995. /**
  996. * Animations are played with a chosen number of repetitions, alternately playing forward
  997. * and backward.
  998. *
  999. * @type {number}
  1000. * @constant
  1001. */
  1002. const LoopPingPong = 2202;
  1003. /**
  1004. * Discrete interpolation mode for keyframe tracks.
  1005. *
  1006. * @type {number}
  1007. * @constant
  1008. */
  1009. const InterpolateDiscrete = 2300;
  1010. /**
  1011. * Linear interpolation mode for keyframe tracks.
  1012. *
  1013. * @type {number}
  1014. * @constant
  1015. */
  1016. const InterpolateLinear = 2301;
  1017. /**
  1018. * Smooth interpolation mode for keyframe tracks.
  1019. *
  1020. * @type {number}
  1021. * @constant
  1022. */
  1023. const InterpolateSmooth = 2302;
  1024. /**
  1025. * Zero curvature ending for animations.
  1026. *
  1027. * @type {number}
  1028. * @constant
  1029. */
  1030. const ZeroCurvatureEnding = 2400;
  1031. /**
  1032. * Zero slope ending for animations.
  1033. *
  1034. * @type {number}
  1035. * @constant
  1036. */
  1037. const ZeroSlopeEnding = 2401;
  1038. /**
  1039. * Wrap around ending for animations.
  1040. *
  1041. * @type {number}
  1042. * @constant
  1043. */
  1044. const WrapAroundEnding = 2402;
  1045. /**
  1046. * Default animation blend mode.
  1047. *
  1048. * @type {number}
  1049. * @constant
  1050. */
  1051. const NormalAnimationBlendMode = 2500;
  1052. /**
  1053. * Additive animation blend mode. Can be used to layer motions on top of
  1054. * each other to build complex performances from smaller re-usable assets.
  1055. *
  1056. * @type {number}
  1057. * @constant
  1058. */
  1059. const AdditiveAnimationBlendMode = 2501;
  1060. /**
  1061. * For every three vertices draw a single triangle.
  1062. *
  1063. * @type {number}
  1064. * @constant
  1065. */
  1066. const TrianglesDrawMode = 0;
  1067. /**
  1068. * For each vertex draw a triangle from the last three vertices.
  1069. *
  1070. * @type {number}
  1071. * @constant
  1072. */
  1073. const TriangleStripDrawMode = 1;
  1074. /**
  1075. * For each vertex draw a triangle from the first vertex and the last two vertices.
  1076. *
  1077. * @type {number}
  1078. * @constant
  1079. */
  1080. const TriangleFanDrawMode = 2;
  1081. /**
  1082. * The depth value is inverted (1.0 - z) for visualization purposes.
  1083. *
  1084. * @type {number}
  1085. * @constant
  1086. */
  1087. const BasicDepthPacking = 3200;
  1088. /**
  1089. * The depth value is packed into 32 bit RGBA.
  1090. *
  1091. * @type {number}
  1092. * @constant
  1093. */
  1094. const RGBADepthPacking = 3201;
  1095. /**
  1096. * The depth value is packed into 24 bit RGB.
  1097. *
  1098. * @type {number}
  1099. * @constant
  1100. */
  1101. const RGBDepthPacking = 3202;
  1102. /**
  1103. * The depth value is packed into 16 bit RG.
  1104. *
  1105. * @type {number}
  1106. * @constant
  1107. */
  1108. const RGDepthPacking = 3203;
  1109. /**
  1110. * Normal information is relative to the underlying surface.
  1111. *
  1112. * @type {number}
  1113. * @constant
  1114. */
  1115. const TangentSpaceNormalMap = 0;
  1116. /**
  1117. * Normal information is relative to the object orientation.
  1118. *
  1119. * @type {number}
  1120. * @constant
  1121. */
  1122. const ObjectSpaceNormalMap = 1;
  1123. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1124. /**
  1125. * No color space.
  1126. *
  1127. * @type {string}
  1128. * @constant
  1129. */
  1130. const NoColorSpace = '';
  1131. /**
  1132. * sRGB color space.
  1133. *
  1134. * @type {string}
  1135. * @constant
  1136. */
  1137. const SRGBColorSpace = 'srgb';
  1138. /**
  1139. * sRGB-linear color space.
  1140. *
  1141. * @type {string}
  1142. * @constant
  1143. */
  1144. const LinearSRGBColorSpace = 'srgb-linear';
  1145. /**
  1146. * Linear transfer function.
  1147. *
  1148. * @type {string}
  1149. * @constant
  1150. */
  1151. const LinearTransfer = 'linear';
  1152. /**
  1153. * sRGB transfer function.
  1154. *
  1155. * @type {string}
  1156. * @constant
  1157. */
  1158. const SRGBTransfer = 'srgb';
  1159. /**
  1160. * No normal map packing.
  1161. *
  1162. * @type {string}
  1163. * @constant
  1164. */
  1165. const NoNormalPacking = '';
  1166. /**
  1167. * Normal RG packing.
  1168. *
  1169. * @type {string}
  1170. * @constant
  1171. */
  1172. const NormalRGPacking = 'rg';
  1173. /**
  1174. * Normal GA packing.
  1175. *
  1176. * @type {string}
  1177. * @constant
  1178. */
  1179. const NormalGAPacking = 'ga';
  1180. /**
  1181. * Sets the stencil buffer value to `0`.
  1182. *
  1183. * @type {number}
  1184. * @constant
  1185. */
  1186. const ZeroStencilOp = 0;
  1187. /**
  1188. * Keeps the current value.
  1189. *
  1190. * @type {number}
  1191. * @constant
  1192. */
  1193. const KeepStencilOp = 7680;
  1194. /**
  1195. * Sets the stencil buffer value to the specified reference value.
  1196. *
  1197. * @type {number}
  1198. * @constant
  1199. */
  1200. const ReplaceStencilOp = 7681;
  1201. /**
  1202. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1203. *
  1204. * @type {number}
  1205. * @constant
  1206. */
  1207. const IncrementStencilOp = 7682;
  1208. /**
  1209. * Decrements the current stencil buffer value. Clamps to `0`.
  1210. *
  1211. * @type {number}
  1212. * @constant
  1213. */
  1214. const DecrementStencilOp = 7683;
  1215. /**
  1216. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1217. * the maximum representable unsigned value.
  1218. *
  1219. * @type {number}
  1220. * @constant
  1221. */
  1222. const IncrementWrapStencilOp = 34055;
  1223. /**
  1224. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1225. * unsigned value when decrementing a stencil buffer value of `0`.
  1226. *
  1227. * @type {number}
  1228. * @constant
  1229. */
  1230. const DecrementWrapStencilOp = 34056;
  1231. /**
  1232. * Inverts the current stencil buffer value bitwise.
  1233. *
  1234. * @type {number}
  1235. * @constant
  1236. */
  1237. const InvertStencilOp = 5386;
  1238. /**
  1239. * Will never return true.
  1240. *
  1241. * @type {number}
  1242. * @constant
  1243. */
  1244. const NeverStencilFunc = 512;
  1245. /**
  1246. * Will return true if the stencil reference value is less than the current stencil value.
  1247. *
  1248. * @type {number}
  1249. * @constant
  1250. */
  1251. const LessStencilFunc = 513;
  1252. /**
  1253. * Will return true if the stencil reference value is equal to the current stencil value.
  1254. *
  1255. * @type {number}
  1256. * @constant
  1257. */
  1258. const EqualStencilFunc = 514;
  1259. /**
  1260. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1261. *
  1262. * @type {number}
  1263. * @constant
  1264. */
  1265. const LessEqualStencilFunc = 515;
  1266. /**
  1267. * Will return true if the stencil reference value is greater than the current stencil value.
  1268. *
  1269. * @type {number}
  1270. * @constant
  1271. */
  1272. const GreaterStencilFunc = 516;
  1273. /**
  1274. * Will return true if the stencil reference value is not equal to the current stencil value.
  1275. *
  1276. * @type {number}
  1277. * @constant
  1278. */
  1279. const NotEqualStencilFunc = 517;
  1280. /**
  1281. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1282. *
  1283. * @type {number}
  1284. * @constant
  1285. */
  1286. const GreaterEqualStencilFunc = 518;
  1287. /**
  1288. * Will always return true.
  1289. *
  1290. * @type {number}
  1291. * @constant
  1292. */
  1293. const AlwaysStencilFunc = 519;
  1294. /**
  1295. * Never pass.
  1296. *
  1297. * @type {number}
  1298. * @constant
  1299. */
  1300. const NeverCompare = 512;
  1301. /**
  1302. * Pass if the incoming value is less than the texture value.
  1303. *
  1304. * @type {number}
  1305. * @constant
  1306. */
  1307. const LessCompare = 513;
  1308. /**
  1309. * Pass if the incoming value equals the texture value.
  1310. *
  1311. * @type {number}
  1312. * @constant
  1313. */
  1314. const EqualCompare = 514;
  1315. /**
  1316. * Pass if the incoming value is less than or equal to the texture value.
  1317. *
  1318. * @type {number}
  1319. * @constant
  1320. */
  1321. const LessEqualCompare = 515;
  1322. /**
  1323. * Pass if the incoming value is greater than the texture value.
  1324. *
  1325. * @type {number}
  1326. * @constant
  1327. */
  1328. const GreaterCompare = 516;
  1329. /**
  1330. * Pass if the incoming value is not equal to the texture value.
  1331. *
  1332. * @type {number}
  1333. * @constant
  1334. */
  1335. const NotEqualCompare = 517;
  1336. /**
  1337. * Pass if the incoming value is greater than or equal to the texture value.
  1338. *
  1339. * @type {number}
  1340. * @constant
  1341. */
  1342. const GreaterEqualCompare = 518;
  1343. /**
  1344. * Always pass.
  1345. *
  1346. * @type {number}
  1347. * @constant
  1348. */
  1349. const AlwaysCompare = 519;
  1350. /**
  1351. * The contents are intended to be specified once by the application, and used many
  1352. * times as the source for drawing and image specification commands.
  1353. *
  1354. * @type {number}
  1355. * @constant
  1356. */
  1357. const StaticDrawUsage = 35044;
  1358. /**
  1359. * The contents are intended to be respecified repeatedly by the application, and
  1360. * used many times as the source for drawing and image specification commands.
  1361. *
  1362. * @type {number}
  1363. * @constant
  1364. */
  1365. const DynamicDrawUsage = 35048;
  1366. /**
  1367. * The contents are intended to be specified once by the application, and used at most
  1368. * a few times as the source for drawing and image specification commands.
  1369. *
  1370. * @type {number}
  1371. * @constant
  1372. */
  1373. const StreamDrawUsage = 35040;
  1374. /**
  1375. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1376. * many times by the application.
  1377. *
  1378. * @type {number}
  1379. * @constant
  1380. */
  1381. const StaticReadUsage = 35045;
  1382. /**
  1383. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1384. * many times by the application.
  1385. *
  1386. * @type {number}
  1387. * @constant
  1388. */
  1389. const DynamicReadUsage = 35049;
  1390. /**
  1391. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1392. * a few times by the application
  1393. *
  1394. * @type {number}
  1395. * @constant
  1396. */
  1397. const StreamReadUsage = 35041;
  1398. /**
  1399. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1400. * the source for WebGL drawing and image specification commands.
  1401. *
  1402. * @type {number}
  1403. * @constant
  1404. */
  1405. const StaticCopyUsage = 35046;
  1406. /**
  1407. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1408. * as the source for WebGL drawing and image specification commands.
  1409. *
  1410. * @type {number}
  1411. * @constant
  1412. */
  1413. const DynamicCopyUsage = 35050;
  1414. /**
  1415. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1416. * as the source for WebGL drawing and image specification commands.
  1417. *
  1418. * @type {number}
  1419. * @constant
  1420. */
  1421. const StreamCopyUsage = 35042;
  1422. /**
  1423. * GLSL 1 shader code.
  1424. *
  1425. * @type {string}
  1426. * @constant
  1427. */
  1428. const GLSL1 = '100';
  1429. /**
  1430. * GLSL 3 shader code.
  1431. *
  1432. * @type {string}
  1433. * @constant
  1434. */
  1435. const GLSL3 = '300 es';
  1436. /**
  1437. * WebGL coordinate system.
  1438. *
  1439. * @type {number}
  1440. * @constant
  1441. */
  1442. const WebGLCoordinateSystem = 2000;
  1443. /**
  1444. * WebGPU coordinate system.
  1445. *
  1446. * @type {number}
  1447. * @constant
  1448. */
  1449. const WebGPUCoordinateSystem = 2001;
  1450. /**
  1451. * Represents the different timestamp query types.
  1452. *
  1453. * @type {ConstantsTimestampQuery}
  1454. * @constant
  1455. */
  1456. const TimestampQuery = {
  1457. COMPUTE: 'compute',
  1458. RENDER: 'render'
  1459. };
  1460. /**
  1461. * Represents mouse buttons and interaction types in context of controls.
  1462. *
  1463. * @type {ConstantsInterpolationSamplingType}
  1464. * @constant
  1465. */
  1466. const InterpolationSamplingType = {
  1467. PERSPECTIVE: 'perspective',
  1468. LINEAR: 'linear',
  1469. FLAT: 'flat'
  1470. };
  1471. /**
  1472. * Represents the different interpolation sampling modes.
  1473. *
  1474. * @type {ConstantsInterpolationSamplingMode}
  1475. * @constant
  1476. */
  1477. const InterpolationSamplingMode = {
  1478. NORMAL: 'normal',
  1479. CENTROID: 'centroid',
  1480. SAMPLE: 'sample',
  1481. FIRST: 'first',
  1482. EITHER: 'either'
  1483. };
  1484. /**
  1485. * This type represents mouse buttons and interaction types in context of controls.
  1486. *
  1487. * @typedef {Object} ConstantsMouse
  1488. * @property {number} MIDDLE - The left mouse button.
  1489. * @property {number} LEFT - The middle mouse button.
  1490. * @property {number} RIGHT - The right mouse button.
  1491. * @property {number} ROTATE - A rotate interaction.
  1492. * @property {number} DOLLY - A dolly interaction.
  1493. * @property {number} PAN - A pan interaction.
  1494. **/
  1495. /**
  1496. * This type represents touch interaction types in context of controls.
  1497. *
  1498. * @typedef {Object} ConstantsTouch
  1499. * @property {number} ROTATE - A rotate interaction.
  1500. * @property {number} PAN - A pan interaction.
  1501. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1502. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1503. **/
  1504. /**
  1505. * This type represents the different timestamp query types.
  1506. *
  1507. * @typedef {Object} ConstantsTimestampQuery
  1508. * @property {string} COMPUTE - A `compute` timestamp query.
  1509. * @property {string} RENDER - A `render` timestamp query.
  1510. **/
  1511. /**
  1512. * Represents the different interpolation sampling types.
  1513. *
  1514. * @typedef {Object} ConstantsInterpolationSamplingType
  1515. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1516. * @property {string} LINEAR - Linear interpolation.
  1517. * @property {string} FLAT - Flat interpolation.
  1518. */
  1519. /**
  1520. * Represents the different interpolation sampling modes.
  1521. *
  1522. * @typedef {Object} ConstantsInterpolationSamplingMode
  1523. * @property {string} NORMAL - Normal sampling mode.
  1524. * @property {string} CENTROID - Centroid sampling mode.
  1525. * @property {string} SAMPLE - Sample-specific sampling mode.
  1526. * @property {string} FIRST - Flat interpolation using the first vertex.
  1527. * @property {string} EITHER - Flat interpolation using either vertex.
  1528. */
  1529. function arrayNeedsUint32( array ) {
  1530. // assumes larger values usually on last
  1531. for ( let i = array.length - 1; i >= 0; -- i ) {
  1532. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1533. }
  1534. return false;
  1535. }
  1536. const TYPED_ARRAYS = {
  1537. Int8Array: Int8Array,
  1538. Uint8Array: Uint8Array,
  1539. Uint8ClampedArray: Uint8ClampedArray,
  1540. Int16Array: Int16Array,
  1541. Uint16Array: Uint16Array,
  1542. Int32Array: Int32Array,
  1543. Uint32Array: Uint32Array,
  1544. Float32Array: Float32Array,
  1545. Float64Array: Float64Array
  1546. };
  1547. function getTypedArray( type, buffer ) {
  1548. return new TYPED_ARRAYS[ type ]( buffer );
  1549. }
  1550. /**
  1551. * Returns `true` if the given object is a typed array.
  1552. *
  1553. * @param {any} array - The object to check.
  1554. * @return {boolean} Whether the given object is a typed array.
  1555. */
  1556. function isTypedArray( array ) {
  1557. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1558. }
  1559. function createElementNS( name ) {
  1560. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1561. }
  1562. function createCanvasElement() {
  1563. const canvas = createElementNS( 'canvas' );
  1564. canvas.style.display = 'block';
  1565. return canvas;
  1566. }
  1567. const _cache = {};
  1568. let _setConsoleFunction = null;
  1569. function setConsoleFunction( fn ) {
  1570. _setConsoleFunction = fn;
  1571. }
  1572. function getConsoleFunction() {
  1573. return _setConsoleFunction;
  1574. }
  1575. function log( ...params ) {
  1576. const message = 'THREE.' + params.shift();
  1577. if ( _setConsoleFunction ) {
  1578. _setConsoleFunction( 'log', message, ...params );
  1579. } else {
  1580. console.log( message, ...params );
  1581. }
  1582. }
  1583. function warn( ...params ) {
  1584. const message = 'THREE.' + params.shift();
  1585. if ( _setConsoleFunction ) {
  1586. _setConsoleFunction( 'warn', message, ...params );
  1587. } else {
  1588. console.warn( message, ...params );
  1589. }
  1590. }
  1591. function error( ...params ) {
  1592. const message = 'THREE.' + params.shift();
  1593. if ( _setConsoleFunction ) {
  1594. _setConsoleFunction( 'error', message, ...params );
  1595. } else {
  1596. console.error( message, ...params );
  1597. }
  1598. }
  1599. function warnOnce( ...params ) {
  1600. const message = params.join( ' ' );
  1601. if ( message in _cache ) return;
  1602. _cache[ message ] = true;
  1603. warn( ...params );
  1604. }
  1605. function probeAsync( gl, sync, interval ) {
  1606. return new Promise( function ( resolve, reject ) {
  1607. function probe() {
  1608. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1609. case gl.WAIT_FAILED:
  1610. reject();
  1611. break;
  1612. case gl.TIMEOUT_EXPIRED:
  1613. setTimeout( probe, interval );
  1614. break;
  1615. default:
  1616. resolve();
  1617. }
  1618. }
  1619. setTimeout( probe, interval );
  1620. } );
  1621. }
  1622. /**
  1623. * This modules allows to dispatch event objects on custom JavaScript objects.
  1624. *
  1625. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1626. *
  1627. * Code Example:
  1628. * ```js
  1629. * class Car extends EventDispatcher {
  1630. * start() {
  1631. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1632. * }
  1633. *};
  1634. *
  1635. * // Using events with the custom object
  1636. * const car = new Car();
  1637. * car.addEventListener( 'start', function ( event ) {
  1638. * alert( event.message );
  1639. * } );
  1640. *
  1641. * car.start();
  1642. * ```
  1643. */
  1644. class EventDispatcher {
  1645. /**
  1646. * Adds the given event listener to the given event type.
  1647. *
  1648. * @param {string} type - The type of event to listen to.
  1649. * @param {Function} listener - The function that gets called when the event is fired.
  1650. */
  1651. addEventListener( type, listener ) {
  1652. if ( this._listeners === undefined ) this._listeners = {};
  1653. const listeners = this._listeners;
  1654. if ( listeners[ type ] === undefined ) {
  1655. listeners[ type ] = [];
  1656. }
  1657. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1658. listeners[ type ].push( listener );
  1659. }
  1660. }
  1661. /**
  1662. * Returns `true` if the given event listener has been added to the given event type.
  1663. *
  1664. * @param {string} type - The type of event.
  1665. * @param {Function} listener - The listener to check.
  1666. * @return {boolean} Whether the given event listener has been added to the given event type.
  1667. */
  1668. hasEventListener( type, listener ) {
  1669. const listeners = this._listeners;
  1670. if ( listeners === undefined ) return false;
  1671. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1672. }
  1673. /**
  1674. * Removes the given event listener from the given event type.
  1675. *
  1676. * @param {string} type - The type of event.
  1677. * @param {Function} listener - The listener to remove.
  1678. */
  1679. removeEventListener( type, listener ) {
  1680. const listeners = this._listeners;
  1681. if ( listeners === undefined ) return;
  1682. const listenerArray = listeners[ type ];
  1683. if ( listenerArray !== undefined ) {
  1684. const index = listenerArray.indexOf( listener );
  1685. if ( index !== -1 ) {
  1686. listenerArray.splice( index, 1 );
  1687. }
  1688. }
  1689. }
  1690. /**
  1691. * Dispatches an event object.
  1692. *
  1693. * @param {Object} event - The event that gets fired.
  1694. */
  1695. dispatchEvent( event ) {
  1696. const listeners = this._listeners;
  1697. if ( listeners === undefined ) return;
  1698. const listenerArray = listeners[ event.type ];
  1699. if ( listenerArray !== undefined ) {
  1700. event.target = this;
  1701. // Make a copy, in case listeners are removed while iterating.
  1702. const array = listenerArray.slice( 0 );
  1703. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1704. array[ i ].call( this, event );
  1705. }
  1706. event.target = null;
  1707. }
  1708. }
  1709. }
  1710. 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' ];
  1711. let _seed = 1234567;
  1712. const DEG2RAD = Math.PI / 180;
  1713. const RAD2DEG = 180 / Math.PI;
  1714. /**
  1715. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1716. * (universally unique identifier).
  1717. *
  1718. * @return {string} The UUID.
  1719. */
  1720. function generateUUID() {
  1721. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1722. const d0 = Math.random() * 0xffffffff | 0;
  1723. const d1 = Math.random() * 0xffffffff | 0;
  1724. const d2 = Math.random() * 0xffffffff | 0;
  1725. const d3 = Math.random() * 0xffffffff | 0;
  1726. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1727. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1728. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1729. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1730. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1731. return uuid.toLowerCase();
  1732. }
  1733. /**
  1734. * Clamps the given value between min and max.
  1735. *
  1736. * @param {number} value - The value to clamp.
  1737. * @param {number} min - The min value.
  1738. * @param {number} max - The max value.
  1739. * @return {number} The clamped value.
  1740. */
  1741. function clamp( value, min, max ) {
  1742. return Math.max( min, Math.min( max, value ) );
  1743. }
  1744. /**
  1745. * Computes the Euclidean modulo of the given parameters that
  1746. * is `( ( n % m ) + m ) % m`.
  1747. *
  1748. * @param {number} n - The first parameter.
  1749. * @param {number} m - The second parameter.
  1750. * @return {number} The Euclidean modulo.
  1751. */
  1752. function euclideanModulo( n, m ) {
  1753. // https://en.wikipedia.org/wiki/Modulo_operation
  1754. return ( ( n % m ) + m ) % m;
  1755. }
  1756. /**
  1757. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1758. * for the given value.
  1759. *
  1760. * @param {number} x - The value to be mapped.
  1761. * @param {number} a1 - Minimum value for range A.
  1762. * @param {number} a2 - Maximum value for range A.
  1763. * @param {number} b1 - Minimum value for range B.
  1764. * @param {number} b2 - Maximum value for range B.
  1765. * @return {number} The mapped value.
  1766. */
  1767. function mapLinear( x, a1, a2, b1, b2 ) {
  1768. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1769. }
  1770. /**
  1771. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1772. * between the start and end point.
  1773. *
  1774. * @param {number} x - The start point
  1775. * @param {number} y - The end point.
  1776. * @param {number} value - A value between start and end.
  1777. * @return {number} The interpolation factor.
  1778. */
  1779. function inverseLerp( x, y, value ) {
  1780. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1781. if ( x !== y ) {
  1782. return ( value - x ) / ( y - x );
  1783. } else {
  1784. return 0;
  1785. }
  1786. }
  1787. /**
  1788. * Returns a value linearly interpolated from two known points based on the given interval -
  1789. * `t = 0` will return `x` and `t = 1` will return `y`.
  1790. *
  1791. * @param {number} x - The start point
  1792. * @param {number} y - The end point.
  1793. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1794. * @return {number} The interpolated value.
  1795. */
  1796. function lerp( x, y, t ) {
  1797. return ( 1 - t ) * x + t * y;
  1798. }
  1799. /**
  1800. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1801. * time to maintain frame rate independent movement. For details, see
  1802. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1803. *
  1804. * @param {number} x - The current point.
  1805. * @param {number} y - The target point.
  1806. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1807. * and a lower value will make the movement more gradual.
  1808. * @param {number} dt - Delta time in seconds.
  1809. * @return {number} The interpolated value.
  1810. */
  1811. function damp( x, y, lambda, dt ) {
  1812. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1813. }
  1814. /**
  1815. * Returns a value that alternates between `0` and the given `length` parameter.
  1816. *
  1817. * @param {number} x - The value to pingpong.
  1818. * @param {number} [length=1] - The positive value the function will pingpong to.
  1819. * @return {number} The alternated value.
  1820. */
  1821. function pingpong( x, length = 1 ) {
  1822. // https://www.desmos.com/calculator/vcsjnyz7x4
  1823. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1824. }
  1825. /**
  1826. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1827. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1828. * the `min` and `max`.
  1829. *
  1830. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1831. *
  1832. * @param {number} x - The value to evaluate based on its position between min and max.
  1833. * @param {number} min - The min value. Any x value below min will be `0`.
  1834. * @param {number} max - The max value. Any x value above max will be `1`.
  1835. * @return {number} The alternated value.
  1836. */
  1837. function smoothstep( x, min, max ) {
  1838. if ( x <= min ) return 0;
  1839. if ( x >= max ) return 1;
  1840. x = ( x - min ) / ( max - min );
  1841. return x * x * ( 3 - 2 * x );
  1842. }
  1843. /**
  1844. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  1845. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1846. *
  1847. * @param {number} x - The value to evaluate based on its position between min and max.
  1848. * @param {number} min - The min value. Any x value below min will be `0`.
  1849. * @param {number} max - The max value. Any x value above max will be `1`.
  1850. * @return {number} The alternated value.
  1851. */
  1852. function smootherstep( x, min, max ) {
  1853. if ( x <= min ) return 0;
  1854. if ( x >= max ) return 1;
  1855. x = ( x - min ) / ( max - min );
  1856. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1857. }
  1858. /**
  1859. * Returns a random integer from `<low, high>` interval.
  1860. *
  1861. * @param {number} low - The lower value boundary.
  1862. * @param {number} high - The upper value boundary
  1863. * @return {number} A random integer.
  1864. */
  1865. function randInt( low, high ) {
  1866. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1867. }
  1868. /**
  1869. * Returns a random float from `<low, high>` interval.
  1870. *
  1871. * @param {number} low - The lower value boundary.
  1872. * @param {number} high - The upper value boundary
  1873. * @return {number} A random float.
  1874. */
  1875. function randFloat( low, high ) {
  1876. return low + Math.random() * ( high - low );
  1877. }
  1878. /**
  1879. * Returns a random integer from `<-range/2, range/2>` interval.
  1880. *
  1881. * @param {number} range - Defines the value range.
  1882. * @return {number} A random float.
  1883. */
  1884. function randFloatSpread( range ) {
  1885. return range * ( 0.5 - Math.random() );
  1886. }
  1887. /**
  1888. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1889. *
  1890. * @param {number} [s] - The integer seed.
  1891. * @return {number} A random float.
  1892. */
  1893. function seededRandom( s ) {
  1894. if ( s !== undefined ) _seed = s;
  1895. // Mulberry32 generator
  1896. let t = _seed += 0x6D2B79F5;
  1897. t = Math.imul( t ^ t >>> 15, t | 1 );
  1898. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1899. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1900. }
  1901. /**
  1902. * Converts degrees to radians.
  1903. *
  1904. * @param {number} degrees - A value in degrees.
  1905. * @return {number} The converted value in radians.
  1906. */
  1907. function degToRad( degrees ) {
  1908. return degrees * DEG2RAD;
  1909. }
  1910. /**
  1911. * Converts radians to degrees.
  1912. *
  1913. * @param {number} radians - A value in radians.
  1914. * @return {number} The converted value in degrees.
  1915. */
  1916. function radToDeg( radians ) {
  1917. return radians * RAD2DEG;
  1918. }
  1919. /**
  1920. * Returns `true` if the given number is a power of two.
  1921. *
  1922. * @param {number} value - The value to check.
  1923. * @return {boolean} Whether the given number is a power of two or not.
  1924. */
  1925. function isPowerOfTwo( value ) {
  1926. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1927. }
  1928. /**
  1929. * Returns the smallest power of two that is greater than or equal to the given number.
  1930. *
  1931. * @param {number} value - The value to find a POT for.
  1932. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1933. */
  1934. function ceilPowerOfTwo( value ) {
  1935. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1936. }
  1937. /**
  1938. * Returns the largest power of two that is less than or equal to the given number.
  1939. *
  1940. * @param {number} value - The value to find a POT for.
  1941. * @return {number} The largest power of two that is less than or equal to the given number.
  1942. */
  1943. function floorPowerOfTwo( value ) {
  1944. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1945. }
  1946. /**
  1947. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  1948. * defined by the given angles and order.
  1949. *
  1950. * Rotations are applied to the axes in the order specified by order:
  1951. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1952. *
  1953. * @param {Quaternion} q - The quaternion to set.
  1954. * @param {number} a - The rotation applied to the first axis, in radians.
  1955. * @param {number} b - The rotation applied to the second axis, in radians.
  1956. * @param {number} c - The rotation applied to the third axis, in radians.
  1957. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1958. */
  1959. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1960. const cos = Math.cos;
  1961. const sin = Math.sin;
  1962. const c2 = cos( b / 2 );
  1963. const s2 = sin( b / 2 );
  1964. const c13 = cos( ( a + c ) / 2 );
  1965. const s13 = sin( ( a + c ) / 2 );
  1966. const c1_3 = cos( ( a - c ) / 2 );
  1967. const s1_3 = sin( ( a - c ) / 2 );
  1968. const c3_1 = cos( ( c - a ) / 2 );
  1969. const s3_1 = sin( ( c - a ) / 2 );
  1970. switch ( order ) {
  1971. case 'XYX':
  1972. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1973. break;
  1974. case 'YZY':
  1975. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1976. break;
  1977. case 'ZXZ':
  1978. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1979. break;
  1980. case 'XZX':
  1981. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1982. break;
  1983. case 'YXY':
  1984. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1985. break;
  1986. case 'ZYZ':
  1987. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1988. break;
  1989. default:
  1990. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1991. }
  1992. }
  1993. /**
  1994. * Denormalizes the given value according to the given typed array.
  1995. *
  1996. * @param {number} value - The value to denormalize.
  1997. * @param {TypedArray} array - The typed array that defines the data type of the value.
  1998. * @return {number} The denormalize (float) value in the range `[0,1]`.
  1999. */
  2000. function denormalize( value, array ) {
  2001. switch ( array.constructor ) {
  2002. case Float32Array:
  2003. return value;
  2004. case Uint32Array:
  2005. return value / 4294967295.0;
  2006. case Uint16Array:
  2007. return value / 65535.0;
  2008. case Uint8Array:
  2009. return value / 255.0;
  2010. case Int32Array:
  2011. return Math.max( value / 2147483647.0, -1 );
  2012. case Int16Array:
  2013. return Math.max( value / 32767.0, -1 );
  2014. case Int8Array:
  2015. return Math.max( value / 127.0, -1 );
  2016. default:
  2017. throw new Error( 'Invalid component type.' );
  2018. }
  2019. }
  2020. /**
  2021. * Normalizes the given value according to the given typed array.
  2022. *
  2023. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2024. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2025. * @return {number} The normalize value.
  2026. */
  2027. function normalize( value, array ) {
  2028. switch ( array.constructor ) {
  2029. case Float32Array:
  2030. return value;
  2031. case Uint32Array:
  2032. return Math.round( value * 4294967295.0 );
  2033. case Uint16Array:
  2034. return Math.round( value * 65535.0 );
  2035. case Uint8Array:
  2036. return Math.round( value * 255.0 );
  2037. case Int32Array:
  2038. return Math.round( value * 2147483647.0 );
  2039. case Int16Array:
  2040. return Math.round( value * 32767.0 );
  2041. case Int8Array:
  2042. return Math.round( value * 127.0 );
  2043. default:
  2044. throw new Error( 'Invalid component type.' );
  2045. }
  2046. }
  2047. /**
  2048. * @class
  2049. * @classdesc A collection of math utility functions.
  2050. * @hideconstructor
  2051. */
  2052. const MathUtils = {
  2053. DEG2RAD: DEG2RAD,
  2054. RAD2DEG: RAD2DEG,
  2055. /**
  2056. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2057. * (universally unique identifier).
  2058. *
  2059. * @static
  2060. * @method
  2061. * @return {string} The UUID.
  2062. */
  2063. generateUUID: generateUUID,
  2064. /**
  2065. * Clamps the given value between min and max.
  2066. *
  2067. * @static
  2068. * @method
  2069. * @param {number} value - The value to clamp.
  2070. * @param {number} min - The min value.
  2071. * @param {number} max - The max value.
  2072. * @return {number} The clamped value.
  2073. */
  2074. clamp: clamp,
  2075. /**
  2076. * Computes the Euclidean modulo of the given parameters that
  2077. * is `( ( n % m ) + m ) % m`.
  2078. *
  2079. * @static
  2080. * @method
  2081. * @param {number} n - The first parameter.
  2082. * @param {number} m - The second parameter.
  2083. * @return {number} The Euclidean modulo.
  2084. */
  2085. euclideanModulo: euclideanModulo,
  2086. /**
  2087. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2088. * for the given value.
  2089. *
  2090. * @static
  2091. * @method
  2092. * @param {number} x - The value to be mapped.
  2093. * @param {number} a1 - Minimum value for range A.
  2094. * @param {number} a2 - Maximum value for range A.
  2095. * @param {number} b1 - Minimum value for range B.
  2096. * @param {number} b2 - Maximum value for range B.
  2097. * @return {number} The mapped value.
  2098. */
  2099. mapLinear: mapLinear,
  2100. /**
  2101. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2102. * between the start and end point.
  2103. *
  2104. * @static
  2105. * @method
  2106. * @param {number} x - The start point
  2107. * @param {number} y - The end point.
  2108. * @param {number} value - A value between start and end.
  2109. * @return {number} The interpolation factor.
  2110. */
  2111. inverseLerp: inverseLerp,
  2112. /**
  2113. * Returns a value linearly interpolated from two known points based on the given interval -
  2114. * `t = 0` will return `x` and `t = 1` will return `y`.
  2115. *
  2116. * @static
  2117. * @method
  2118. * @param {number} x - The start point
  2119. * @param {number} y - The end point.
  2120. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2121. * @return {number} The interpolated value.
  2122. */
  2123. lerp: lerp,
  2124. /**
  2125. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2126. * time to maintain frame rate independent movement. For details, see
  2127. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2128. *
  2129. * @static
  2130. * @method
  2131. * @param {number} x - The current point.
  2132. * @param {number} y - The target point.
  2133. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2134. * and a lower value will make the movement more gradual.
  2135. * @param {number} dt - Delta time in seconds.
  2136. * @return {number} The interpolated value.
  2137. */
  2138. damp: damp,
  2139. /**
  2140. * Returns a value that alternates between `0` and the given `length` parameter.
  2141. *
  2142. * @static
  2143. * @method
  2144. * @param {number} x - The value to pingpong.
  2145. * @param {number} [length=1] - The positive value the function will pingpong to.
  2146. * @return {number} The alternated value.
  2147. */
  2148. pingpong: pingpong,
  2149. /**
  2150. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2151. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2152. * the `min` and `max`.
  2153. *
  2154. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2155. *
  2156. * @static
  2157. * @method
  2158. * @param {number} x - The value to evaluate based on its position between min and max.
  2159. * @param {number} min - The min value. Any x value below min will be `0`.
  2160. * @param {number} max - The max value. Any x value above max will be `1`.
  2161. * @return {number} The alternated value.
  2162. */
  2163. smoothstep: smoothstep,
  2164. /**
  2165. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2166. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2167. *
  2168. * @static
  2169. * @method
  2170. * @param {number} x - The value to evaluate based on its position between min and max.
  2171. * @param {number} min - The min value. Any x value below min will be `0`.
  2172. * @param {number} max - The max value. Any x value above max will be `1`.
  2173. * @return {number} The alternated value.
  2174. */
  2175. smootherstep: smootherstep,
  2176. /**
  2177. * Returns a random integer from `<low, high>` interval.
  2178. *
  2179. * @static
  2180. * @method
  2181. * @param {number} low - The lower value boundary.
  2182. * @param {number} high - The upper value boundary
  2183. * @return {number} A random integer.
  2184. */
  2185. randInt: randInt,
  2186. /**
  2187. * Returns a random float from `<low, high>` interval.
  2188. *
  2189. * @static
  2190. * @method
  2191. * @param {number} low - The lower value boundary.
  2192. * @param {number} high - The upper value boundary
  2193. * @return {number} A random float.
  2194. */
  2195. randFloat: randFloat,
  2196. /**
  2197. * Returns a random integer from `<-range/2, range/2>` interval.
  2198. *
  2199. * @static
  2200. * @method
  2201. * @param {number} range - Defines the value range.
  2202. * @return {number} A random float.
  2203. */
  2204. randFloatSpread: randFloatSpread,
  2205. /**
  2206. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2207. *
  2208. * @static
  2209. * @method
  2210. * @param {number} [s] - The integer seed.
  2211. * @return {number} A random float.
  2212. */
  2213. seededRandom: seededRandom,
  2214. /**
  2215. * Converts degrees to radians.
  2216. *
  2217. * @static
  2218. * @method
  2219. * @param {number} degrees - A value in degrees.
  2220. * @return {number} The converted value in radians.
  2221. */
  2222. degToRad: degToRad,
  2223. /**
  2224. * Converts radians to degrees.
  2225. *
  2226. * @static
  2227. * @method
  2228. * @param {number} radians - A value in radians.
  2229. * @return {number} The converted value in degrees.
  2230. */
  2231. radToDeg: radToDeg,
  2232. /**
  2233. * Returns `true` if the given number is a power of two.
  2234. *
  2235. * @static
  2236. * @method
  2237. * @param {number} value - The value to check.
  2238. * @return {boolean} Whether the given number is a power of two or not.
  2239. */
  2240. isPowerOfTwo: isPowerOfTwo,
  2241. /**
  2242. * Returns the smallest power of two that is greater than or equal to the given number.
  2243. *
  2244. * @static
  2245. * @method
  2246. * @param {number} value - The value to find a POT for.
  2247. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2248. */
  2249. ceilPowerOfTwo: ceilPowerOfTwo,
  2250. /**
  2251. * Returns the largest power of two that is less than or equal to the given number.
  2252. *
  2253. * @static
  2254. * @method
  2255. * @param {number} value - The value to find a POT for.
  2256. * @return {number} The largest power of two that is less than or equal to the given number.
  2257. */
  2258. floorPowerOfTwo: floorPowerOfTwo,
  2259. /**
  2260. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2261. * defined by the given angles and order.
  2262. *
  2263. * Rotations are applied to the axes in the order specified by order:
  2264. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2265. *
  2266. * @static
  2267. * @method
  2268. * @param {Quaternion} q - The quaternion to set.
  2269. * @param {number} a - The rotation applied to the first axis, in radians.
  2270. * @param {number} b - The rotation applied to the second axis, in radians.
  2271. * @param {number} c - The rotation applied to the third axis, in radians.
  2272. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2273. */
  2274. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2275. /**
  2276. * Normalizes the given value according to the given typed array.
  2277. *
  2278. * @static
  2279. * @method
  2280. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2281. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2282. * @return {number} The normalize value.
  2283. */
  2284. normalize: normalize,
  2285. /**
  2286. * Denormalizes the given value according to the given typed array.
  2287. *
  2288. * @static
  2289. * @method
  2290. * @param {number} value - The value to denormalize.
  2291. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2292. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2293. */
  2294. denormalize: denormalize
  2295. };
  2296. /**
  2297. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2298. * (labeled x and y), which can be used to represent a number of things, such as:
  2299. *
  2300. * - A point in 2D space (i.e. a position on a plane).
  2301. * - A direction and length across a plane. In three.js the length will
  2302. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2303. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2304. * - Any arbitrary ordered pair of numbers.
  2305. *
  2306. * There are other things a 2D vector can be used to represent, such as
  2307. * momentum vectors, complex numbers and so on, however these are the most
  2308. * common uses in three.js.
  2309. *
  2310. * Iterating through a vector instance will yield its components `(x, y)` in
  2311. * the corresponding order.
  2312. * ```js
  2313. * const a = new THREE.Vector2( 0, 1 );
  2314. *
  2315. * //no arguments; will be initialised to (0, 0)
  2316. * const b = new THREE.Vector2( );
  2317. *
  2318. * const d = a.distanceTo( b );
  2319. * ```
  2320. */
  2321. class Vector2 {
  2322. /**
  2323. * Constructs a new 2D vector.
  2324. *
  2325. * @param {number} [x=0] - The x value of this vector.
  2326. * @param {number} [y=0] - The y value of this vector.
  2327. */
  2328. constructor( x = 0, y = 0 ) {
  2329. /**
  2330. * This flag can be used for type testing.
  2331. *
  2332. * @type {boolean}
  2333. * @readonly
  2334. * @default true
  2335. */
  2336. Vector2.prototype.isVector2 = true;
  2337. /**
  2338. * The x value of this vector.
  2339. *
  2340. * @type {number}
  2341. */
  2342. this.x = x;
  2343. /**
  2344. * The y value of this vector.
  2345. *
  2346. * @type {number}
  2347. */
  2348. this.y = y;
  2349. }
  2350. /**
  2351. * Alias for {@link Vector2#x}.
  2352. *
  2353. * @type {number}
  2354. */
  2355. get width() {
  2356. return this.x;
  2357. }
  2358. set width( value ) {
  2359. this.x = value;
  2360. }
  2361. /**
  2362. * Alias for {@link Vector2#y}.
  2363. *
  2364. * @type {number}
  2365. */
  2366. get height() {
  2367. return this.y;
  2368. }
  2369. set height( value ) {
  2370. this.y = value;
  2371. }
  2372. /**
  2373. * Sets the vector components.
  2374. *
  2375. * @param {number} x - The value of the x component.
  2376. * @param {number} y - The value of the y component.
  2377. * @return {Vector2} A reference to this vector.
  2378. */
  2379. set( x, y ) {
  2380. this.x = x;
  2381. this.y = y;
  2382. return this;
  2383. }
  2384. /**
  2385. * Sets the vector components to the same value.
  2386. *
  2387. * @param {number} scalar - The value to set for all vector components.
  2388. * @return {Vector2} A reference to this vector.
  2389. */
  2390. setScalar( scalar ) {
  2391. this.x = scalar;
  2392. this.y = scalar;
  2393. return this;
  2394. }
  2395. /**
  2396. * Sets the vector's x component to the given value
  2397. *
  2398. * @param {number} x - The value to set.
  2399. * @return {Vector2} A reference to this vector.
  2400. */
  2401. setX( x ) {
  2402. this.x = x;
  2403. return this;
  2404. }
  2405. /**
  2406. * Sets the vector's y component to the given value
  2407. *
  2408. * @param {number} y - The value to set.
  2409. * @return {Vector2} A reference to this vector.
  2410. */
  2411. setY( y ) {
  2412. this.y = y;
  2413. return this;
  2414. }
  2415. /**
  2416. * Allows to set a vector component with an index.
  2417. *
  2418. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2419. * @param {number} value - The value to set.
  2420. * @return {Vector2} A reference to this vector.
  2421. */
  2422. setComponent( index, value ) {
  2423. switch ( index ) {
  2424. case 0: this.x = value; break;
  2425. case 1: this.y = value; break;
  2426. default: throw new Error( 'index is out of range: ' + index );
  2427. }
  2428. return this;
  2429. }
  2430. /**
  2431. * Returns the value of the vector component which matches the given index.
  2432. *
  2433. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2434. * @return {number} A vector component value.
  2435. */
  2436. getComponent( index ) {
  2437. switch ( index ) {
  2438. case 0: return this.x;
  2439. case 1: return this.y;
  2440. default: throw new Error( 'index is out of range: ' + index );
  2441. }
  2442. }
  2443. /**
  2444. * Returns a new vector with copied values from this instance.
  2445. *
  2446. * @return {Vector2} A clone of this instance.
  2447. */
  2448. clone() {
  2449. return new this.constructor( this.x, this.y );
  2450. }
  2451. /**
  2452. * Copies the values of the given vector to this instance.
  2453. *
  2454. * @param {Vector2} v - The vector to copy.
  2455. * @return {Vector2} A reference to this vector.
  2456. */
  2457. copy( v ) {
  2458. this.x = v.x;
  2459. this.y = v.y;
  2460. return this;
  2461. }
  2462. /**
  2463. * Adds the given vector to this instance.
  2464. *
  2465. * @param {Vector2} v - The vector to add.
  2466. * @return {Vector2} A reference to this vector.
  2467. */
  2468. add( v ) {
  2469. this.x += v.x;
  2470. this.y += v.y;
  2471. return this;
  2472. }
  2473. /**
  2474. * Adds the given scalar value to all components of this instance.
  2475. *
  2476. * @param {number} s - The scalar to add.
  2477. * @return {Vector2} A reference to this vector.
  2478. */
  2479. addScalar( s ) {
  2480. this.x += s;
  2481. this.y += s;
  2482. return this;
  2483. }
  2484. /**
  2485. * Adds the given vectors and stores the result in this instance.
  2486. *
  2487. * @param {Vector2} a - The first vector.
  2488. * @param {Vector2} b - The second vector.
  2489. * @return {Vector2} A reference to this vector.
  2490. */
  2491. addVectors( a, b ) {
  2492. this.x = a.x + b.x;
  2493. this.y = a.y + b.y;
  2494. return this;
  2495. }
  2496. /**
  2497. * Adds the given vector scaled by the given factor to this instance.
  2498. *
  2499. * @param {Vector2} v - The vector.
  2500. * @param {number} s - The factor that scales `v`.
  2501. * @return {Vector2} A reference to this vector.
  2502. */
  2503. addScaledVector( v, s ) {
  2504. this.x += v.x * s;
  2505. this.y += v.y * s;
  2506. return this;
  2507. }
  2508. /**
  2509. * Subtracts the given vector from this instance.
  2510. *
  2511. * @param {Vector2} v - The vector to subtract.
  2512. * @return {Vector2} A reference to this vector.
  2513. */
  2514. sub( v ) {
  2515. this.x -= v.x;
  2516. this.y -= v.y;
  2517. return this;
  2518. }
  2519. /**
  2520. * Subtracts the given scalar value from all components of this instance.
  2521. *
  2522. * @param {number} s - The scalar to subtract.
  2523. * @return {Vector2} A reference to this vector.
  2524. */
  2525. subScalar( s ) {
  2526. this.x -= s;
  2527. this.y -= s;
  2528. return this;
  2529. }
  2530. /**
  2531. * Subtracts the given vectors and stores the result in this instance.
  2532. *
  2533. * @param {Vector2} a - The first vector.
  2534. * @param {Vector2} b - The second vector.
  2535. * @return {Vector2} A reference to this vector.
  2536. */
  2537. subVectors( a, b ) {
  2538. this.x = a.x - b.x;
  2539. this.y = a.y - b.y;
  2540. return this;
  2541. }
  2542. /**
  2543. * Multiplies the given vector with this instance.
  2544. *
  2545. * @param {Vector2} v - The vector to multiply.
  2546. * @return {Vector2} A reference to this vector.
  2547. */
  2548. multiply( v ) {
  2549. this.x *= v.x;
  2550. this.y *= v.y;
  2551. return this;
  2552. }
  2553. /**
  2554. * Multiplies the given scalar value with all components of this instance.
  2555. *
  2556. * @param {number} scalar - The scalar to multiply.
  2557. * @return {Vector2} A reference to this vector.
  2558. */
  2559. multiplyScalar( scalar ) {
  2560. this.x *= scalar;
  2561. this.y *= scalar;
  2562. return this;
  2563. }
  2564. /**
  2565. * Divides this instance by the given vector.
  2566. *
  2567. * @param {Vector2} v - The vector to divide.
  2568. * @return {Vector2} A reference to this vector.
  2569. */
  2570. divide( v ) {
  2571. this.x /= v.x;
  2572. this.y /= v.y;
  2573. return this;
  2574. }
  2575. /**
  2576. * Divides this vector by the given scalar.
  2577. *
  2578. * @param {number} scalar - The scalar to divide.
  2579. * @return {Vector2} A reference to this vector.
  2580. */
  2581. divideScalar( scalar ) {
  2582. return this.multiplyScalar( 1 / scalar );
  2583. }
  2584. /**
  2585. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2586. * the given 3x3 matrix.
  2587. *
  2588. * @param {Matrix3} m - The matrix to apply.
  2589. * @return {Vector2} A reference to this vector.
  2590. */
  2591. applyMatrix3( m ) {
  2592. const x = this.x, y = this.y;
  2593. const e = m.elements;
  2594. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2595. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2596. return this;
  2597. }
  2598. /**
  2599. * If this vector's x or y value is greater than the given vector's x or y
  2600. * value, replace that value with the corresponding min value.
  2601. *
  2602. * @param {Vector2} v - The vector.
  2603. * @return {Vector2} A reference to this vector.
  2604. */
  2605. min( v ) {
  2606. this.x = Math.min( this.x, v.x );
  2607. this.y = Math.min( this.y, v.y );
  2608. return this;
  2609. }
  2610. /**
  2611. * If this vector's x or y value is less than the given vector's x or y
  2612. * value, replace that value with the corresponding max value.
  2613. *
  2614. * @param {Vector2} v - The vector.
  2615. * @return {Vector2} A reference to this vector.
  2616. */
  2617. max( v ) {
  2618. this.x = Math.max( this.x, v.x );
  2619. this.y = Math.max( this.y, v.y );
  2620. return this;
  2621. }
  2622. /**
  2623. * If this vector's x or y value is greater than the max vector's x or y
  2624. * value, it is replaced by the corresponding value.
  2625. * If this vector's x or y value is less than the min vector's x or y value,
  2626. * it is replaced by the corresponding value.
  2627. *
  2628. * @param {Vector2} min - The minimum x and y values.
  2629. * @param {Vector2} max - The maximum x and y values in the desired range.
  2630. * @return {Vector2} A reference to this vector.
  2631. */
  2632. clamp( min, max ) {
  2633. // assumes min < max, componentwise
  2634. this.x = clamp( this.x, min.x, max.x );
  2635. this.y = clamp( this.y, min.y, max.y );
  2636. return this;
  2637. }
  2638. /**
  2639. * If this vector's x or y values are greater than the max value, they are
  2640. * replaced by the max value.
  2641. * If this vector's x or y values are less than the min value, they are
  2642. * replaced by the min value.
  2643. *
  2644. * @param {number} minVal - The minimum value the components will be clamped to.
  2645. * @param {number} maxVal - The maximum value the components will be clamped to.
  2646. * @return {Vector2} A reference to this vector.
  2647. */
  2648. clampScalar( minVal, maxVal ) {
  2649. this.x = clamp( this.x, minVal, maxVal );
  2650. this.y = clamp( this.y, minVal, maxVal );
  2651. return this;
  2652. }
  2653. /**
  2654. * If this vector's length is greater than the max value, it is replaced by
  2655. * the max value.
  2656. * If this vector's length is less than the min value, it is replaced by the
  2657. * min value.
  2658. *
  2659. * @param {number} min - The minimum value the vector length will be clamped to.
  2660. * @param {number} max - The maximum value the vector length will be clamped to.
  2661. * @return {Vector2} A reference to this vector.
  2662. */
  2663. clampLength( min, max ) {
  2664. const length = this.length();
  2665. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2666. }
  2667. /**
  2668. * The components of this vector are rounded down to the nearest integer value.
  2669. *
  2670. * @return {Vector2} A reference to this vector.
  2671. */
  2672. floor() {
  2673. this.x = Math.floor( this.x );
  2674. this.y = Math.floor( this.y );
  2675. return this;
  2676. }
  2677. /**
  2678. * The components of this vector are rounded up to the nearest integer value.
  2679. *
  2680. * @return {Vector2} A reference to this vector.
  2681. */
  2682. ceil() {
  2683. this.x = Math.ceil( this.x );
  2684. this.y = Math.ceil( this.y );
  2685. return this;
  2686. }
  2687. /**
  2688. * The components of this vector are rounded to the nearest integer value
  2689. *
  2690. * @return {Vector2} A reference to this vector.
  2691. */
  2692. round() {
  2693. this.x = Math.round( this.x );
  2694. this.y = Math.round( this.y );
  2695. return this;
  2696. }
  2697. /**
  2698. * The components of this vector are rounded towards zero (up if negative,
  2699. * down if positive) to an integer value.
  2700. *
  2701. * @return {Vector2} A reference to this vector.
  2702. */
  2703. roundToZero() {
  2704. this.x = Math.trunc( this.x );
  2705. this.y = Math.trunc( this.y );
  2706. return this;
  2707. }
  2708. /**
  2709. * Inverts this vector - i.e. sets x = -x and y = -y.
  2710. *
  2711. * @return {Vector2} A reference to this vector.
  2712. */
  2713. negate() {
  2714. this.x = - this.x;
  2715. this.y = - this.y;
  2716. return this;
  2717. }
  2718. /**
  2719. * Calculates the dot product of the given vector with this instance.
  2720. *
  2721. * @param {Vector2} v - The vector to compute the dot product with.
  2722. * @return {number} The result of the dot product.
  2723. */
  2724. dot( v ) {
  2725. return this.x * v.x + this.y * v.y;
  2726. }
  2727. /**
  2728. * Calculates the cross product of the given vector with this instance.
  2729. *
  2730. * @param {Vector2} v - The vector to compute the cross product with.
  2731. * @return {number} The result of the cross product.
  2732. */
  2733. cross( v ) {
  2734. return this.x * v.y - this.y * v.x;
  2735. }
  2736. /**
  2737. * Computes the square of the Euclidean length (straight-line length) from
  2738. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2739. * compare the length squared instead as it is slightly more efficient to calculate.
  2740. *
  2741. * @return {number} The square length of this vector.
  2742. */
  2743. lengthSq() {
  2744. return this.x * this.x + this.y * this.y;
  2745. }
  2746. /**
  2747. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2748. *
  2749. * @return {number} The length of this vector.
  2750. */
  2751. length() {
  2752. return Math.sqrt( this.x * this.x + this.y * this.y );
  2753. }
  2754. /**
  2755. * Computes the Manhattan length of this vector.
  2756. *
  2757. * @return {number} The length of this vector.
  2758. */
  2759. manhattanLength() {
  2760. return Math.abs( this.x ) + Math.abs( this.y );
  2761. }
  2762. /**
  2763. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2764. * with the same direction as this one, but with a vector length of `1`.
  2765. *
  2766. * @return {Vector2} A reference to this vector.
  2767. */
  2768. normalize() {
  2769. return this.divideScalar( this.length() || 1 );
  2770. }
  2771. /**
  2772. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2773. *
  2774. * @return {number} The angle in radians.
  2775. */
  2776. angle() {
  2777. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2778. return angle;
  2779. }
  2780. /**
  2781. * Returns the angle between the given vector and this instance in radians.
  2782. *
  2783. * @param {Vector2} v - The vector to compute the angle with.
  2784. * @return {number} The angle in radians.
  2785. */
  2786. angleTo( v ) {
  2787. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2788. if ( denominator === 0 ) return Math.PI / 2;
  2789. const theta = this.dot( v ) / denominator;
  2790. // clamp, to handle numerical problems
  2791. return Math.acos( clamp( theta, -1, 1 ) );
  2792. }
  2793. /**
  2794. * Computes the distance from the given vector to this instance.
  2795. *
  2796. * @param {Vector2} v - The vector to compute the distance to.
  2797. * @return {number} The distance.
  2798. */
  2799. distanceTo( v ) {
  2800. return Math.sqrt( this.distanceToSquared( v ) );
  2801. }
  2802. /**
  2803. * Computes the squared distance from the given vector to this instance.
  2804. * If you are just comparing the distance with another distance, you should compare
  2805. * the distance squared instead as it is slightly more efficient to calculate.
  2806. *
  2807. * @param {Vector2} v - The vector to compute the squared distance to.
  2808. * @return {number} The squared distance.
  2809. */
  2810. distanceToSquared( v ) {
  2811. const dx = this.x - v.x, dy = this.y - v.y;
  2812. return dx * dx + dy * dy;
  2813. }
  2814. /**
  2815. * Computes the Manhattan distance from the given vector to this instance.
  2816. *
  2817. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2818. * @return {number} The Manhattan distance.
  2819. */
  2820. manhattanDistanceTo( v ) {
  2821. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2822. }
  2823. /**
  2824. * Sets this vector to a vector with the same direction as this one, but
  2825. * with the specified length.
  2826. *
  2827. * @param {number} length - The new length of this vector.
  2828. * @return {Vector2} A reference to this vector.
  2829. */
  2830. setLength( length ) {
  2831. return this.normalize().multiplyScalar( length );
  2832. }
  2833. /**
  2834. * Linearly interpolates between the given vector and this instance, where
  2835. * alpha is the percent distance along the line - alpha = 0 will be this
  2836. * vector, and alpha = 1 will be the given one.
  2837. *
  2838. * @param {Vector2} v - The vector to interpolate towards.
  2839. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2840. * @return {Vector2} A reference to this vector.
  2841. */
  2842. lerp( v, alpha ) {
  2843. this.x += ( v.x - this.x ) * alpha;
  2844. this.y += ( v.y - this.y ) * alpha;
  2845. return this;
  2846. }
  2847. /**
  2848. * Linearly interpolates between the given vectors, where alpha is the percent
  2849. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2850. * be the second one. The result is stored in this instance.
  2851. *
  2852. * @param {Vector2} v1 - The first vector.
  2853. * @param {Vector2} v2 - The second vector.
  2854. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2855. * @return {Vector2} A reference to this vector.
  2856. */
  2857. lerpVectors( v1, v2, alpha ) {
  2858. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2859. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2860. return this;
  2861. }
  2862. /**
  2863. * Returns `true` if this vector is equal with the given one.
  2864. *
  2865. * @param {Vector2} v - The vector to test for equality.
  2866. * @return {boolean} Whether this vector is equal with the given one.
  2867. */
  2868. equals( v ) {
  2869. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2870. }
  2871. /**
  2872. * Sets this vector's x value to be `array[ offset ]` and y
  2873. * value to be `array[ offset + 1 ]`.
  2874. *
  2875. * @param {Array<number>} array - An array holding the vector component values.
  2876. * @param {number} [offset=0] - The offset into the array.
  2877. * @return {Vector2} A reference to this vector.
  2878. */
  2879. fromArray( array, offset = 0 ) {
  2880. this.x = array[ offset ];
  2881. this.y = array[ offset + 1 ];
  2882. return this;
  2883. }
  2884. /**
  2885. * Writes the components of this vector to the given array. If no array is provided,
  2886. * the method returns a new instance.
  2887. *
  2888. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2889. * @param {number} [offset=0] - Index of the first element in the array.
  2890. * @return {Array<number>} The vector components.
  2891. */
  2892. toArray( array = [], offset = 0 ) {
  2893. array[ offset ] = this.x;
  2894. array[ offset + 1 ] = this.y;
  2895. return array;
  2896. }
  2897. /**
  2898. * Sets the components of this vector from the given buffer attribute.
  2899. *
  2900. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2901. * @param {number} index - The index into the attribute.
  2902. * @return {Vector2} A reference to this vector.
  2903. */
  2904. fromBufferAttribute( attribute, index ) {
  2905. this.x = attribute.getX( index );
  2906. this.y = attribute.getY( index );
  2907. return this;
  2908. }
  2909. /**
  2910. * Rotates this vector around the given center by the given angle.
  2911. *
  2912. * @param {Vector2} center - The point around which to rotate.
  2913. * @param {number} angle - The angle to rotate, in radians.
  2914. * @return {Vector2} A reference to this vector.
  2915. */
  2916. rotateAround( center, angle ) {
  2917. const c = Math.cos( angle ), s = Math.sin( angle );
  2918. const x = this.x - center.x;
  2919. const y = this.y - center.y;
  2920. this.x = x * c - y * s + center.x;
  2921. this.y = x * s + y * c + center.y;
  2922. return this;
  2923. }
  2924. /**
  2925. * Sets each component of this vector to a pseudo-random value between `0` and
  2926. * `1`, excluding `1`.
  2927. *
  2928. * @return {Vector2} A reference to this vector.
  2929. */
  2930. random() {
  2931. this.x = Math.random();
  2932. this.y = Math.random();
  2933. return this;
  2934. }
  2935. *[ Symbol.iterator ]() {
  2936. yield this.x;
  2937. yield this.y;
  2938. }
  2939. }
  2940. /**
  2941. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2942. *
  2943. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2944. * the corresponding order.
  2945. *
  2946. * Note that three.js expects Quaternions to be normalized.
  2947. * ```js
  2948. * const quaternion = new THREE.Quaternion();
  2949. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2950. *
  2951. * const vector = new THREE.Vector3( 1, 0, 0 );
  2952. * vector.applyQuaternion( quaternion );
  2953. * ```
  2954. */
  2955. class Quaternion {
  2956. /**
  2957. * Constructs a new quaternion.
  2958. *
  2959. * @param {number} [x=0] - The x value of this quaternion.
  2960. * @param {number} [y=0] - The y value of this quaternion.
  2961. * @param {number} [z=0] - The z value of this quaternion.
  2962. * @param {number} [w=1] - The w value of this quaternion.
  2963. */
  2964. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2965. /**
  2966. * This flag can be used for type testing.
  2967. *
  2968. * @type {boolean}
  2969. * @readonly
  2970. * @default true
  2971. */
  2972. this.isQuaternion = true;
  2973. this._x = x;
  2974. this._y = y;
  2975. this._z = z;
  2976. this._w = w;
  2977. }
  2978. /**
  2979. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2980. * quaternion data are managed in flat arrays.
  2981. *
  2982. * @param {Array<number>} dst - The destination array.
  2983. * @param {number} dstOffset - An offset into the destination array.
  2984. * @param {Array<number>} src0 - The source array of the first quaternion.
  2985. * @param {number} srcOffset0 - An offset into the first source array.
  2986. * @param {Array<number>} src1 - The source array of the second quaternion.
  2987. * @param {number} srcOffset1 - An offset into the second source array.
  2988. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  2989. * @see {@link Quaternion#slerp}
  2990. */
  2991. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2992. let x0 = src0[ srcOffset0 + 0 ],
  2993. y0 = src0[ srcOffset0 + 1 ],
  2994. z0 = src0[ srcOffset0 + 2 ],
  2995. w0 = src0[ srcOffset0 + 3 ];
  2996. let x1 = src1[ srcOffset1 + 0 ],
  2997. y1 = src1[ srcOffset1 + 1 ],
  2998. z1 = src1[ srcOffset1 + 2 ],
  2999. w1 = src1[ srcOffset1 + 3 ];
  3000. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3001. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3002. if ( dot < 0 ) {
  3003. x1 = - x1;
  3004. y1 = - y1;
  3005. z1 = - z1;
  3006. w1 = - w1;
  3007. dot = - dot;
  3008. }
  3009. let s = 1 - t;
  3010. if ( dot < 0.9995 ) {
  3011. // slerp
  3012. const theta = Math.acos( dot );
  3013. const sin = Math.sin( theta );
  3014. s = Math.sin( s * theta ) / sin;
  3015. t = Math.sin( t * theta ) / sin;
  3016. x0 = x0 * s + x1 * t;
  3017. y0 = y0 * s + y1 * t;
  3018. z0 = z0 * s + z1 * t;
  3019. w0 = w0 * s + w1 * t;
  3020. } else {
  3021. // for small angles, lerp then normalize
  3022. x0 = x0 * s + x1 * t;
  3023. y0 = y0 * s + y1 * t;
  3024. z0 = z0 * s + z1 * t;
  3025. w0 = w0 * s + w1 * t;
  3026. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3027. x0 *= f;
  3028. y0 *= f;
  3029. z0 *= f;
  3030. w0 *= f;
  3031. }
  3032. }
  3033. dst[ dstOffset ] = x0;
  3034. dst[ dstOffset + 1 ] = y0;
  3035. dst[ dstOffset + 2 ] = z0;
  3036. dst[ dstOffset + 3 ] = w0;
  3037. }
  3038. /**
  3039. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3040. * in flat arrays.
  3041. *
  3042. * @param {Array<number>} dst - The destination array.
  3043. * @param {number} dstOffset - An offset into the destination array.
  3044. * @param {Array<number>} src0 - The source array of the first quaternion.
  3045. * @param {number} srcOffset0 - An offset into the first source array.
  3046. * @param {Array<number>} src1 - The source array of the second quaternion.
  3047. * @param {number} srcOffset1 - An offset into the second source array.
  3048. * @return {Array<number>} The destination array.
  3049. * @see {@link Quaternion#multiplyQuaternions}.
  3050. */
  3051. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3052. const x0 = src0[ srcOffset0 ];
  3053. const y0 = src0[ srcOffset0 + 1 ];
  3054. const z0 = src0[ srcOffset0 + 2 ];
  3055. const w0 = src0[ srcOffset0 + 3 ];
  3056. const x1 = src1[ srcOffset1 ];
  3057. const y1 = src1[ srcOffset1 + 1 ];
  3058. const z1 = src1[ srcOffset1 + 2 ];
  3059. const w1 = src1[ srcOffset1 + 3 ];
  3060. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3061. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3062. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3063. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3064. return dst;
  3065. }
  3066. /**
  3067. * The x value of this quaternion.
  3068. *
  3069. * @type {number}
  3070. * @default 0
  3071. */
  3072. get x() {
  3073. return this._x;
  3074. }
  3075. set x( value ) {
  3076. this._x = value;
  3077. this._onChangeCallback();
  3078. }
  3079. /**
  3080. * The y value of this quaternion.
  3081. *
  3082. * @type {number}
  3083. * @default 0
  3084. */
  3085. get y() {
  3086. return this._y;
  3087. }
  3088. set y( value ) {
  3089. this._y = value;
  3090. this._onChangeCallback();
  3091. }
  3092. /**
  3093. * The z value of this quaternion.
  3094. *
  3095. * @type {number}
  3096. * @default 0
  3097. */
  3098. get z() {
  3099. return this._z;
  3100. }
  3101. set z( value ) {
  3102. this._z = value;
  3103. this._onChangeCallback();
  3104. }
  3105. /**
  3106. * The w value of this quaternion.
  3107. *
  3108. * @type {number}
  3109. * @default 1
  3110. */
  3111. get w() {
  3112. return this._w;
  3113. }
  3114. set w( value ) {
  3115. this._w = value;
  3116. this._onChangeCallback();
  3117. }
  3118. /**
  3119. * Sets the quaternion components.
  3120. *
  3121. * @param {number} x - The x value of this quaternion.
  3122. * @param {number} y - The y value of this quaternion.
  3123. * @param {number} z - The z value of this quaternion.
  3124. * @param {number} w - The w value of this quaternion.
  3125. * @return {Quaternion} A reference to this quaternion.
  3126. */
  3127. set( x, y, z, w ) {
  3128. this._x = x;
  3129. this._y = y;
  3130. this._z = z;
  3131. this._w = w;
  3132. this._onChangeCallback();
  3133. return this;
  3134. }
  3135. /**
  3136. * Returns a new quaternion with copied values from this instance.
  3137. *
  3138. * @return {Quaternion} A clone of this instance.
  3139. */
  3140. clone() {
  3141. return new this.constructor( this._x, this._y, this._z, this._w );
  3142. }
  3143. /**
  3144. * Copies the values of the given quaternion to this instance.
  3145. *
  3146. * @param {Quaternion} quaternion - The quaternion to copy.
  3147. * @return {Quaternion} A reference to this quaternion.
  3148. */
  3149. copy( quaternion ) {
  3150. this._x = quaternion.x;
  3151. this._y = quaternion.y;
  3152. this._z = quaternion.z;
  3153. this._w = quaternion.w;
  3154. this._onChangeCallback();
  3155. return this;
  3156. }
  3157. /**
  3158. * Sets this quaternion from the rotation specified by the given
  3159. * Euler angles.
  3160. *
  3161. * @param {Euler} euler - The Euler angles.
  3162. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3163. * @return {Quaternion} A reference to this quaternion.
  3164. */
  3165. setFromEuler( euler, update = true ) {
  3166. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3167. // http://www.mathworks.com/matlabcentral/fileexchange/
  3168. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3169. // content/SpinCalc.m
  3170. const cos = Math.cos;
  3171. const sin = Math.sin;
  3172. const c1 = cos( x / 2 );
  3173. const c2 = cos( y / 2 );
  3174. const c3 = cos( z / 2 );
  3175. const s1 = sin( x / 2 );
  3176. const s2 = sin( y / 2 );
  3177. const s3 = sin( z / 2 );
  3178. switch ( order ) {
  3179. case 'XYZ':
  3180. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3181. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3182. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3183. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3184. break;
  3185. case 'YXZ':
  3186. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3187. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3188. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3189. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3190. break;
  3191. case 'ZXY':
  3192. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3193. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3194. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3195. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3196. break;
  3197. case 'ZYX':
  3198. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3199. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3200. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3201. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3202. break;
  3203. case 'YZX':
  3204. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3205. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3206. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3207. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3208. break;
  3209. case 'XZY':
  3210. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3211. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3212. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3213. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3214. break;
  3215. default:
  3216. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3217. }
  3218. if ( update === true ) this._onChangeCallback();
  3219. return this;
  3220. }
  3221. /**
  3222. * Sets this quaternion from the given axis and angle.
  3223. *
  3224. * @param {Vector3} axis - The normalized axis.
  3225. * @param {number} angle - The angle in radians.
  3226. * @return {Quaternion} A reference to this quaternion.
  3227. */
  3228. setFromAxisAngle( axis, angle ) {
  3229. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3230. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3231. this._x = axis.x * s;
  3232. this._y = axis.y * s;
  3233. this._z = axis.z * s;
  3234. this._w = Math.cos( halfAngle );
  3235. this._onChangeCallback();
  3236. return this;
  3237. }
  3238. /**
  3239. * Sets this quaternion from the given rotation matrix.
  3240. *
  3241. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3242. * @return {Quaternion} A reference to this quaternion.
  3243. */
  3244. setFromRotationMatrix( m ) {
  3245. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3246. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3247. const te = m.elements,
  3248. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3249. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3250. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3251. trace = m11 + m22 + m33;
  3252. if ( trace > 0 ) {
  3253. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3254. this._w = 0.25 / s;
  3255. this._x = ( m32 - m23 ) * s;
  3256. this._y = ( m13 - m31 ) * s;
  3257. this._z = ( m21 - m12 ) * s;
  3258. } else if ( m11 > m22 && m11 > m33 ) {
  3259. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3260. this._w = ( m32 - m23 ) / s;
  3261. this._x = 0.25 * s;
  3262. this._y = ( m12 + m21 ) / s;
  3263. this._z = ( m13 + m31 ) / s;
  3264. } else if ( m22 > m33 ) {
  3265. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3266. this._w = ( m13 - m31 ) / s;
  3267. this._x = ( m12 + m21 ) / s;
  3268. this._y = 0.25 * s;
  3269. this._z = ( m23 + m32 ) / s;
  3270. } else {
  3271. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3272. this._w = ( m21 - m12 ) / s;
  3273. this._x = ( m13 + m31 ) / s;
  3274. this._y = ( m23 + m32 ) / s;
  3275. this._z = 0.25 * s;
  3276. }
  3277. this._onChangeCallback();
  3278. return this;
  3279. }
  3280. /**
  3281. * Sets this quaternion to the rotation required to rotate the direction vector
  3282. * `vFrom` to the direction vector `vTo`.
  3283. *
  3284. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3285. * @param {Vector3} vTo - The second (normalized) direction vector.
  3286. * @return {Quaternion} A reference to this quaternion.
  3287. */
  3288. setFromUnitVectors( vFrom, vTo ) {
  3289. // assumes direction vectors vFrom and vTo are normalized
  3290. let r = vFrom.dot( vTo ) + 1;
  3291. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3292. // vFrom and vTo point in opposite directions
  3293. r = 0;
  3294. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3295. this._x = - vFrom.y;
  3296. this._y = vFrom.x;
  3297. this._z = 0;
  3298. this._w = r;
  3299. } else {
  3300. this._x = 0;
  3301. this._y = - vFrom.z;
  3302. this._z = vFrom.y;
  3303. this._w = r;
  3304. }
  3305. } else {
  3306. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3307. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3308. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3309. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3310. this._w = r;
  3311. }
  3312. return this.normalize();
  3313. }
  3314. /**
  3315. * Returns the angle between this quaternion and the given one in radians.
  3316. *
  3317. * @param {Quaternion} q - The quaternion to compute the angle with.
  3318. * @return {number} The angle in radians.
  3319. */
  3320. angleTo( q ) {
  3321. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3322. }
  3323. /**
  3324. * Rotates this quaternion by a given angular step to the given quaternion.
  3325. * The method ensures that the final quaternion will not overshoot `q`.
  3326. *
  3327. * @param {Quaternion} q - The target quaternion.
  3328. * @param {number} step - The angular step in radians.
  3329. * @return {Quaternion} A reference to this quaternion.
  3330. */
  3331. rotateTowards( q, step ) {
  3332. const angle = this.angleTo( q );
  3333. if ( angle === 0 ) return this;
  3334. const t = Math.min( 1, step / angle );
  3335. this.slerp( q, t );
  3336. return this;
  3337. }
  3338. /**
  3339. * Sets this quaternion to the identity quaternion; that is, to the
  3340. * quaternion that represents "no rotation".
  3341. *
  3342. * @return {Quaternion} A reference to this quaternion.
  3343. */
  3344. identity() {
  3345. return this.set( 0, 0, 0, 1 );
  3346. }
  3347. /**
  3348. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3349. * quaternion is assumed to have unit length.
  3350. *
  3351. * @return {Quaternion} A reference to this quaternion.
  3352. */
  3353. invert() {
  3354. return this.conjugate();
  3355. }
  3356. /**
  3357. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3358. * quaternion represents the same rotation in the opposite direction about
  3359. * the rotational axis.
  3360. *
  3361. * @return {Quaternion} A reference to this quaternion.
  3362. */
  3363. conjugate() {
  3364. this._x *= -1;
  3365. this._y *= -1;
  3366. this._z *= -1;
  3367. this._onChangeCallback();
  3368. return this;
  3369. }
  3370. /**
  3371. * Calculates the dot product of this quaternion and the given one.
  3372. *
  3373. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3374. * @return {number} The result of the dot product.
  3375. */
  3376. dot( v ) {
  3377. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3378. }
  3379. /**
  3380. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3381. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3382. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3383. * {@link Quaternion#length}.
  3384. *
  3385. * @return {number} The squared Euclidean length.
  3386. */
  3387. lengthSq() {
  3388. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3389. }
  3390. /**
  3391. * Computes the Euclidean length (straight-line length) of this quaternion,
  3392. * considered as a 4 dimensional vector.
  3393. *
  3394. * @return {number} The Euclidean length.
  3395. */
  3396. length() {
  3397. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3398. }
  3399. /**
  3400. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3401. * the same rotation as this one, but has a length equal to `1`.
  3402. *
  3403. * @return {Quaternion} A reference to this quaternion.
  3404. */
  3405. normalize() {
  3406. let l = this.length();
  3407. if ( l === 0 ) {
  3408. this._x = 0;
  3409. this._y = 0;
  3410. this._z = 0;
  3411. this._w = 1;
  3412. } else {
  3413. l = 1 / l;
  3414. this._x = this._x * l;
  3415. this._y = this._y * l;
  3416. this._z = this._z * l;
  3417. this._w = this._w * l;
  3418. }
  3419. this._onChangeCallback();
  3420. return this;
  3421. }
  3422. /**
  3423. * Multiplies this quaternion by the given one.
  3424. *
  3425. * @param {Quaternion} q - The quaternion.
  3426. * @return {Quaternion} A reference to this quaternion.
  3427. */
  3428. multiply( q ) {
  3429. return this.multiplyQuaternions( this, q );
  3430. }
  3431. /**
  3432. * Pre-multiplies this quaternion by the given one.
  3433. *
  3434. * @param {Quaternion} q - The quaternion.
  3435. * @return {Quaternion} A reference to this quaternion.
  3436. */
  3437. premultiply( q ) {
  3438. return this.multiplyQuaternions( q, this );
  3439. }
  3440. /**
  3441. * Multiplies the given quaternions and stores the result in this instance.
  3442. *
  3443. * @param {Quaternion} a - The first quaternion.
  3444. * @param {Quaternion} b - The second quaternion.
  3445. * @return {Quaternion} A reference to this quaternion.
  3446. */
  3447. multiplyQuaternions( a, b ) {
  3448. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3449. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3450. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3451. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3452. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3453. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3454. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3455. this._onChangeCallback();
  3456. return this;
  3457. }
  3458. /**
  3459. * Performs a spherical linear interpolation between this quaternion and the target quaternion.
  3460. *
  3461. * @param {Quaternion} qb - The target quaternion.
  3462. * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate.
  3463. * @return {Quaternion} A reference to this quaternion.
  3464. */
  3465. slerp( qb, t ) {
  3466. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3467. let dot = this.dot( qb );
  3468. if ( dot < 0 ) {
  3469. x = - x;
  3470. y = - y;
  3471. z = - z;
  3472. w = - w;
  3473. dot = - dot;
  3474. }
  3475. let s = 1 - t;
  3476. if ( dot < 0.9995 ) {
  3477. // slerp
  3478. const theta = Math.acos( dot );
  3479. const sin = Math.sin( theta );
  3480. s = Math.sin( s * theta ) / sin;
  3481. t = Math.sin( t * theta ) / sin;
  3482. this._x = this._x * s + x * t;
  3483. this._y = this._y * s + y * t;
  3484. this._z = this._z * s + z * t;
  3485. this._w = this._w * s + w * t;
  3486. this._onChangeCallback();
  3487. } else {
  3488. // for small angles, lerp then normalize
  3489. this._x = this._x * s + x * t;
  3490. this._y = this._y * s + y * t;
  3491. this._z = this._z * s + z * t;
  3492. this._w = this._w * s + w * t;
  3493. this.normalize(); // normalize calls _onChangeCallback()
  3494. }
  3495. return this;
  3496. }
  3497. /**
  3498. * Performs a spherical linear interpolation between the given quaternions
  3499. * and stores the result in this quaternion.
  3500. *
  3501. * @param {Quaternion} qa - The source quaternion.
  3502. * @param {Quaternion} qb - The target quaternion.
  3503. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3504. * @return {Quaternion} A reference to this quaternion.
  3505. */
  3506. slerpQuaternions( qa, qb, t ) {
  3507. return this.copy( qa ).slerp( qb, t );
  3508. }
  3509. /**
  3510. * Sets this quaternion to a uniformly random, normalized quaternion.
  3511. *
  3512. * @return {Quaternion} A reference to this quaternion.
  3513. */
  3514. random() {
  3515. // Ken Shoemake
  3516. // Uniform random rotations
  3517. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3518. const theta1 = 2 * Math.PI * Math.random();
  3519. const theta2 = 2 * Math.PI * Math.random();
  3520. const x0 = Math.random();
  3521. const r1 = Math.sqrt( 1 - x0 );
  3522. const r2 = Math.sqrt( x0 );
  3523. return this.set(
  3524. r1 * Math.sin( theta1 ),
  3525. r1 * Math.cos( theta1 ),
  3526. r2 * Math.sin( theta2 ),
  3527. r2 * Math.cos( theta2 ),
  3528. );
  3529. }
  3530. /**
  3531. * Returns `true` if this quaternion is equal with the given one.
  3532. *
  3533. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3534. * @return {boolean} Whether this quaternion is equal with the given one.
  3535. */
  3536. equals( quaternion ) {
  3537. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3538. }
  3539. /**
  3540. * Sets this quaternion's components from the given array.
  3541. *
  3542. * @param {Array<number>} array - An array holding the quaternion component values.
  3543. * @param {number} [offset=0] - The offset into the array.
  3544. * @return {Quaternion} A reference to this quaternion.
  3545. */
  3546. fromArray( array, offset = 0 ) {
  3547. this._x = array[ offset ];
  3548. this._y = array[ offset + 1 ];
  3549. this._z = array[ offset + 2 ];
  3550. this._w = array[ offset + 3 ];
  3551. this._onChangeCallback();
  3552. return this;
  3553. }
  3554. /**
  3555. * Writes the components of this quaternion to the given array. If no array is provided,
  3556. * the method returns a new instance.
  3557. *
  3558. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3559. * @param {number} [offset=0] - Index of the first element in the array.
  3560. * @return {Array<number>} The quaternion components.
  3561. */
  3562. toArray( array = [], offset = 0 ) {
  3563. array[ offset ] = this._x;
  3564. array[ offset + 1 ] = this._y;
  3565. array[ offset + 2 ] = this._z;
  3566. array[ offset + 3 ] = this._w;
  3567. return array;
  3568. }
  3569. /**
  3570. * Sets the components of this quaternion from the given buffer attribute.
  3571. *
  3572. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3573. * @param {number} index - The index into the attribute.
  3574. * @return {Quaternion} A reference to this quaternion.
  3575. */
  3576. fromBufferAttribute( attribute, index ) {
  3577. this._x = attribute.getX( index );
  3578. this._y = attribute.getY( index );
  3579. this._z = attribute.getZ( index );
  3580. this._w = attribute.getW( index );
  3581. this._onChangeCallback();
  3582. return this;
  3583. }
  3584. /**
  3585. * This methods defines the serialization result of this class. Returns the
  3586. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3587. *
  3588. * @return {Array<number>} The serialized quaternion.
  3589. */
  3590. toJSON() {
  3591. return this.toArray();
  3592. }
  3593. _onChange( callback ) {
  3594. this._onChangeCallback = callback;
  3595. return this;
  3596. }
  3597. _onChangeCallback() {}
  3598. *[ Symbol.iterator ]() {
  3599. yield this._x;
  3600. yield this._y;
  3601. yield this._z;
  3602. yield this._w;
  3603. }
  3604. }
  3605. /**
  3606. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3607. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3608. *
  3609. * - A point in 3D space.
  3610. * - A direction and length in 3D space. In three.js the length will
  3611. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3612. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3613. * - Any arbitrary ordered triplet of numbers.
  3614. *
  3615. * There are other things a 3D vector can be used to represent, such as
  3616. * momentum vectors and so on, however these are the most
  3617. * common uses in three.js.
  3618. *
  3619. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3620. * the corresponding order.
  3621. * ```js
  3622. * const a = new THREE.Vector3( 0, 1, 0 );
  3623. *
  3624. * //no arguments; will be initialised to (0, 0, 0)
  3625. * const b = new THREE.Vector3( );
  3626. *
  3627. * const d = a.distanceTo( b );
  3628. * ```
  3629. */
  3630. class Vector3 {
  3631. /**
  3632. * Constructs a new 3D vector.
  3633. *
  3634. * @param {number} [x=0] - The x value of this vector.
  3635. * @param {number} [y=0] - The y value of this vector.
  3636. * @param {number} [z=0] - The z value of this vector.
  3637. */
  3638. constructor( x = 0, y = 0, z = 0 ) {
  3639. /**
  3640. * This flag can be used for type testing.
  3641. *
  3642. * @type {boolean}
  3643. * @readonly
  3644. * @default true
  3645. */
  3646. Vector3.prototype.isVector3 = true;
  3647. /**
  3648. * The x value of this vector.
  3649. *
  3650. * @type {number}
  3651. */
  3652. this.x = x;
  3653. /**
  3654. * The y value of this vector.
  3655. *
  3656. * @type {number}
  3657. */
  3658. this.y = y;
  3659. /**
  3660. * The z value of this vector.
  3661. *
  3662. * @type {number}
  3663. */
  3664. this.z = z;
  3665. }
  3666. /**
  3667. * Sets the vector components.
  3668. *
  3669. * @param {number} x - The value of the x component.
  3670. * @param {number} y - The value of the y component.
  3671. * @param {number} z - The value of the z component.
  3672. * @return {Vector3} A reference to this vector.
  3673. */
  3674. set( x, y, z ) {
  3675. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3676. this.x = x;
  3677. this.y = y;
  3678. this.z = z;
  3679. return this;
  3680. }
  3681. /**
  3682. * Sets the vector components to the same value.
  3683. *
  3684. * @param {number} scalar - The value to set for all vector components.
  3685. * @return {Vector3} A reference to this vector.
  3686. */
  3687. setScalar( scalar ) {
  3688. this.x = scalar;
  3689. this.y = scalar;
  3690. this.z = scalar;
  3691. return this;
  3692. }
  3693. /**
  3694. * Sets the vector's x component to the given value
  3695. *
  3696. * @param {number} x - The value to set.
  3697. * @return {Vector3} A reference to this vector.
  3698. */
  3699. setX( x ) {
  3700. this.x = x;
  3701. return this;
  3702. }
  3703. /**
  3704. * Sets the vector's y component to the given value
  3705. *
  3706. * @param {number} y - The value to set.
  3707. * @return {Vector3} A reference to this vector.
  3708. */
  3709. setY( y ) {
  3710. this.y = y;
  3711. return this;
  3712. }
  3713. /**
  3714. * Sets the vector's z component to the given value
  3715. *
  3716. * @param {number} z - The value to set.
  3717. * @return {Vector3} A reference to this vector.
  3718. */
  3719. setZ( z ) {
  3720. this.z = z;
  3721. return this;
  3722. }
  3723. /**
  3724. * Allows to set a vector component with an index.
  3725. *
  3726. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3727. * @param {number} value - The value to set.
  3728. * @return {Vector3} A reference to this vector.
  3729. */
  3730. setComponent( index, value ) {
  3731. switch ( index ) {
  3732. case 0: this.x = value; break;
  3733. case 1: this.y = value; break;
  3734. case 2: this.z = value; break;
  3735. default: throw new Error( 'index is out of range: ' + index );
  3736. }
  3737. return this;
  3738. }
  3739. /**
  3740. * Returns the value of the vector component which matches the given index.
  3741. *
  3742. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3743. * @return {number} A vector component value.
  3744. */
  3745. getComponent( index ) {
  3746. switch ( index ) {
  3747. case 0: return this.x;
  3748. case 1: return this.y;
  3749. case 2: return this.z;
  3750. default: throw new Error( 'index is out of range: ' + index );
  3751. }
  3752. }
  3753. /**
  3754. * Returns a new vector with copied values from this instance.
  3755. *
  3756. * @return {Vector3} A clone of this instance.
  3757. */
  3758. clone() {
  3759. return new this.constructor( this.x, this.y, this.z );
  3760. }
  3761. /**
  3762. * Copies the values of the given vector to this instance.
  3763. *
  3764. * @param {Vector3} v - The vector to copy.
  3765. * @return {Vector3} A reference to this vector.
  3766. */
  3767. copy( v ) {
  3768. this.x = v.x;
  3769. this.y = v.y;
  3770. this.z = v.z;
  3771. return this;
  3772. }
  3773. /**
  3774. * Adds the given vector to this instance.
  3775. *
  3776. * @param {Vector3} v - The vector to add.
  3777. * @return {Vector3} A reference to this vector.
  3778. */
  3779. add( v ) {
  3780. this.x += v.x;
  3781. this.y += v.y;
  3782. this.z += v.z;
  3783. return this;
  3784. }
  3785. /**
  3786. * Adds the given scalar value to all components of this instance.
  3787. *
  3788. * @param {number} s - The scalar to add.
  3789. * @return {Vector3} A reference to this vector.
  3790. */
  3791. addScalar( s ) {
  3792. this.x += s;
  3793. this.y += s;
  3794. this.z += s;
  3795. return this;
  3796. }
  3797. /**
  3798. * Adds the given vectors and stores the result in this instance.
  3799. *
  3800. * @param {Vector3} a - The first vector.
  3801. * @param {Vector3} b - The second vector.
  3802. * @return {Vector3} A reference to this vector.
  3803. */
  3804. addVectors( a, b ) {
  3805. this.x = a.x + b.x;
  3806. this.y = a.y + b.y;
  3807. this.z = a.z + b.z;
  3808. return this;
  3809. }
  3810. /**
  3811. * Adds the given vector scaled by the given factor to this instance.
  3812. *
  3813. * @param {Vector3|Vector4} v - The vector.
  3814. * @param {number} s - The factor that scales `v`.
  3815. * @return {Vector3} A reference to this vector.
  3816. */
  3817. addScaledVector( v, s ) {
  3818. this.x += v.x * s;
  3819. this.y += v.y * s;
  3820. this.z += v.z * s;
  3821. return this;
  3822. }
  3823. /**
  3824. * Subtracts the given vector from this instance.
  3825. *
  3826. * @param {Vector3} v - The vector to subtract.
  3827. * @return {Vector3} A reference to this vector.
  3828. */
  3829. sub( v ) {
  3830. this.x -= v.x;
  3831. this.y -= v.y;
  3832. this.z -= v.z;
  3833. return this;
  3834. }
  3835. /**
  3836. * Subtracts the given scalar value from all components of this instance.
  3837. *
  3838. * @param {number} s - The scalar to subtract.
  3839. * @return {Vector3} A reference to this vector.
  3840. */
  3841. subScalar( s ) {
  3842. this.x -= s;
  3843. this.y -= s;
  3844. this.z -= s;
  3845. return this;
  3846. }
  3847. /**
  3848. * Subtracts the given vectors and stores the result in this instance.
  3849. *
  3850. * @param {Vector3} a - The first vector.
  3851. * @param {Vector3} b - The second vector.
  3852. * @return {Vector3} A reference to this vector.
  3853. */
  3854. subVectors( a, b ) {
  3855. this.x = a.x - b.x;
  3856. this.y = a.y - b.y;
  3857. this.z = a.z - b.z;
  3858. return this;
  3859. }
  3860. /**
  3861. * Multiplies the given vector with this instance.
  3862. *
  3863. * @param {Vector3} v - The vector to multiply.
  3864. * @return {Vector3} A reference to this vector.
  3865. */
  3866. multiply( v ) {
  3867. this.x *= v.x;
  3868. this.y *= v.y;
  3869. this.z *= v.z;
  3870. return this;
  3871. }
  3872. /**
  3873. * Multiplies the given scalar value with all components of this instance.
  3874. *
  3875. * @param {number} scalar - The scalar to multiply.
  3876. * @return {Vector3} A reference to this vector.
  3877. */
  3878. multiplyScalar( scalar ) {
  3879. this.x *= scalar;
  3880. this.y *= scalar;
  3881. this.z *= scalar;
  3882. return this;
  3883. }
  3884. /**
  3885. * Multiplies the given vectors and stores the result in this instance.
  3886. *
  3887. * @param {Vector3} a - The first vector.
  3888. * @param {Vector3} b - The second vector.
  3889. * @return {Vector3} A reference to this vector.
  3890. */
  3891. multiplyVectors( a, b ) {
  3892. this.x = a.x * b.x;
  3893. this.y = a.y * b.y;
  3894. this.z = a.z * b.z;
  3895. return this;
  3896. }
  3897. /**
  3898. * Applies the given Euler rotation to this vector.
  3899. *
  3900. * @param {Euler} euler - The Euler angles.
  3901. * @return {Vector3} A reference to this vector.
  3902. */
  3903. applyEuler( euler ) {
  3904. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3905. }
  3906. /**
  3907. * Applies a rotation specified by an axis and an angle to this vector.
  3908. *
  3909. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3910. * @param {number} angle - The angle in radians.
  3911. * @return {Vector3} A reference to this vector.
  3912. */
  3913. applyAxisAngle( axis, angle ) {
  3914. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3915. }
  3916. /**
  3917. * Multiplies this vector with the given 3x3 matrix.
  3918. *
  3919. * @param {Matrix3} m - The 3x3 matrix.
  3920. * @return {Vector3} A reference to this vector.
  3921. */
  3922. applyMatrix3( m ) {
  3923. const x = this.x, y = this.y, z = this.z;
  3924. const e = m.elements;
  3925. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3926. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3927. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3928. return this;
  3929. }
  3930. /**
  3931. * Multiplies this vector by the given normal matrix and normalizes
  3932. * the result.
  3933. *
  3934. * @param {Matrix3} m - The normal matrix.
  3935. * @return {Vector3} A reference to this vector.
  3936. */
  3937. applyNormalMatrix( m ) {
  3938. return this.applyMatrix3( m ).normalize();
  3939. }
  3940. /**
  3941. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3942. * divides by perspective.
  3943. *
  3944. * @param {Matrix4} m - The matrix to apply.
  3945. * @return {Vector3} A reference to this vector.
  3946. */
  3947. applyMatrix4( m ) {
  3948. const x = this.x, y = this.y, z = this.z;
  3949. const e = m.elements;
  3950. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3951. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3952. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3953. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3954. return this;
  3955. }
  3956. /**
  3957. * Applies the given Quaternion to this vector.
  3958. *
  3959. * @param {Quaternion} q - The Quaternion.
  3960. * @return {Vector3} A reference to this vector.
  3961. */
  3962. applyQuaternion( q ) {
  3963. // quaternion q is assumed to have unit length
  3964. const vx = this.x, vy = this.y, vz = this.z;
  3965. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3966. // t = 2 * cross( q.xyz, v );
  3967. const tx = 2 * ( qy * vz - qz * vy );
  3968. const ty = 2 * ( qz * vx - qx * vz );
  3969. const tz = 2 * ( qx * vy - qy * vx );
  3970. // v + q.w * t + cross( q.xyz, t );
  3971. this.x = vx + qw * tx + qy * tz - qz * ty;
  3972. this.y = vy + qw * ty + qz * tx - qx * tz;
  3973. this.z = vz + qw * tz + qx * ty - qy * tx;
  3974. return this;
  3975. }
  3976. /**
  3977. * Projects this vector from world space into the camera's normalized
  3978. * device coordinate (NDC) space.
  3979. *
  3980. * @param {Camera} camera - The camera.
  3981. * @return {Vector3} A reference to this vector.
  3982. */
  3983. project( camera ) {
  3984. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  3985. }
  3986. /**
  3987. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  3988. * space into world space.
  3989. *
  3990. * @param {Camera} camera - The camera.
  3991. * @return {Vector3} A reference to this vector.
  3992. */
  3993. unproject( camera ) {
  3994. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  3995. }
  3996. /**
  3997. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  3998. * subset of the given 4x4 matrix and then normalizes the result.
  3999. *
  4000. * @param {Matrix4} m - The matrix.
  4001. * @return {Vector3} A reference to this vector.
  4002. */
  4003. transformDirection( m ) {
  4004. // input: THREE.Matrix4 affine matrix
  4005. // vector interpreted as a direction
  4006. const x = this.x, y = this.y, z = this.z;
  4007. const e = m.elements;
  4008. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4009. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4010. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4011. return this.normalize();
  4012. }
  4013. /**
  4014. * Divides this instance by the given vector.
  4015. *
  4016. * @param {Vector3} v - The vector to divide.
  4017. * @return {Vector3} A reference to this vector.
  4018. */
  4019. divide( v ) {
  4020. this.x /= v.x;
  4021. this.y /= v.y;
  4022. this.z /= v.z;
  4023. return this;
  4024. }
  4025. /**
  4026. * Divides this vector by the given scalar.
  4027. *
  4028. * @param {number} scalar - The scalar to divide.
  4029. * @return {Vector3} A reference to this vector.
  4030. */
  4031. divideScalar( scalar ) {
  4032. return this.multiplyScalar( 1 / scalar );
  4033. }
  4034. /**
  4035. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4036. * value, replace that value with the corresponding min value.
  4037. *
  4038. * @param {Vector3} v - The vector.
  4039. * @return {Vector3} A reference to this vector.
  4040. */
  4041. min( v ) {
  4042. this.x = Math.min( this.x, v.x );
  4043. this.y = Math.min( this.y, v.y );
  4044. this.z = Math.min( this.z, v.z );
  4045. return this;
  4046. }
  4047. /**
  4048. * If this vector's x, y or z value is less than the given vector's x, y or z
  4049. * value, replace that value with the corresponding max value.
  4050. *
  4051. * @param {Vector3} v - The vector.
  4052. * @return {Vector3} A reference to this vector.
  4053. */
  4054. max( v ) {
  4055. this.x = Math.max( this.x, v.x );
  4056. this.y = Math.max( this.y, v.y );
  4057. this.z = Math.max( this.z, v.z );
  4058. return this;
  4059. }
  4060. /**
  4061. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4062. * value, it is replaced by the corresponding value.
  4063. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4064. * it is replaced by the corresponding value.
  4065. *
  4066. * @param {Vector3} min - The minimum x, y and z values.
  4067. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4068. * @return {Vector3} A reference to this vector.
  4069. */
  4070. clamp( min, max ) {
  4071. // assumes min < max, componentwise
  4072. this.x = clamp( this.x, min.x, max.x );
  4073. this.y = clamp( this.y, min.y, max.y );
  4074. this.z = clamp( this.z, min.z, max.z );
  4075. return this;
  4076. }
  4077. /**
  4078. * If this vector's x, y or z values are greater than the max value, they are
  4079. * replaced by the max value.
  4080. * If this vector's x, y or z values are less than the min value, they are
  4081. * replaced by the min value.
  4082. *
  4083. * @param {number} minVal - The minimum value the components will be clamped to.
  4084. * @param {number} maxVal - The maximum value the components will be clamped to.
  4085. * @return {Vector3} A reference to this vector.
  4086. */
  4087. clampScalar( minVal, maxVal ) {
  4088. this.x = clamp( this.x, minVal, maxVal );
  4089. this.y = clamp( this.y, minVal, maxVal );
  4090. this.z = clamp( this.z, minVal, maxVal );
  4091. return this;
  4092. }
  4093. /**
  4094. * If this vector's length is greater than the max value, it is replaced by
  4095. * the max value.
  4096. * If this vector's length is less than the min value, it is replaced by the
  4097. * min value.
  4098. *
  4099. * @param {number} min - The minimum value the vector length will be clamped to.
  4100. * @param {number} max - The maximum value the vector length will be clamped to.
  4101. * @return {Vector3} A reference to this vector.
  4102. */
  4103. clampLength( min, max ) {
  4104. const length = this.length();
  4105. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4106. }
  4107. /**
  4108. * The components of this vector are rounded down to the nearest integer value.
  4109. *
  4110. * @return {Vector3} A reference to this vector.
  4111. */
  4112. floor() {
  4113. this.x = Math.floor( this.x );
  4114. this.y = Math.floor( this.y );
  4115. this.z = Math.floor( this.z );
  4116. return this;
  4117. }
  4118. /**
  4119. * The components of this vector are rounded up to the nearest integer value.
  4120. *
  4121. * @return {Vector3} A reference to this vector.
  4122. */
  4123. ceil() {
  4124. this.x = Math.ceil( this.x );
  4125. this.y = Math.ceil( this.y );
  4126. this.z = Math.ceil( this.z );
  4127. return this;
  4128. }
  4129. /**
  4130. * The components of this vector are rounded to the nearest integer value
  4131. *
  4132. * @return {Vector3} A reference to this vector.
  4133. */
  4134. round() {
  4135. this.x = Math.round( this.x );
  4136. this.y = Math.round( this.y );
  4137. this.z = Math.round( this.z );
  4138. return this;
  4139. }
  4140. /**
  4141. * The components of this vector are rounded towards zero (up if negative,
  4142. * down if positive) to an integer value.
  4143. *
  4144. * @return {Vector3} A reference to this vector.
  4145. */
  4146. roundToZero() {
  4147. this.x = Math.trunc( this.x );
  4148. this.y = Math.trunc( this.y );
  4149. this.z = Math.trunc( this.z );
  4150. return this;
  4151. }
  4152. /**
  4153. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4154. *
  4155. * @return {Vector3} A reference to this vector.
  4156. */
  4157. negate() {
  4158. this.x = - this.x;
  4159. this.y = - this.y;
  4160. this.z = - this.z;
  4161. return this;
  4162. }
  4163. /**
  4164. * Calculates the dot product of the given vector with this instance.
  4165. *
  4166. * @param {Vector3} v - The vector to compute the dot product with.
  4167. * @return {number} The result of the dot product.
  4168. */
  4169. dot( v ) {
  4170. return this.x * v.x + this.y * v.y + this.z * v.z;
  4171. }
  4172. /**
  4173. * Computes the square of the Euclidean length (straight-line length) from
  4174. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4175. * compare the length squared instead as it is slightly more efficient to calculate.
  4176. *
  4177. * @return {number} The square length of this vector.
  4178. */
  4179. lengthSq() {
  4180. return this.x * this.x + this.y * this.y + this.z * this.z;
  4181. }
  4182. /**
  4183. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4184. *
  4185. * @return {number} The length of this vector.
  4186. */
  4187. length() {
  4188. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4189. }
  4190. /**
  4191. * Computes the Manhattan length of this vector.
  4192. *
  4193. * @return {number} The length of this vector.
  4194. */
  4195. manhattanLength() {
  4196. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4197. }
  4198. /**
  4199. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4200. * with the same direction as this one, but with a vector length of `1`.
  4201. *
  4202. * @return {Vector3} A reference to this vector.
  4203. */
  4204. normalize() {
  4205. return this.divideScalar( this.length() || 1 );
  4206. }
  4207. /**
  4208. * Sets this vector to a vector with the same direction as this one, but
  4209. * with the specified length.
  4210. *
  4211. * @param {number} length - The new length of this vector.
  4212. * @return {Vector3} A reference to this vector.
  4213. */
  4214. setLength( length ) {
  4215. return this.normalize().multiplyScalar( length );
  4216. }
  4217. /**
  4218. * Linearly interpolates between the given vector and this instance, where
  4219. * alpha is the percent distance along the line - alpha = 0 will be this
  4220. * vector, and alpha = 1 will be the given one.
  4221. *
  4222. * @param {Vector3} v - The vector to interpolate towards.
  4223. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4224. * @return {Vector3} A reference to this vector.
  4225. */
  4226. lerp( v, alpha ) {
  4227. this.x += ( v.x - this.x ) * alpha;
  4228. this.y += ( v.y - this.y ) * alpha;
  4229. this.z += ( v.z - this.z ) * alpha;
  4230. return this;
  4231. }
  4232. /**
  4233. * Linearly interpolates between the given vectors, where alpha is the percent
  4234. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4235. * be the second one. The result is stored in this instance.
  4236. *
  4237. * @param {Vector3} v1 - The first vector.
  4238. * @param {Vector3} v2 - The second vector.
  4239. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4240. * @return {Vector3} A reference to this vector.
  4241. */
  4242. lerpVectors( v1, v2, alpha ) {
  4243. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4244. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4245. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4246. return this;
  4247. }
  4248. /**
  4249. * Calculates the cross product of the given vector with this instance.
  4250. *
  4251. * @param {Vector3} v - The vector to compute the cross product with.
  4252. * @return {Vector3} The result of the cross product.
  4253. */
  4254. cross( v ) {
  4255. return this.crossVectors( this, v );
  4256. }
  4257. /**
  4258. * Calculates the cross product of the given vectors and stores the result
  4259. * in this instance.
  4260. *
  4261. * @param {Vector3} a - The first vector.
  4262. * @param {Vector3} b - The second vector.
  4263. * @return {Vector3} A reference to this vector.
  4264. */
  4265. crossVectors( a, b ) {
  4266. const ax = a.x, ay = a.y, az = a.z;
  4267. const bx = b.x, by = b.y, bz = b.z;
  4268. this.x = ay * bz - az * by;
  4269. this.y = az * bx - ax * bz;
  4270. this.z = ax * by - ay * bx;
  4271. return this;
  4272. }
  4273. /**
  4274. * Projects this vector onto the given one.
  4275. *
  4276. * @param {Vector3} v - The vector to project to.
  4277. * @return {Vector3} A reference to this vector.
  4278. */
  4279. projectOnVector( v ) {
  4280. const denominator = v.lengthSq();
  4281. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4282. const scalar = v.dot( this ) / denominator;
  4283. return this.copy( v ).multiplyScalar( scalar );
  4284. }
  4285. /**
  4286. * Projects this vector onto a plane by subtracting this
  4287. * vector projected onto the plane's normal from this vector.
  4288. *
  4289. * @param {Vector3} planeNormal - The plane normal.
  4290. * @return {Vector3} A reference to this vector.
  4291. */
  4292. projectOnPlane( planeNormal ) {
  4293. _vector$c.copy( this ).projectOnVector( planeNormal );
  4294. return this.sub( _vector$c );
  4295. }
  4296. /**
  4297. * Reflects this vector off a plane orthogonal to the given normal vector.
  4298. *
  4299. * @param {Vector3} normal - The (normalized) normal vector.
  4300. * @return {Vector3} A reference to this vector.
  4301. */
  4302. reflect( normal ) {
  4303. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4304. }
  4305. /**
  4306. * Returns the angle between the given vector and this instance in radians.
  4307. *
  4308. * @param {Vector3} v - The vector to compute the angle with.
  4309. * @return {number} The angle in radians.
  4310. */
  4311. angleTo( v ) {
  4312. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4313. if ( denominator === 0 ) return Math.PI / 2;
  4314. const theta = this.dot( v ) / denominator;
  4315. // clamp, to handle numerical problems
  4316. return Math.acos( clamp( theta, -1, 1 ) );
  4317. }
  4318. /**
  4319. * Computes the distance from the given vector to this instance.
  4320. *
  4321. * @param {Vector3} v - The vector to compute the distance to.
  4322. * @return {number} The distance.
  4323. */
  4324. distanceTo( v ) {
  4325. return Math.sqrt( this.distanceToSquared( v ) );
  4326. }
  4327. /**
  4328. * Computes the squared distance from the given vector to this instance.
  4329. * If you are just comparing the distance with another distance, you should compare
  4330. * the distance squared instead as it is slightly more efficient to calculate.
  4331. *
  4332. * @param {Vector3} v - The vector to compute the squared distance to.
  4333. * @return {number} The squared distance.
  4334. */
  4335. distanceToSquared( v ) {
  4336. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4337. return dx * dx + dy * dy + dz * dz;
  4338. }
  4339. /**
  4340. * Computes the Manhattan distance from the given vector to this instance.
  4341. *
  4342. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4343. * @return {number} The Manhattan distance.
  4344. */
  4345. manhattanDistanceTo( v ) {
  4346. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4347. }
  4348. /**
  4349. * Sets the vector components from the given spherical coordinates.
  4350. *
  4351. * @param {Spherical} s - The spherical coordinates.
  4352. * @return {Vector3} A reference to this vector.
  4353. */
  4354. setFromSpherical( s ) {
  4355. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4356. }
  4357. /**
  4358. * Sets the vector components from the given spherical coordinates.
  4359. *
  4360. * @param {number} radius - The radius.
  4361. * @param {number} phi - The phi angle in radians.
  4362. * @param {number} theta - The theta angle in radians.
  4363. * @return {Vector3} A reference to this vector.
  4364. */
  4365. setFromSphericalCoords( radius, phi, theta ) {
  4366. const sinPhiRadius = Math.sin( phi ) * radius;
  4367. this.x = sinPhiRadius * Math.sin( theta );
  4368. this.y = Math.cos( phi ) * radius;
  4369. this.z = sinPhiRadius * Math.cos( theta );
  4370. return this;
  4371. }
  4372. /**
  4373. * Sets the vector components from the given cylindrical coordinates.
  4374. *
  4375. * @param {Cylindrical} c - The cylindrical coordinates.
  4376. * @return {Vector3} A reference to this vector.
  4377. */
  4378. setFromCylindrical( c ) {
  4379. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4380. }
  4381. /**
  4382. * Sets the vector components from the given cylindrical coordinates.
  4383. *
  4384. * @param {number} radius - The radius.
  4385. * @param {number} theta - The theta angle in radians.
  4386. * @param {number} y - The y value.
  4387. * @return {Vector3} A reference to this vector.
  4388. */
  4389. setFromCylindricalCoords( radius, theta, y ) {
  4390. this.x = radius * Math.sin( theta );
  4391. this.y = y;
  4392. this.z = radius * Math.cos( theta );
  4393. return this;
  4394. }
  4395. /**
  4396. * Sets the vector components to the position elements of the
  4397. * given transformation matrix.
  4398. *
  4399. * @param {Matrix4} m - The 4x4 matrix.
  4400. * @return {Vector3} A reference to this vector.
  4401. */
  4402. setFromMatrixPosition( m ) {
  4403. const e = m.elements;
  4404. this.x = e[ 12 ];
  4405. this.y = e[ 13 ];
  4406. this.z = e[ 14 ];
  4407. return this;
  4408. }
  4409. /**
  4410. * Sets the vector components to the scale elements of the
  4411. * given transformation matrix.
  4412. *
  4413. * @param {Matrix4} m - The 4x4 matrix.
  4414. * @return {Vector3} A reference to this vector.
  4415. */
  4416. setFromMatrixScale( m ) {
  4417. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4418. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4419. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4420. this.x = sx;
  4421. this.y = sy;
  4422. this.z = sz;
  4423. return this;
  4424. }
  4425. /**
  4426. * Sets the vector components from the specified matrix column.
  4427. *
  4428. * @param {Matrix4} m - The 4x4 matrix.
  4429. * @param {number} index - The column index.
  4430. * @return {Vector3} A reference to this vector.
  4431. */
  4432. setFromMatrixColumn( m, index ) {
  4433. return this.fromArray( m.elements, index * 4 );
  4434. }
  4435. /**
  4436. * Sets the vector components from the specified matrix column.
  4437. *
  4438. * @param {Matrix3} m - The 3x3 matrix.
  4439. * @param {number} index - The column index.
  4440. * @return {Vector3} A reference to this vector.
  4441. */
  4442. setFromMatrix3Column( m, index ) {
  4443. return this.fromArray( m.elements, index * 3 );
  4444. }
  4445. /**
  4446. * Sets the vector components from the given Euler angles.
  4447. *
  4448. * @param {Euler} e - The Euler angles to set.
  4449. * @return {Vector3} A reference to this vector.
  4450. */
  4451. setFromEuler( e ) {
  4452. this.x = e._x;
  4453. this.y = e._y;
  4454. this.z = e._z;
  4455. return this;
  4456. }
  4457. /**
  4458. * Sets the vector components from the RGB components of the
  4459. * given color.
  4460. *
  4461. * @param {Color} c - The color to set.
  4462. * @return {Vector3} A reference to this vector.
  4463. */
  4464. setFromColor( c ) {
  4465. this.x = c.r;
  4466. this.y = c.g;
  4467. this.z = c.b;
  4468. return this;
  4469. }
  4470. /**
  4471. * Returns `true` if this vector is equal with the given one.
  4472. *
  4473. * @param {Vector3} v - The vector to test for equality.
  4474. * @return {boolean} Whether this vector is equal with the given one.
  4475. */
  4476. equals( v ) {
  4477. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4478. }
  4479. /**
  4480. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4481. * and z value to be `array[ offset + 2 ]`.
  4482. *
  4483. * @param {Array<number>} array - An array holding the vector component values.
  4484. * @param {number} [offset=0] - The offset into the array.
  4485. * @return {Vector3} A reference to this vector.
  4486. */
  4487. fromArray( array, offset = 0 ) {
  4488. this.x = array[ offset ];
  4489. this.y = array[ offset + 1 ];
  4490. this.z = array[ offset + 2 ];
  4491. return this;
  4492. }
  4493. /**
  4494. * Writes the components of this vector to the given array. If no array is provided,
  4495. * the method returns a new instance.
  4496. *
  4497. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4498. * @param {number} [offset=0] - Index of the first element in the array.
  4499. * @return {Array<number>} The vector components.
  4500. */
  4501. toArray( array = [], offset = 0 ) {
  4502. array[ offset ] = this.x;
  4503. array[ offset + 1 ] = this.y;
  4504. array[ offset + 2 ] = this.z;
  4505. return array;
  4506. }
  4507. /**
  4508. * Sets the components of this vector from the given buffer attribute.
  4509. *
  4510. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4511. * @param {number} index - The index into the attribute.
  4512. * @return {Vector3} A reference to this vector.
  4513. */
  4514. fromBufferAttribute( attribute, index ) {
  4515. this.x = attribute.getX( index );
  4516. this.y = attribute.getY( index );
  4517. this.z = attribute.getZ( index );
  4518. return this;
  4519. }
  4520. /**
  4521. * Sets each component of this vector to a pseudo-random value between `0` and
  4522. * `1`, excluding `1`.
  4523. *
  4524. * @return {Vector3} A reference to this vector.
  4525. */
  4526. random() {
  4527. this.x = Math.random();
  4528. this.y = Math.random();
  4529. this.z = Math.random();
  4530. return this;
  4531. }
  4532. /**
  4533. * Sets this vector to a uniformly random point on a unit sphere.
  4534. *
  4535. * @return {Vector3} A reference to this vector.
  4536. */
  4537. randomDirection() {
  4538. // https://mathworld.wolfram.com/SpherePointPicking.html
  4539. const theta = Math.random() * Math.PI * 2;
  4540. const u = Math.random() * 2 - 1;
  4541. const c = Math.sqrt( 1 - u * u );
  4542. this.x = c * Math.cos( theta );
  4543. this.y = u;
  4544. this.z = c * Math.sin( theta );
  4545. return this;
  4546. }
  4547. *[ Symbol.iterator ]() {
  4548. yield this.x;
  4549. yield this.y;
  4550. yield this.z;
  4551. }
  4552. }
  4553. const _vector$c = /*@__PURE__*/ new Vector3();
  4554. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4555. /**
  4556. * Represents a 3x3 matrix.
  4557. *
  4558. * A Note on Row-Major and Column-Major Ordering:
  4559. *
  4560. * The constructor and {@link Matrix3#set} method take arguments in
  4561. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4562. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4563. * This means that calling:
  4564. * ```js
  4565. * const m = new THREE.Matrix();
  4566. * m.set( 11, 12, 13,
  4567. * 21, 22, 23,
  4568. * 31, 32, 33 );
  4569. * ```
  4570. * will result in the elements array containing:
  4571. * ```js
  4572. * m.elements = [ 11, 21, 31,
  4573. * 12, 22, 32,
  4574. * 13, 23, 33 ];
  4575. * ```
  4576. * and internally all calculations are performed using column-major ordering.
  4577. * However, as the actual ordering makes no difference mathematically and
  4578. * most people are used to thinking about matrices in row-major order, the
  4579. * three.js documentation shows matrices in row-major order. Just bear in
  4580. * mind that if you are reading the source code, you'll have to take the
  4581. * transpose of any matrices outlined here to make sense of the calculations.
  4582. */
  4583. class Matrix3 {
  4584. /**
  4585. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4586. * in row-major order. If no arguments are provided, the constructor
  4587. * initializes the matrix as an identity matrix.
  4588. *
  4589. * @param {number} [n11] - 1-1 matrix element.
  4590. * @param {number} [n12] - 1-2 matrix element.
  4591. * @param {number} [n13] - 1-3 matrix element.
  4592. * @param {number} [n21] - 2-1 matrix element.
  4593. * @param {number} [n22] - 2-2 matrix element.
  4594. * @param {number} [n23] - 2-3 matrix element.
  4595. * @param {number} [n31] - 3-1 matrix element.
  4596. * @param {number} [n32] - 3-2 matrix element.
  4597. * @param {number} [n33] - 3-3 matrix element.
  4598. */
  4599. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4600. /**
  4601. * This flag can be used for type testing.
  4602. *
  4603. * @type {boolean}
  4604. * @readonly
  4605. * @default true
  4606. */
  4607. Matrix3.prototype.isMatrix3 = true;
  4608. /**
  4609. * A column-major list of matrix values.
  4610. *
  4611. * @type {Array<number>}
  4612. */
  4613. this.elements = [
  4614. 1, 0, 0,
  4615. 0, 1, 0,
  4616. 0, 0, 1
  4617. ];
  4618. if ( n11 !== undefined ) {
  4619. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4620. }
  4621. }
  4622. /**
  4623. * Sets the elements of the matrix.The arguments are supposed to be
  4624. * in row-major order.
  4625. *
  4626. * @param {number} [n11] - 1-1 matrix element.
  4627. * @param {number} [n12] - 1-2 matrix element.
  4628. * @param {number} [n13] - 1-3 matrix element.
  4629. * @param {number} [n21] - 2-1 matrix element.
  4630. * @param {number} [n22] - 2-2 matrix element.
  4631. * @param {number} [n23] - 2-3 matrix element.
  4632. * @param {number} [n31] - 3-1 matrix element.
  4633. * @param {number} [n32] - 3-2 matrix element.
  4634. * @param {number} [n33] - 3-3 matrix element.
  4635. * @return {Matrix3} A reference to this matrix.
  4636. */
  4637. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4638. const te = this.elements;
  4639. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4640. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4641. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4642. return this;
  4643. }
  4644. /**
  4645. * Sets this matrix to the 3x3 identity matrix.
  4646. *
  4647. * @return {Matrix3} A reference to this matrix.
  4648. */
  4649. identity() {
  4650. this.set(
  4651. 1, 0, 0,
  4652. 0, 1, 0,
  4653. 0, 0, 1
  4654. );
  4655. return this;
  4656. }
  4657. /**
  4658. * Copies the values of the given matrix to this instance.
  4659. *
  4660. * @param {Matrix3} m - The matrix to copy.
  4661. * @return {Matrix3} A reference to this matrix.
  4662. */
  4663. copy( m ) {
  4664. const te = this.elements;
  4665. const me = m.elements;
  4666. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4667. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4668. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4669. return this;
  4670. }
  4671. /**
  4672. * Extracts the basis of this matrix into the three axis vectors provided.
  4673. *
  4674. * @param {Vector3} xAxis - The basis's x axis.
  4675. * @param {Vector3} yAxis - The basis's y axis.
  4676. * @param {Vector3} zAxis - The basis's z axis.
  4677. * @return {Matrix3} A reference to this matrix.
  4678. */
  4679. extractBasis( xAxis, yAxis, zAxis ) {
  4680. xAxis.setFromMatrix3Column( this, 0 );
  4681. yAxis.setFromMatrix3Column( this, 1 );
  4682. zAxis.setFromMatrix3Column( this, 2 );
  4683. return this;
  4684. }
  4685. /**
  4686. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4687. *
  4688. * @param {Matrix4} m - The 4x4 matrix.
  4689. * @return {Matrix3} A reference to this matrix.
  4690. */
  4691. setFromMatrix4( m ) {
  4692. const me = m.elements;
  4693. this.set(
  4694. me[ 0 ], me[ 4 ], me[ 8 ],
  4695. me[ 1 ], me[ 5 ], me[ 9 ],
  4696. me[ 2 ], me[ 6 ], me[ 10 ]
  4697. );
  4698. return this;
  4699. }
  4700. /**
  4701. * Post-multiplies this matrix by the given 3x3 matrix.
  4702. *
  4703. * @param {Matrix3} m - The matrix to multiply with.
  4704. * @return {Matrix3} A reference to this matrix.
  4705. */
  4706. multiply( m ) {
  4707. return this.multiplyMatrices( this, m );
  4708. }
  4709. /**
  4710. * Pre-multiplies this matrix by the given 3x3 matrix.
  4711. *
  4712. * @param {Matrix3} m - The matrix to multiply with.
  4713. * @return {Matrix3} A reference to this matrix.
  4714. */
  4715. premultiply( m ) {
  4716. return this.multiplyMatrices( m, this );
  4717. }
  4718. /**
  4719. * Multiples the given 3x3 matrices and stores the result
  4720. * in this matrix.
  4721. *
  4722. * @param {Matrix3} a - The first matrix.
  4723. * @param {Matrix3} b - The second matrix.
  4724. * @return {Matrix3} A reference to this matrix.
  4725. */
  4726. multiplyMatrices( a, b ) {
  4727. const ae = a.elements;
  4728. const be = b.elements;
  4729. const te = this.elements;
  4730. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4731. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4732. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4733. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4734. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4735. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4736. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4737. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4738. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4739. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4740. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4741. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4742. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4743. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4744. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4745. return this;
  4746. }
  4747. /**
  4748. * Multiplies every component of the matrix by the given scalar.
  4749. *
  4750. * @param {number} s - The scalar.
  4751. * @return {Matrix3} A reference to this matrix.
  4752. */
  4753. multiplyScalar( s ) {
  4754. const te = this.elements;
  4755. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4756. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4757. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4758. return this;
  4759. }
  4760. /**
  4761. * Computes and returns the determinant of this matrix.
  4762. *
  4763. * @return {number} The determinant.
  4764. */
  4765. determinant() {
  4766. const te = this.elements;
  4767. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4768. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4769. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4770. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4771. }
  4772. /**
  4773. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4774. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4775. * a zero matrix instead.
  4776. *
  4777. * @return {Matrix3} A reference to this matrix.
  4778. */
  4779. invert() {
  4780. const te = this.elements,
  4781. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4782. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4783. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4784. t11 = n33 * n22 - n32 * n23,
  4785. t12 = n32 * n13 - n33 * n12,
  4786. t13 = n23 * n12 - n22 * n13,
  4787. det = n11 * t11 + n21 * t12 + n31 * t13;
  4788. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4789. const detInv = 1 / det;
  4790. te[ 0 ] = t11 * detInv;
  4791. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4792. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4793. te[ 3 ] = t12 * detInv;
  4794. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4795. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4796. te[ 6 ] = t13 * detInv;
  4797. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4798. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4799. return this;
  4800. }
  4801. /**
  4802. * Transposes this matrix in place.
  4803. *
  4804. * @return {Matrix3} A reference to this matrix.
  4805. */
  4806. transpose() {
  4807. let tmp;
  4808. const m = this.elements;
  4809. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4810. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4811. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4812. return this;
  4813. }
  4814. /**
  4815. * Computes the normal matrix which is the inverse transpose of the upper
  4816. * left 3x3 portion of the given 4x4 matrix.
  4817. *
  4818. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4819. * @return {Matrix3} A reference to this matrix.
  4820. */
  4821. getNormalMatrix( matrix4 ) {
  4822. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4823. }
  4824. /**
  4825. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4826. *
  4827. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4828. * @return {Matrix3} A reference to this matrix.
  4829. */
  4830. transposeIntoArray( r ) {
  4831. const m = this.elements;
  4832. r[ 0 ] = m[ 0 ];
  4833. r[ 1 ] = m[ 3 ];
  4834. r[ 2 ] = m[ 6 ];
  4835. r[ 3 ] = m[ 1 ];
  4836. r[ 4 ] = m[ 4 ];
  4837. r[ 5 ] = m[ 7 ];
  4838. r[ 6 ] = m[ 2 ];
  4839. r[ 7 ] = m[ 5 ];
  4840. r[ 8 ] = m[ 8 ];
  4841. return this;
  4842. }
  4843. /**
  4844. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4845. *
  4846. * @param {number} tx - Offset x.
  4847. * @param {number} ty - Offset y.
  4848. * @param {number} sx - Repeat x.
  4849. * @param {number} sy - Repeat y.
  4850. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4851. * @param {number} cx - Center x of rotation.
  4852. * @param {number} cy - Center y of rotation
  4853. * @return {Matrix3} A reference to this matrix.
  4854. */
  4855. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4856. const c = Math.cos( rotation );
  4857. const s = Math.sin( rotation );
  4858. this.set(
  4859. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4860. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4861. 0, 0, 1
  4862. );
  4863. return this;
  4864. }
  4865. /**
  4866. * Scales this matrix with the given scalar values.
  4867. *
  4868. * @param {number} sx - The amount to scale in the X axis.
  4869. * @param {number} sy - The amount to scale in the Y axis.
  4870. * @return {Matrix3} A reference to this matrix.
  4871. */
  4872. scale( sx, sy ) {
  4873. this.premultiply( _m3.makeScale( sx, sy ) );
  4874. return this;
  4875. }
  4876. /**
  4877. * Rotates this matrix by the given angle.
  4878. *
  4879. * @param {number} theta - The rotation in radians.
  4880. * @return {Matrix3} A reference to this matrix.
  4881. */
  4882. rotate( theta ) {
  4883. this.premultiply( _m3.makeRotation( - theta ) );
  4884. return this;
  4885. }
  4886. /**
  4887. * Translates this matrix by the given scalar values.
  4888. *
  4889. * @param {number} tx - The amount to translate in the X axis.
  4890. * @param {number} ty - The amount to translate in the Y axis.
  4891. * @return {Matrix3} A reference to this matrix.
  4892. */
  4893. translate( tx, ty ) {
  4894. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4895. return this;
  4896. }
  4897. // for 2D Transforms
  4898. /**
  4899. * Sets this matrix as a 2D translation transform.
  4900. *
  4901. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4902. * @param {number} y - The amount to translate in the Y axis.
  4903. * @return {Matrix3} A reference to this matrix.
  4904. */
  4905. makeTranslation( x, y ) {
  4906. if ( x.isVector2 ) {
  4907. this.set(
  4908. 1, 0, x.x,
  4909. 0, 1, x.y,
  4910. 0, 0, 1
  4911. );
  4912. } else {
  4913. this.set(
  4914. 1, 0, x,
  4915. 0, 1, y,
  4916. 0, 0, 1
  4917. );
  4918. }
  4919. return this;
  4920. }
  4921. /**
  4922. * Sets this matrix as a 2D rotational transformation.
  4923. *
  4924. * @param {number} theta - The rotation in radians.
  4925. * @return {Matrix3} A reference to this matrix.
  4926. */
  4927. makeRotation( theta ) {
  4928. // counterclockwise
  4929. const c = Math.cos( theta );
  4930. const s = Math.sin( theta );
  4931. this.set(
  4932. c, - s, 0,
  4933. s, c, 0,
  4934. 0, 0, 1
  4935. );
  4936. return this;
  4937. }
  4938. /**
  4939. * Sets this matrix as a 2D scale transform.
  4940. *
  4941. * @param {number} x - The amount to scale in the X axis.
  4942. * @param {number} y - The amount to scale in the Y axis.
  4943. * @return {Matrix3} A reference to this matrix.
  4944. */
  4945. makeScale( x, y ) {
  4946. this.set(
  4947. x, 0, 0,
  4948. 0, y, 0,
  4949. 0, 0, 1
  4950. );
  4951. return this;
  4952. }
  4953. /**
  4954. * Returns `true` if this matrix is equal with the given one.
  4955. *
  4956. * @param {Matrix3} matrix - The matrix to test for equality.
  4957. * @return {boolean} Whether this matrix is equal with the given one.
  4958. */
  4959. equals( matrix ) {
  4960. const te = this.elements;
  4961. const me = matrix.elements;
  4962. for ( let i = 0; i < 9; i ++ ) {
  4963. if ( te[ i ] !== me[ i ] ) return false;
  4964. }
  4965. return true;
  4966. }
  4967. /**
  4968. * Sets the elements of the matrix from the given array.
  4969. *
  4970. * @param {Array<number>} array - The matrix elements in column-major order.
  4971. * @param {number} [offset=0] - Index of the first element in the array.
  4972. * @return {Matrix3} A reference to this matrix.
  4973. */
  4974. fromArray( array, offset = 0 ) {
  4975. for ( let i = 0; i < 9; i ++ ) {
  4976. this.elements[ i ] = array[ i + offset ];
  4977. }
  4978. return this;
  4979. }
  4980. /**
  4981. * Writes the elements of this matrix to the given array. If no array is provided,
  4982. * the method returns a new instance.
  4983. *
  4984. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  4985. * @param {number} [offset=0] - Index of the first element in the array.
  4986. * @return {Array<number>} The matrix elements in column-major order.
  4987. */
  4988. toArray( array = [], offset = 0 ) {
  4989. const te = this.elements;
  4990. array[ offset ] = te[ 0 ];
  4991. array[ offset + 1 ] = te[ 1 ];
  4992. array[ offset + 2 ] = te[ 2 ];
  4993. array[ offset + 3 ] = te[ 3 ];
  4994. array[ offset + 4 ] = te[ 4 ];
  4995. array[ offset + 5 ] = te[ 5 ];
  4996. array[ offset + 6 ] = te[ 6 ];
  4997. array[ offset + 7 ] = te[ 7 ];
  4998. array[ offset + 8 ] = te[ 8 ];
  4999. return array;
  5000. }
  5001. /**
  5002. * Returns a matrix with copied values from this instance.
  5003. *
  5004. * @return {Matrix3} A clone of this instance.
  5005. */
  5006. clone() {
  5007. return new this.constructor().fromArray( this.elements );
  5008. }
  5009. }
  5010. const _m3 = /*@__PURE__*/ new Matrix3();
  5011. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5012. 0.4123908, 0.3575843, 0.1804808,
  5013. 0.2126390, 0.7151687, 0.0721923,
  5014. 0.0193308, 0.1191948, 0.9505322
  5015. );
  5016. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5017. 3.2409699, -1.5373832, -0.4986108,
  5018. -0.9692436, 1.8759675, 0.0415551,
  5019. 0.0556301, -0.203977, 1.0569715
  5020. );
  5021. function createColorManagement() {
  5022. const ColorManagement = {
  5023. enabled: true,
  5024. workingColorSpace: LinearSRGBColorSpace,
  5025. /**
  5026. * Implementations of supported color spaces.
  5027. *
  5028. * Required:
  5029. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5030. * - whitePoint: reference white [ x y ]
  5031. * - transfer: transfer function (pre-defined)
  5032. * - toXYZ: Matrix3 RGB to XYZ transform
  5033. * - fromXYZ: Matrix3 XYZ to RGB transform
  5034. * - luminanceCoefficients: RGB luminance coefficients
  5035. *
  5036. * Optional:
  5037. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5038. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5039. *
  5040. * Reference:
  5041. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5042. */
  5043. spaces: {},
  5044. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5045. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5046. return color;
  5047. }
  5048. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5049. color.r = SRGBToLinear( color.r );
  5050. color.g = SRGBToLinear( color.g );
  5051. color.b = SRGBToLinear( color.b );
  5052. }
  5053. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5054. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5055. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5056. }
  5057. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5058. color.r = LinearToSRGB( color.r );
  5059. color.g = LinearToSRGB( color.g );
  5060. color.b = LinearToSRGB( color.b );
  5061. }
  5062. return color;
  5063. },
  5064. workingToColorSpace: function ( color, targetColorSpace ) {
  5065. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5066. },
  5067. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5068. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5069. },
  5070. getPrimaries: function ( colorSpace ) {
  5071. return this.spaces[ colorSpace ].primaries;
  5072. },
  5073. getTransfer: function ( colorSpace ) {
  5074. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5075. return this.spaces[ colorSpace ].transfer;
  5076. },
  5077. getToneMappingMode: function ( colorSpace ) {
  5078. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5079. },
  5080. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5081. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5082. },
  5083. define: function ( colorSpaces ) {
  5084. Object.assign( this.spaces, colorSpaces );
  5085. },
  5086. // Internal APIs
  5087. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5088. return targetMatrix
  5089. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5090. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5091. },
  5092. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5093. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5094. },
  5095. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5096. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5097. },
  5098. // Deprecated
  5099. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5100. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5101. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5102. },
  5103. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5104. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5105. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5106. },
  5107. };
  5108. /******************************************************************************
  5109. * sRGB definitions
  5110. */
  5111. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5112. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5113. const D65 = [ 0.3127, 0.3290 ];
  5114. ColorManagement.define( {
  5115. [ LinearSRGBColorSpace ]: {
  5116. primaries: REC709_PRIMARIES,
  5117. whitePoint: D65,
  5118. transfer: LinearTransfer,
  5119. toXYZ: LINEAR_REC709_TO_XYZ,
  5120. fromXYZ: XYZ_TO_LINEAR_REC709,
  5121. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5122. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5123. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5124. },
  5125. [ SRGBColorSpace ]: {
  5126. primaries: REC709_PRIMARIES,
  5127. whitePoint: D65,
  5128. transfer: SRGBTransfer,
  5129. toXYZ: LINEAR_REC709_TO_XYZ,
  5130. fromXYZ: XYZ_TO_LINEAR_REC709,
  5131. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5132. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5133. },
  5134. } );
  5135. return ColorManagement;
  5136. }
  5137. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5138. function SRGBToLinear( c ) {
  5139. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5140. }
  5141. function LinearToSRGB( c ) {
  5142. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5143. }
  5144. let _canvas;
  5145. /**
  5146. * A class containing utility functions for images.
  5147. *
  5148. * @hideconstructor
  5149. */
  5150. class ImageUtils {
  5151. /**
  5152. * Returns a data URI containing a representation of the given image.
  5153. *
  5154. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5155. * @param {string} [type='image/png'] - Indicates the image format.
  5156. * @return {string} The data URI.
  5157. */
  5158. static getDataURL( image, type = 'image/png' ) {
  5159. if ( /^data:/i.test( image.src ) ) {
  5160. return image.src;
  5161. }
  5162. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5163. return image.src;
  5164. }
  5165. let canvas;
  5166. if ( image instanceof HTMLCanvasElement ) {
  5167. canvas = image;
  5168. } else {
  5169. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5170. _canvas.width = image.width;
  5171. _canvas.height = image.height;
  5172. const context = _canvas.getContext( '2d' );
  5173. if ( image instanceof ImageData ) {
  5174. context.putImageData( image, 0, 0 );
  5175. } else {
  5176. context.drawImage( image, 0, 0, image.width, image.height );
  5177. }
  5178. canvas = _canvas;
  5179. }
  5180. return canvas.toDataURL( type );
  5181. }
  5182. /**
  5183. * Converts the given sRGB image data to linear color space.
  5184. *
  5185. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5186. * @return {HTMLCanvasElement|Object} The converted image.
  5187. */
  5188. static sRGBToLinear( image ) {
  5189. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5190. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5191. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5192. const canvas = createElementNS( 'canvas' );
  5193. canvas.width = image.width;
  5194. canvas.height = image.height;
  5195. const context = canvas.getContext( '2d' );
  5196. context.drawImage( image, 0, 0, image.width, image.height );
  5197. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5198. const data = imageData.data;
  5199. for ( let i = 0; i < data.length; i ++ ) {
  5200. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5201. }
  5202. context.putImageData( imageData, 0, 0 );
  5203. return canvas;
  5204. } else if ( image.data ) {
  5205. const data = image.data.slice( 0 );
  5206. for ( let i = 0; i < data.length; i ++ ) {
  5207. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5208. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5209. } else {
  5210. // assuming float
  5211. data[ i ] = SRGBToLinear( data[ i ] );
  5212. }
  5213. }
  5214. return {
  5215. data: data,
  5216. width: image.width,
  5217. height: image.height
  5218. };
  5219. } else {
  5220. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5221. return image;
  5222. }
  5223. }
  5224. }
  5225. let _sourceId = 0;
  5226. /**
  5227. * Represents the data source of a texture.
  5228. *
  5229. * The main purpose of this class is to decouple the data definition from the texture
  5230. * definition so the same data can be used with multiple texture instances.
  5231. */
  5232. class Source {
  5233. /**
  5234. * Constructs a new video texture.
  5235. *
  5236. * @param {any} [data=null] - The data definition of a texture.
  5237. */
  5238. constructor( data = null ) {
  5239. /**
  5240. * This flag can be used for type testing.
  5241. *
  5242. * @type {boolean}
  5243. * @readonly
  5244. * @default true
  5245. */
  5246. this.isSource = true;
  5247. /**
  5248. * The ID of the source.
  5249. *
  5250. * @name Source#id
  5251. * @type {number}
  5252. * @readonly
  5253. */
  5254. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5255. /**
  5256. * The UUID of the source.
  5257. *
  5258. * @type {string}
  5259. * @readonly
  5260. */
  5261. this.uuid = generateUUID();
  5262. /**
  5263. * The data definition of a texture.
  5264. *
  5265. * @type {any}
  5266. */
  5267. this.data = data;
  5268. /**
  5269. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5270. * provides more control on how texture data should be processed. When `dataReady` is set
  5271. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5272. * the data into the GPU memory.
  5273. *
  5274. * @type {boolean}
  5275. * @default true
  5276. */
  5277. this.dataReady = true;
  5278. /**
  5279. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5280. *
  5281. * @type {number}
  5282. * @readonly
  5283. * @default 0
  5284. */
  5285. this.version = 0;
  5286. }
  5287. /**
  5288. * Returns the dimensions of the source into the given target vector.
  5289. *
  5290. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5291. * @return {(Vector2|Vector3)} The dimensions of the source.
  5292. */
  5293. getSize( target ) {
  5294. const data = this.data;
  5295. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5296. target.set( data.videoWidth, data.videoHeight, 0 );
  5297. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5298. target.set( data.displayHeight, data.displayWidth, 0 );
  5299. } else if ( data !== null ) {
  5300. target.set( data.width, data.height, data.depth || 0 );
  5301. } else {
  5302. target.set( 0, 0, 0 );
  5303. }
  5304. return target;
  5305. }
  5306. /**
  5307. * When the property is set to `true`, the engine allocates the memory
  5308. * for the texture (if necessary) and triggers the actual texture upload
  5309. * to the GPU next time the source is used.
  5310. *
  5311. * @type {boolean}
  5312. * @default false
  5313. * @param {boolean} value
  5314. */
  5315. set needsUpdate( value ) {
  5316. if ( value === true ) this.version ++;
  5317. }
  5318. /**
  5319. * Serializes the source into JSON.
  5320. *
  5321. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5322. * @return {Object} A JSON object representing the serialized source.
  5323. * @see {@link ObjectLoader#parse}
  5324. */
  5325. toJSON( meta ) {
  5326. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5327. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5328. return meta.images[ this.uuid ];
  5329. }
  5330. const output = {
  5331. uuid: this.uuid,
  5332. url: ''
  5333. };
  5334. const data = this.data;
  5335. if ( data !== null ) {
  5336. let url;
  5337. if ( Array.isArray( data ) ) {
  5338. // cube texture
  5339. url = [];
  5340. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5341. if ( data[ i ].isDataTexture ) {
  5342. url.push( serializeImage( data[ i ].image ) );
  5343. } else {
  5344. url.push( serializeImage( data[ i ] ) );
  5345. }
  5346. }
  5347. } else {
  5348. // texture
  5349. url = serializeImage( data );
  5350. }
  5351. output.url = url;
  5352. }
  5353. if ( ! isRootObject ) {
  5354. meta.images[ this.uuid ] = output;
  5355. }
  5356. return output;
  5357. }
  5358. }
  5359. function serializeImage( image ) {
  5360. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5361. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5362. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5363. // default images
  5364. return ImageUtils.getDataURL( image );
  5365. } else {
  5366. if ( image.data ) {
  5367. // images of DataTexture
  5368. return {
  5369. data: Array.from( image.data ),
  5370. width: image.width,
  5371. height: image.height,
  5372. type: image.data.constructor.name
  5373. };
  5374. } else {
  5375. warn( 'Texture: Unable to serialize Texture.' );
  5376. return {};
  5377. }
  5378. }
  5379. }
  5380. let _textureId = 0;
  5381. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5382. /**
  5383. * Base class for all textures.
  5384. *
  5385. * Note: After the initial use of a texture, its dimensions, format, and type
  5386. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5387. *
  5388. * @augments EventDispatcher
  5389. */
  5390. class Texture extends EventDispatcher {
  5391. /**
  5392. * Constructs a new texture.
  5393. *
  5394. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5395. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5396. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5397. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5398. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5399. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5400. * @param {number} [format=RGBAFormat] - The texture format.
  5401. * @param {number} [type=UnsignedByteType] - The texture type.
  5402. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5403. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5404. */
  5405. constructor( image = Texture.DEFAULT_IMAGE, mapping = Texture.DEFAULT_MAPPING, wrapS = ClampToEdgeWrapping, wrapT = ClampToEdgeWrapping, magFilter = LinearFilter, minFilter = LinearMipmapLinearFilter, format = RGBAFormat, type = UnsignedByteType, anisotropy = Texture.DEFAULT_ANISOTROPY, colorSpace = NoColorSpace ) {
  5406. super();
  5407. /**
  5408. * This flag can be used for type testing.
  5409. *
  5410. * @type {boolean}
  5411. * @readonly
  5412. * @default true
  5413. */
  5414. this.isTexture = true;
  5415. /**
  5416. * The ID of the texture.
  5417. *
  5418. * @name Texture#id
  5419. * @type {number}
  5420. * @readonly
  5421. */
  5422. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5423. /**
  5424. * The UUID of the material.
  5425. *
  5426. * @type {string}
  5427. * @readonly
  5428. */
  5429. this.uuid = generateUUID();
  5430. /**
  5431. * The name of the material.
  5432. *
  5433. * @type {string}
  5434. */
  5435. this.name = '';
  5436. /**
  5437. * The data definition of a texture. A reference to the data source can be
  5438. * shared across textures. This is often useful in context of spritesheets
  5439. * where multiple textures render the same data but with different texture
  5440. * transformations.
  5441. *
  5442. * @type {Source}
  5443. */
  5444. this.source = new Source( image );
  5445. /**
  5446. * An array holding user-defined mipmaps.
  5447. *
  5448. * @type {Array<Object>}
  5449. */
  5450. this.mipmaps = [];
  5451. /**
  5452. * How the texture is applied to the object. The value `UVMapping`
  5453. * is the default, where texture or uv coordinates are used to apply the map.
  5454. *
  5455. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5456. * @default UVMapping
  5457. */
  5458. this.mapping = mapping;
  5459. /**
  5460. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5461. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5462. *
  5463. * @type {number}
  5464. * @default 0
  5465. */
  5466. this.channel = 0;
  5467. /**
  5468. * This defines how the texture is wrapped horizontally and corresponds to
  5469. * *U* in UV mapping.
  5470. *
  5471. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5472. * @default ClampToEdgeWrapping
  5473. */
  5474. this.wrapS = wrapS;
  5475. /**
  5476. * This defines how the texture is wrapped horizontally and corresponds to
  5477. * *V* in UV mapping.
  5478. *
  5479. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5480. * @default ClampToEdgeWrapping
  5481. */
  5482. this.wrapT = wrapT;
  5483. /**
  5484. * How the texture is sampled when a texel covers more than one pixel.
  5485. *
  5486. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5487. * @default LinearFilter
  5488. */
  5489. this.magFilter = magFilter;
  5490. /**
  5491. * How the texture is sampled when a texel covers less than one pixel.
  5492. *
  5493. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5494. * @default LinearMipmapLinearFilter
  5495. */
  5496. this.minFilter = minFilter;
  5497. /**
  5498. * The number of samples taken along the axis through the pixel that has the
  5499. * highest density of texels. By default, this value is `1`. A higher value
  5500. * gives a less blurry result than a basic mipmap, at the cost of more
  5501. * texture samples being used.
  5502. *
  5503. * @type {number}
  5504. * @default Texture.DEFAULT_ANISOTROPY
  5505. */
  5506. this.anisotropy = anisotropy;
  5507. /**
  5508. * The format of the texture.
  5509. *
  5510. * @type {number}
  5511. * @default RGBAFormat
  5512. */
  5513. this.format = format;
  5514. /**
  5515. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5516. * defines how the texture data is going to be stored on the GPU.
  5517. *
  5518. * This property allows to overwrite the default format.
  5519. *
  5520. * @type {?string}
  5521. * @default null
  5522. */
  5523. this.internalFormat = null;
  5524. /**
  5525. * The data type of the texture.
  5526. *
  5527. * @type {number}
  5528. * @default UnsignedByteType
  5529. */
  5530. this.type = type;
  5531. /**
  5532. * How much a single repetition of the texture is offset from the beginning,
  5533. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5534. *
  5535. * @type {Vector2}
  5536. * @default (0,0)
  5537. */
  5538. this.offset = new Vector2( 0, 0 );
  5539. /**
  5540. * How many times the texture is repeated across the surface, in each
  5541. * direction U and V. If repeat is set greater than `1` in either direction,
  5542. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5543. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5544. *
  5545. * @type {Vector2}
  5546. * @default (1,1)
  5547. */
  5548. this.repeat = new Vector2( 1, 1 );
  5549. /**
  5550. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5551. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5552. *
  5553. * @type {Vector2}
  5554. * @default (0,0)
  5555. */
  5556. this.center = new Vector2( 0, 0 );
  5557. /**
  5558. * How much the texture is rotated around the center point, in radians.
  5559. * Positive values are counter-clockwise.
  5560. *
  5561. * @type {number}
  5562. * @default 0
  5563. */
  5564. this.rotation = 0;
  5565. /**
  5566. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5567. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5568. * {@link Texture#rotation}, and {@link Texture#center}.
  5569. *
  5570. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5571. *
  5572. * @type {boolean}
  5573. * @default true
  5574. */
  5575. this.matrixAutoUpdate = true;
  5576. /**
  5577. * The uv-transformation matrix of the texture.
  5578. *
  5579. * @type {Matrix3}
  5580. */
  5581. this.matrix = new Matrix3();
  5582. /**
  5583. * Whether to generate mipmaps (if possible) for a texture.
  5584. *
  5585. * Set this to `false` if you are creating mipmaps manually.
  5586. *
  5587. * @type {boolean}
  5588. * @default true
  5589. */
  5590. this.generateMipmaps = true;
  5591. /**
  5592. * If set to `true`, the alpha channel, if present, is multiplied into the
  5593. * color channels when the texture is uploaded to the GPU.
  5594. *
  5595. * Note that this property has no effect when using `ImageBitmap`. You need to
  5596. * configure premultiply alpha on bitmap creation instead.
  5597. *
  5598. * @type {boolean}
  5599. * @default false
  5600. */
  5601. this.premultiplyAlpha = false;
  5602. /**
  5603. * If set to `true`, the texture is flipped along the vertical axis when
  5604. * uploaded to the GPU.
  5605. *
  5606. * Note that this property has no effect when using `ImageBitmap`. You need to
  5607. * configure the flip on bitmap creation instead.
  5608. *
  5609. * @type {boolean}
  5610. * @default true
  5611. */
  5612. this.flipY = true;
  5613. /**
  5614. * Specifies the alignment requirements for the start of each pixel row in memory.
  5615. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5616. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5617. *
  5618. * @type {number}
  5619. * @default 4
  5620. */
  5621. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5622. /**
  5623. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5624. *
  5625. * @type {string}
  5626. * @default NoColorSpace
  5627. */
  5628. this.colorSpace = colorSpace;
  5629. /**
  5630. * An object that can be used to store custom data about the texture. It
  5631. * should not hold references to functions as these will not be cloned.
  5632. *
  5633. * @type {Object}
  5634. */
  5635. this.userData = {};
  5636. /**
  5637. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5638. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5639. *
  5640. * @type {Array<Object>}
  5641. */
  5642. this.updateRanges = [];
  5643. /**
  5644. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5645. *
  5646. * @type {number}
  5647. * @readonly
  5648. * @default 0
  5649. */
  5650. this.version = 0;
  5651. /**
  5652. * A callback function, called when the texture is updated (e.g., when
  5653. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5654. *
  5655. * @type {?Function}
  5656. * @default null
  5657. */
  5658. this.onUpdate = null;
  5659. /**
  5660. * An optional back reference to the textures render target.
  5661. *
  5662. * @type {?(RenderTarget|WebGLRenderTarget)}
  5663. * @default null
  5664. */
  5665. this.renderTarget = null;
  5666. /**
  5667. * Indicates whether a texture belongs to a render target or not.
  5668. *
  5669. * @type {boolean}
  5670. * @readonly
  5671. * @default false
  5672. */
  5673. this.isRenderTargetTexture = false;
  5674. /**
  5675. * Indicates if a texture should be handled like a texture array.
  5676. *
  5677. * @type {boolean}
  5678. * @readonly
  5679. * @default false
  5680. */
  5681. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5682. /**
  5683. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5684. * (only relevant for render target textures).
  5685. *
  5686. * @type {number}
  5687. * @readonly
  5688. * @default 0
  5689. */
  5690. this.pmremVersion = 0;
  5691. }
  5692. /**
  5693. * The width of the texture in pixels.
  5694. */
  5695. get width() {
  5696. return this.source.getSize( _tempVec3 ).x;
  5697. }
  5698. /**
  5699. * The height of the texture in pixels.
  5700. */
  5701. get height() {
  5702. return this.source.getSize( _tempVec3 ).y;
  5703. }
  5704. /**
  5705. * The depth of the texture in pixels.
  5706. */
  5707. get depth() {
  5708. return this.source.getSize( _tempVec3 ).z;
  5709. }
  5710. /**
  5711. * The image object holding the texture data.
  5712. *
  5713. * @type {?Object}
  5714. */
  5715. get image() {
  5716. return this.source.data;
  5717. }
  5718. set image( value = null ) {
  5719. this.source.data = value;
  5720. }
  5721. /**
  5722. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5723. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5724. */
  5725. updateMatrix() {
  5726. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5727. }
  5728. /**
  5729. * Adds a range of data in the data texture to be updated on the GPU.
  5730. *
  5731. * @param {number} start - Position at which to start update.
  5732. * @param {number} count - The number of components to update.
  5733. */
  5734. addUpdateRange( start, count ) {
  5735. this.updateRanges.push( { start, count } );
  5736. }
  5737. /**
  5738. * Clears the update ranges.
  5739. */
  5740. clearUpdateRanges() {
  5741. this.updateRanges.length = 0;
  5742. }
  5743. /**
  5744. * Returns a new texture with copied values from this instance.
  5745. *
  5746. * @return {Texture} A clone of this instance.
  5747. */
  5748. clone() {
  5749. return new this.constructor().copy( this );
  5750. }
  5751. /**
  5752. * Copies the values of the given texture to this instance.
  5753. *
  5754. * @param {Texture} source - The texture to copy.
  5755. * @return {Texture} A reference to this instance.
  5756. */
  5757. copy( source ) {
  5758. this.name = source.name;
  5759. this.source = source.source;
  5760. this.mipmaps = source.mipmaps.slice( 0 );
  5761. this.mapping = source.mapping;
  5762. this.channel = source.channel;
  5763. this.wrapS = source.wrapS;
  5764. this.wrapT = source.wrapT;
  5765. this.magFilter = source.magFilter;
  5766. this.minFilter = source.minFilter;
  5767. this.anisotropy = source.anisotropy;
  5768. this.format = source.format;
  5769. this.internalFormat = source.internalFormat;
  5770. this.type = source.type;
  5771. this.offset.copy( source.offset );
  5772. this.repeat.copy( source.repeat );
  5773. this.center.copy( source.center );
  5774. this.rotation = source.rotation;
  5775. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5776. this.matrix.copy( source.matrix );
  5777. this.generateMipmaps = source.generateMipmaps;
  5778. this.premultiplyAlpha = source.premultiplyAlpha;
  5779. this.flipY = source.flipY;
  5780. this.unpackAlignment = source.unpackAlignment;
  5781. this.colorSpace = source.colorSpace;
  5782. this.renderTarget = source.renderTarget;
  5783. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5784. this.isArrayTexture = source.isArrayTexture;
  5785. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5786. this.needsUpdate = true;
  5787. return this;
  5788. }
  5789. /**
  5790. * Sets this texture's properties based on `values`.
  5791. * @param {Object} values - A container with texture parameters.
  5792. */
  5793. setValues( values ) {
  5794. for ( const key in values ) {
  5795. const newValue = values[ key ];
  5796. if ( newValue === undefined ) {
  5797. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5798. continue;
  5799. }
  5800. const currentValue = this[ key ];
  5801. if ( currentValue === undefined ) {
  5802. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5803. continue;
  5804. }
  5805. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5806. currentValue.copy( newValue );
  5807. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5808. currentValue.copy( newValue );
  5809. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5810. currentValue.copy( newValue );
  5811. } else {
  5812. this[ key ] = newValue;
  5813. }
  5814. }
  5815. }
  5816. /**
  5817. * Serializes the texture into JSON.
  5818. *
  5819. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5820. * @return {Object} A JSON object representing the serialized texture.
  5821. * @see {@link ObjectLoader#parse}
  5822. */
  5823. toJSON( meta ) {
  5824. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5825. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5826. return meta.textures[ this.uuid ];
  5827. }
  5828. const output = {
  5829. metadata: {
  5830. version: 4.7,
  5831. type: 'Texture',
  5832. generator: 'Texture.toJSON'
  5833. },
  5834. uuid: this.uuid,
  5835. name: this.name,
  5836. image: this.source.toJSON( meta ).uuid,
  5837. mapping: this.mapping,
  5838. channel: this.channel,
  5839. repeat: [ this.repeat.x, this.repeat.y ],
  5840. offset: [ this.offset.x, this.offset.y ],
  5841. center: [ this.center.x, this.center.y ],
  5842. rotation: this.rotation,
  5843. wrap: [ this.wrapS, this.wrapT ],
  5844. format: this.format,
  5845. internalFormat: this.internalFormat,
  5846. type: this.type,
  5847. colorSpace: this.colorSpace,
  5848. minFilter: this.minFilter,
  5849. magFilter: this.magFilter,
  5850. anisotropy: this.anisotropy,
  5851. flipY: this.flipY,
  5852. generateMipmaps: this.generateMipmaps,
  5853. premultiplyAlpha: this.premultiplyAlpha,
  5854. unpackAlignment: this.unpackAlignment
  5855. };
  5856. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5857. if ( ! isRootObject ) {
  5858. meta.textures[ this.uuid ] = output;
  5859. }
  5860. return output;
  5861. }
  5862. /**
  5863. * Frees the GPU-related resources allocated by this instance. Call this
  5864. * method whenever this instance is no longer used in your app.
  5865. *
  5866. * @fires Texture#dispose
  5867. */
  5868. dispose() {
  5869. /**
  5870. * Fires when the texture has been disposed of.
  5871. *
  5872. * @event Texture#dispose
  5873. * @type {Object}
  5874. */
  5875. this.dispatchEvent( { type: 'dispose' } );
  5876. }
  5877. /**
  5878. * Transforms the given uv vector with the textures uv transformation matrix.
  5879. *
  5880. * @param {Vector2} uv - The uv vector.
  5881. * @return {Vector2} The transformed uv vector.
  5882. */
  5883. transformUv( uv ) {
  5884. if ( this.mapping !== UVMapping ) return uv;
  5885. uv.applyMatrix3( this.matrix );
  5886. if ( uv.x < 0 || uv.x > 1 ) {
  5887. switch ( this.wrapS ) {
  5888. case RepeatWrapping:
  5889. uv.x = uv.x - Math.floor( uv.x );
  5890. break;
  5891. case ClampToEdgeWrapping:
  5892. uv.x = uv.x < 0 ? 0 : 1;
  5893. break;
  5894. case MirroredRepeatWrapping:
  5895. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5896. uv.x = Math.ceil( uv.x ) - uv.x;
  5897. } else {
  5898. uv.x = uv.x - Math.floor( uv.x );
  5899. }
  5900. break;
  5901. }
  5902. }
  5903. if ( uv.y < 0 || uv.y > 1 ) {
  5904. switch ( this.wrapT ) {
  5905. case RepeatWrapping:
  5906. uv.y = uv.y - Math.floor( uv.y );
  5907. break;
  5908. case ClampToEdgeWrapping:
  5909. uv.y = uv.y < 0 ? 0 : 1;
  5910. break;
  5911. case MirroredRepeatWrapping:
  5912. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5913. uv.y = Math.ceil( uv.y ) - uv.y;
  5914. } else {
  5915. uv.y = uv.y - Math.floor( uv.y );
  5916. }
  5917. break;
  5918. }
  5919. }
  5920. if ( this.flipY ) {
  5921. uv.y = 1 - uv.y;
  5922. }
  5923. return uv;
  5924. }
  5925. /**
  5926. * Setting this property to `true` indicates the engine the texture
  5927. * must be updated in the next render. This triggers a texture upload
  5928. * to the GPU and ensures correct texture parameter configuration.
  5929. *
  5930. * @type {boolean}
  5931. * @default false
  5932. * @param {boolean} value
  5933. */
  5934. set needsUpdate( value ) {
  5935. if ( value === true ) {
  5936. this.version ++;
  5937. this.source.needsUpdate = true;
  5938. }
  5939. }
  5940. /**
  5941. * Setting this property to `true` indicates the engine the PMREM
  5942. * must be regenerated.
  5943. *
  5944. * @type {boolean}
  5945. * @default false
  5946. * @param {boolean} value
  5947. */
  5948. set needsPMREMUpdate( value ) {
  5949. if ( value === true ) {
  5950. this.pmremVersion ++;
  5951. }
  5952. }
  5953. }
  5954. /**
  5955. * The default image for all textures.
  5956. *
  5957. * @static
  5958. * @type {?Image}
  5959. * @default null
  5960. */
  5961. Texture.DEFAULT_IMAGE = null;
  5962. /**
  5963. * The default mapping for all textures.
  5964. *
  5965. * @static
  5966. * @type {number}
  5967. * @default UVMapping
  5968. */
  5969. Texture.DEFAULT_MAPPING = UVMapping;
  5970. /**
  5971. * The default anisotropy value for all textures.
  5972. *
  5973. * @static
  5974. * @type {number}
  5975. * @default 1
  5976. */
  5977. Texture.DEFAULT_ANISOTROPY = 1;
  5978. /**
  5979. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  5980. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  5981. *
  5982. * - A point in 4D space.
  5983. * - A direction and length in 4D space. In three.js the length will
  5984. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  5985. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  5986. * - Any arbitrary ordered quadruplet of numbers.
  5987. *
  5988. * There are other things a 4D vector can be used to represent, however these
  5989. * are the most common uses in *three.js*.
  5990. *
  5991. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  5992. * the corresponding order.
  5993. * ```js
  5994. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  5995. *
  5996. * //no arguments; will be initialised to (0, 0, 0, 1)
  5997. * const b = new THREE.Vector4( );
  5998. *
  5999. * const d = a.dot( b );
  6000. * ```
  6001. */
  6002. class Vector4 {
  6003. /**
  6004. * Constructs a new 4D vector.
  6005. *
  6006. * @param {number} [x=0] - The x value of this vector.
  6007. * @param {number} [y=0] - The y value of this vector.
  6008. * @param {number} [z=0] - The z value of this vector.
  6009. * @param {number} [w=1] - The w value of this vector.
  6010. */
  6011. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6012. /**
  6013. * This flag can be used for type testing.
  6014. *
  6015. * @type {boolean}
  6016. * @readonly
  6017. * @default true
  6018. */
  6019. Vector4.prototype.isVector4 = true;
  6020. /**
  6021. * The x value of this vector.
  6022. *
  6023. * @type {number}
  6024. */
  6025. this.x = x;
  6026. /**
  6027. * The y value of this vector.
  6028. *
  6029. * @type {number}
  6030. */
  6031. this.y = y;
  6032. /**
  6033. * The z value of this vector.
  6034. *
  6035. * @type {number}
  6036. */
  6037. this.z = z;
  6038. /**
  6039. * The w value of this vector.
  6040. *
  6041. * @type {number}
  6042. */
  6043. this.w = w;
  6044. }
  6045. /**
  6046. * Alias for {@link Vector4#z}.
  6047. *
  6048. * @type {number}
  6049. */
  6050. get width() {
  6051. return this.z;
  6052. }
  6053. set width( value ) {
  6054. this.z = value;
  6055. }
  6056. /**
  6057. * Alias for {@link Vector4#w}.
  6058. *
  6059. * @type {number}
  6060. */
  6061. get height() {
  6062. return this.w;
  6063. }
  6064. set height( value ) {
  6065. this.w = value;
  6066. }
  6067. /**
  6068. * Sets the vector components.
  6069. *
  6070. * @param {number} x - The value of the x component.
  6071. * @param {number} y - The value of the y component.
  6072. * @param {number} z - The value of the z component.
  6073. * @param {number} w - The value of the w component.
  6074. * @return {Vector4} A reference to this vector.
  6075. */
  6076. set( x, y, z, w ) {
  6077. this.x = x;
  6078. this.y = y;
  6079. this.z = z;
  6080. this.w = w;
  6081. return this;
  6082. }
  6083. /**
  6084. * Sets the vector components to the same value.
  6085. *
  6086. * @param {number} scalar - The value to set for all vector components.
  6087. * @return {Vector4} A reference to this vector.
  6088. */
  6089. setScalar( scalar ) {
  6090. this.x = scalar;
  6091. this.y = scalar;
  6092. this.z = scalar;
  6093. this.w = scalar;
  6094. return this;
  6095. }
  6096. /**
  6097. * Sets the vector's x component to the given value
  6098. *
  6099. * @param {number} x - The value to set.
  6100. * @return {Vector4} A reference to this vector.
  6101. */
  6102. setX( x ) {
  6103. this.x = x;
  6104. return this;
  6105. }
  6106. /**
  6107. * Sets the vector's y component to the given value
  6108. *
  6109. * @param {number} y - The value to set.
  6110. * @return {Vector4} A reference to this vector.
  6111. */
  6112. setY( y ) {
  6113. this.y = y;
  6114. return this;
  6115. }
  6116. /**
  6117. * Sets the vector's z component to the given value
  6118. *
  6119. * @param {number} z - The value to set.
  6120. * @return {Vector4} A reference to this vector.
  6121. */
  6122. setZ( z ) {
  6123. this.z = z;
  6124. return this;
  6125. }
  6126. /**
  6127. * Sets the vector's w component to the given value
  6128. *
  6129. * @param {number} w - The value to set.
  6130. * @return {Vector4} A reference to this vector.
  6131. */
  6132. setW( w ) {
  6133. this.w = w;
  6134. return this;
  6135. }
  6136. /**
  6137. * Allows to set a vector component with an index.
  6138. *
  6139. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6140. * `2` equals to z, `3` equals to w.
  6141. * @param {number} value - The value to set.
  6142. * @return {Vector4} A reference to this vector.
  6143. */
  6144. setComponent( index, value ) {
  6145. switch ( index ) {
  6146. case 0: this.x = value; break;
  6147. case 1: this.y = value; break;
  6148. case 2: this.z = value; break;
  6149. case 3: this.w = value; break;
  6150. default: throw new Error( 'index is out of range: ' + index );
  6151. }
  6152. return this;
  6153. }
  6154. /**
  6155. * Returns the value of the vector component which matches the given index.
  6156. *
  6157. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6158. * `2` equals to z, `3` equals to w.
  6159. * @return {number} A vector component value.
  6160. */
  6161. getComponent( index ) {
  6162. switch ( index ) {
  6163. case 0: return this.x;
  6164. case 1: return this.y;
  6165. case 2: return this.z;
  6166. case 3: return this.w;
  6167. default: throw new Error( 'index is out of range: ' + index );
  6168. }
  6169. }
  6170. /**
  6171. * Returns a new vector with copied values from this instance.
  6172. *
  6173. * @return {Vector4} A clone of this instance.
  6174. */
  6175. clone() {
  6176. return new this.constructor( this.x, this.y, this.z, this.w );
  6177. }
  6178. /**
  6179. * Copies the values of the given vector to this instance.
  6180. *
  6181. * @param {Vector3|Vector4} v - The vector to copy.
  6182. * @return {Vector4} A reference to this vector.
  6183. */
  6184. copy( v ) {
  6185. this.x = v.x;
  6186. this.y = v.y;
  6187. this.z = v.z;
  6188. this.w = ( v.w !== undefined ) ? v.w : 1;
  6189. return this;
  6190. }
  6191. /**
  6192. * Adds the given vector to this instance.
  6193. *
  6194. * @param {Vector4} v - The vector to add.
  6195. * @return {Vector4} A reference to this vector.
  6196. */
  6197. add( v ) {
  6198. this.x += v.x;
  6199. this.y += v.y;
  6200. this.z += v.z;
  6201. this.w += v.w;
  6202. return this;
  6203. }
  6204. /**
  6205. * Adds the given scalar value to all components of this instance.
  6206. *
  6207. * @param {number} s - The scalar to add.
  6208. * @return {Vector4} A reference to this vector.
  6209. */
  6210. addScalar( s ) {
  6211. this.x += s;
  6212. this.y += s;
  6213. this.z += s;
  6214. this.w += s;
  6215. return this;
  6216. }
  6217. /**
  6218. * Adds the given vectors and stores the result in this instance.
  6219. *
  6220. * @param {Vector4} a - The first vector.
  6221. * @param {Vector4} b - The second vector.
  6222. * @return {Vector4} A reference to this vector.
  6223. */
  6224. addVectors( a, b ) {
  6225. this.x = a.x + b.x;
  6226. this.y = a.y + b.y;
  6227. this.z = a.z + b.z;
  6228. this.w = a.w + b.w;
  6229. return this;
  6230. }
  6231. /**
  6232. * Adds the given vector scaled by the given factor to this instance.
  6233. *
  6234. * @param {Vector4} v - The vector.
  6235. * @param {number} s - The factor that scales `v`.
  6236. * @return {Vector4} A reference to this vector.
  6237. */
  6238. addScaledVector( v, s ) {
  6239. this.x += v.x * s;
  6240. this.y += v.y * s;
  6241. this.z += v.z * s;
  6242. this.w += v.w * s;
  6243. return this;
  6244. }
  6245. /**
  6246. * Subtracts the given vector from this instance.
  6247. *
  6248. * @param {Vector4} v - The vector to subtract.
  6249. * @return {Vector4} A reference to this vector.
  6250. */
  6251. sub( v ) {
  6252. this.x -= v.x;
  6253. this.y -= v.y;
  6254. this.z -= v.z;
  6255. this.w -= v.w;
  6256. return this;
  6257. }
  6258. /**
  6259. * Subtracts the given scalar value from all components of this instance.
  6260. *
  6261. * @param {number} s - The scalar to subtract.
  6262. * @return {Vector4} A reference to this vector.
  6263. */
  6264. subScalar( s ) {
  6265. this.x -= s;
  6266. this.y -= s;
  6267. this.z -= s;
  6268. this.w -= s;
  6269. return this;
  6270. }
  6271. /**
  6272. * Subtracts the given vectors and stores the result in this instance.
  6273. *
  6274. * @param {Vector4} a - The first vector.
  6275. * @param {Vector4} b - The second vector.
  6276. * @return {Vector4} A reference to this vector.
  6277. */
  6278. subVectors( a, b ) {
  6279. this.x = a.x - b.x;
  6280. this.y = a.y - b.y;
  6281. this.z = a.z - b.z;
  6282. this.w = a.w - b.w;
  6283. return this;
  6284. }
  6285. /**
  6286. * Multiplies the given vector with this instance.
  6287. *
  6288. * @param {Vector4} v - The vector to multiply.
  6289. * @return {Vector4} A reference to this vector.
  6290. */
  6291. multiply( v ) {
  6292. this.x *= v.x;
  6293. this.y *= v.y;
  6294. this.z *= v.z;
  6295. this.w *= v.w;
  6296. return this;
  6297. }
  6298. /**
  6299. * Multiplies the given scalar value with all components of this instance.
  6300. *
  6301. * @param {number} scalar - The scalar to multiply.
  6302. * @return {Vector4} A reference to this vector.
  6303. */
  6304. multiplyScalar( scalar ) {
  6305. this.x *= scalar;
  6306. this.y *= scalar;
  6307. this.z *= scalar;
  6308. this.w *= scalar;
  6309. return this;
  6310. }
  6311. /**
  6312. * Multiplies this vector with the given 4x4 matrix.
  6313. *
  6314. * @param {Matrix4} m - The 4x4 matrix.
  6315. * @return {Vector4} A reference to this vector.
  6316. */
  6317. applyMatrix4( m ) {
  6318. const x = this.x, y = this.y, z = this.z, w = this.w;
  6319. const e = m.elements;
  6320. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6321. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6322. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6323. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6324. return this;
  6325. }
  6326. /**
  6327. * Divides this instance by the given vector.
  6328. *
  6329. * @param {Vector4} v - The vector to divide.
  6330. * @return {Vector4} A reference to this vector.
  6331. */
  6332. divide( v ) {
  6333. this.x /= v.x;
  6334. this.y /= v.y;
  6335. this.z /= v.z;
  6336. this.w /= v.w;
  6337. return this;
  6338. }
  6339. /**
  6340. * Divides this vector by the given scalar.
  6341. *
  6342. * @param {number} scalar - The scalar to divide.
  6343. * @return {Vector4} A reference to this vector.
  6344. */
  6345. divideScalar( scalar ) {
  6346. return this.multiplyScalar( 1 / scalar );
  6347. }
  6348. /**
  6349. * Sets the x, y and z components of this
  6350. * vector to the quaternion's axis and w to the angle.
  6351. *
  6352. * @param {Quaternion} q - The Quaternion to set.
  6353. * @return {Vector4} A reference to this vector.
  6354. */
  6355. setAxisAngleFromQuaternion( q ) {
  6356. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6357. // q is assumed to be normalized
  6358. this.w = 2 * Math.acos( q.w );
  6359. const s = Math.sqrt( 1 - q.w * q.w );
  6360. if ( s < 0.0001 ) {
  6361. this.x = 1;
  6362. this.y = 0;
  6363. this.z = 0;
  6364. } else {
  6365. this.x = q.x / s;
  6366. this.y = q.y / s;
  6367. this.z = q.z / s;
  6368. }
  6369. return this;
  6370. }
  6371. /**
  6372. * Sets the x, y and z components of this
  6373. * vector to the axis of rotation and w to the angle.
  6374. *
  6375. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6376. * @return {Vector4} A reference to this vector.
  6377. */
  6378. setAxisAngleFromRotationMatrix( m ) {
  6379. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6380. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6381. let angle, x, y, z; // variables for result
  6382. const epsilon = 0.01, // margin to allow for rounding errors
  6383. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6384. te = m.elements,
  6385. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6386. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6387. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6388. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6389. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6390. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6391. // singularity found
  6392. // first check for identity matrix which must have +1 for all terms
  6393. // in leading diagonal and zero in other terms
  6394. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6395. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6396. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6397. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6398. // this singularity is identity matrix so angle = 0
  6399. this.set( 1, 0, 0, 0 );
  6400. return this; // zero angle, arbitrary axis
  6401. }
  6402. // otherwise this singularity is angle = 180
  6403. angle = Math.PI;
  6404. const xx = ( m11 + 1 ) / 2;
  6405. const yy = ( m22 + 1 ) / 2;
  6406. const zz = ( m33 + 1 ) / 2;
  6407. const xy = ( m12 + m21 ) / 4;
  6408. const xz = ( m13 + m31 ) / 4;
  6409. const yz = ( m23 + m32 ) / 4;
  6410. if ( ( xx > yy ) && ( xx > zz ) ) {
  6411. // m11 is the largest diagonal term
  6412. if ( xx < epsilon ) {
  6413. x = 0;
  6414. y = 0.707106781;
  6415. z = 0.707106781;
  6416. } else {
  6417. x = Math.sqrt( xx );
  6418. y = xy / x;
  6419. z = xz / x;
  6420. }
  6421. } else if ( yy > zz ) {
  6422. // m22 is the largest diagonal term
  6423. if ( yy < epsilon ) {
  6424. x = 0.707106781;
  6425. y = 0;
  6426. z = 0.707106781;
  6427. } else {
  6428. y = Math.sqrt( yy );
  6429. x = xy / y;
  6430. z = yz / y;
  6431. }
  6432. } else {
  6433. // m33 is the largest diagonal term so base result on this
  6434. if ( zz < epsilon ) {
  6435. x = 0.707106781;
  6436. y = 0.707106781;
  6437. z = 0;
  6438. } else {
  6439. z = Math.sqrt( zz );
  6440. x = xz / z;
  6441. y = yz / z;
  6442. }
  6443. }
  6444. this.set( x, y, z, angle );
  6445. return this; // return 180 deg rotation
  6446. }
  6447. // as we have reached here there are no singularities so we can handle normally
  6448. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6449. ( m13 - m31 ) * ( m13 - m31 ) +
  6450. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6451. if ( Math.abs( s ) < 0.001 ) s = 1;
  6452. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6453. // caught by singularity test above, but I've left it in just in case
  6454. this.x = ( m32 - m23 ) / s;
  6455. this.y = ( m13 - m31 ) / s;
  6456. this.z = ( m21 - m12 ) / s;
  6457. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6458. return this;
  6459. }
  6460. /**
  6461. * Sets the vector components to the position elements of the
  6462. * given transformation matrix.
  6463. *
  6464. * @param {Matrix4} m - The 4x4 matrix.
  6465. * @return {Vector4} A reference to this vector.
  6466. */
  6467. setFromMatrixPosition( m ) {
  6468. const e = m.elements;
  6469. this.x = e[ 12 ];
  6470. this.y = e[ 13 ];
  6471. this.z = e[ 14 ];
  6472. this.w = e[ 15 ];
  6473. return this;
  6474. }
  6475. /**
  6476. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6477. * value, replace that value with the corresponding min value.
  6478. *
  6479. * @param {Vector4} v - The vector.
  6480. * @return {Vector4} A reference to this vector.
  6481. */
  6482. min( v ) {
  6483. this.x = Math.min( this.x, v.x );
  6484. this.y = Math.min( this.y, v.y );
  6485. this.z = Math.min( this.z, v.z );
  6486. this.w = Math.min( this.w, v.w );
  6487. return this;
  6488. }
  6489. /**
  6490. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6491. * value, replace that value with the corresponding max value.
  6492. *
  6493. * @param {Vector4} v - The vector.
  6494. * @return {Vector4} A reference to this vector.
  6495. */
  6496. max( v ) {
  6497. this.x = Math.max( this.x, v.x );
  6498. this.y = Math.max( this.y, v.y );
  6499. this.z = Math.max( this.z, v.z );
  6500. this.w = Math.max( this.w, v.w );
  6501. return this;
  6502. }
  6503. /**
  6504. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6505. * value, it is replaced by the corresponding value.
  6506. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6507. * it is replaced by the corresponding value.
  6508. *
  6509. * @param {Vector4} min - The minimum x, y and z values.
  6510. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6511. * @return {Vector4} A reference to this vector.
  6512. */
  6513. clamp( min, max ) {
  6514. // assumes min < max, componentwise
  6515. this.x = clamp( this.x, min.x, max.x );
  6516. this.y = clamp( this.y, min.y, max.y );
  6517. this.z = clamp( this.z, min.z, max.z );
  6518. this.w = clamp( this.w, min.w, max.w );
  6519. return this;
  6520. }
  6521. /**
  6522. * If this vector's x, y, z or w values are greater than the max value, they are
  6523. * replaced by the max value.
  6524. * If this vector's x, y, z or w values are less than the min value, they are
  6525. * replaced by the min value.
  6526. *
  6527. * @param {number} minVal - The minimum value the components will be clamped to.
  6528. * @param {number} maxVal - The maximum value the components will be clamped to.
  6529. * @return {Vector4} A reference to this vector.
  6530. */
  6531. clampScalar( minVal, maxVal ) {
  6532. this.x = clamp( this.x, minVal, maxVal );
  6533. this.y = clamp( this.y, minVal, maxVal );
  6534. this.z = clamp( this.z, minVal, maxVal );
  6535. this.w = clamp( this.w, minVal, maxVal );
  6536. return this;
  6537. }
  6538. /**
  6539. * If this vector's length is greater than the max value, it is replaced by
  6540. * the max value.
  6541. * If this vector's length is less than the min value, it is replaced by the
  6542. * min value.
  6543. *
  6544. * @param {number} min - The minimum value the vector length will be clamped to.
  6545. * @param {number} max - The maximum value the vector length will be clamped to.
  6546. * @return {Vector4} A reference to this vector.
  6547. */
  6548. clampLength( min, max ) {
  6549. const length = this.length();
  6550. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6551. }
  6552. /**
  6553. * The components of this vector are rounded down to the nearest integer value.
  6554. *
  6555. * @return {Vector4} A reference to this vector.
  6556. */
  6557. floor() {
  6558. this.x = Math.floor( this.x );
  6559. this.y = Math.floor( this.y );
  6560. this.z = Math.floor( this.z );
  6561. this.w = Math.floor( this.w );
  6562. return this;
  6563. }
  6564. /**
  6565. * The components of this vector are rounded up to the nearest integer value.
  6566. *
  6567. * @return {Vector4} A reference to this vector.
  6568. */
  6569. ceil() {
  6570. this.x = Math.ceil( this.x );
  6571. this.y = Math.ceil( this.y );
  6572. this.z = Math.ceil( this.z );
  6573. this.w = Math.ceil( this.w );
  6574. return this;
  6575. }
  6576. /**
  6577. * The components of this vector are rounded to the nearest integer value
  6578. *
  6579. * @return {Vector4} A reference to this vector.
  6580. */
  6581. round() {
  6582. this.x = Math.round( this.x );
  6583. this.y = Math.round( this.y );
  6584. this.z = Math.round( this.z );
  6585. this.w = Math.round( this.w );
  6586. return this;
  6587. }
  6588. /**
  6589. * The components of this vector are rounded towards zero (up if negative,
  6590. * down if positive) to an integer value.
  6591. *
  6592. * @return {Vector4} A reference to this vector.
  6593. */
  6594. roundToZero() {
  6595. this.x = Math.trunc( this.x );
  6596. this.y = Math.trunc( this.y );
  6597. this.z = Math.trunc( this.z );
  6598. this.w = Math.trunc( this.w );
  6599. return this;
  6600. }
  6601. /**
  6602. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6603. *
  6604. * @return {Vector4} A reference to this vector.
  6605. */
  6606. negate() {
  6607. this.x = - this.x;
  6608. this.y = - this.y;
  6609. this.z = - this.z;
  6610. this.w = - this.w;
  6611. return this;
  6612. }
  6613. /**
  6614. * Calculates the dot product of the given vector with this instance.
  6615. *
  6616. * @param {Vector4} v - The vector to compute the dot product with.
  6617. * @return {number} The result of the dot product.
  6618. */
  6619. dot( v ) {
  6620. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6621. }
  6622. /**
  6623. * Computes the square of the Euclidean length (straight-line length) from
  6624. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6625. * compare the length squared instead as it is slightly more efficient to calculate.
  6626. *
  6627. * @return {number} The square length of this vector.
  6628. */
  6629. lengthSq() {
  6630. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6631. }
  6632. /**
  6633. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6634. *
  6635. * @return {number} The length of this vector.
  6636. */
  6637. length() {
  6638. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6639. }
  6640. /**
  6641. * Computes the Manhattan length of this vector.
  6642. *
  6643. * @return {number} The length of this vector.
  6644. */
  6645. manhattanLength() {
  6646. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6647. }
  6648. /**
  6649. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6650. * with the same direction as this one, but with a vector length of `1`.
  6651. *
  6652. * @return {Vector4} A reference to this vector.
  6653. */
  6654. normalize() {
  6655. return this.divideScalar( this.length() || 1 );
  6656. }
  6657. /**
  6658. * Sets this vector to a vector with the same direction as this one, but
  6659. * with the specified length.
  6660. *
  6661. * @param {number} length - The new length of this vector.
  6662. * @return {Vector4} A reference to this vector.
  6663. */
  6664. setLength( length ) {
  6665. return this.normalize().multiplyScalar( length );
  6666. }
  6667. /**
  6668. * Linearly interpolates between the given vector and this instance, where
  6669. * alpha is the percent distance along the line - alpha = 0 will be this
  6670. * vector, and alpha = 1 will be the given one.
  6671. *
  6672. * @param {Vector4} v - The vector to interpolate towards.
  6673. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6674. * @return {Vector4} A reference to this vector.
  6675. */
  6676. lerp( v, alpha ) {
  6677. this.x += ( v.x - this.x ) * alpha;
  6678. this.y += ( v.y - this.y ) * alpha;
  6679. this.z += ( v.z - this.z ) * alpha;
  6680. this.w += ( v.w - this.w ) * alpha;
  6681. return this;
  6682. }
  6683. /**
  6684. * Linearly interpolates between the given vectors, where alpha is the percent
  6685. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6686. * be the second one. The result is stored in this instance.
  6687. *
  6688. * @param {Vector4} v1 - The first vector.
  6689. * @param {Vector4} v2 - The second vector.
  6690. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6691. * @return {Vector4} A reference to this vector.
  6692. */
  6693. lerpVectors( v1, v2, alpha ) {
  6694. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6695. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6696. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6697. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6698. return this;
  6699. }
  6700. /**
  6701. * Returns `true` if this vector is equal with the given one.
  6702. *
  6703. * @param {Vector4} v - The vector to test for equality.
  6704. * @return {boolean} Whether this vector is equal with the given one.
  6705. */
  6706. equals( v ) {
  6707. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6708. }
  6709. /**
  6710. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6711. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6712. *
  6713. * @param {Array<number>} array - An array holding the vector component values.
  6714. * @param {number} [offset=0] - The offset into the array.
  6715. * @return {Vector4} A reference to this vector.
  6716. */
  6717. fromArray( array, offset = 0 ) {
  6718. this.x = array[ offset ];
  6719. this.y = array[ offset + 1 ];
  6720. this.z = array[ offset + 2 ];
  6721. this.w = array[ offset + 3 ];
  6722. return this;
  6723. }
  6724. /**
  6725. * Writes the components of this vector to the given array. If no array is provided,
  6726. * the method returns a new instance.
  6727. *
  6728. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6729. * @param {number} [offset=0] - Index of the first element in the array.
  6730. * @return {Array<number>} The vector components.
  6731. */
  6732. toArray( array = [], offset = 0 ) {
  6733. array[ offset ] = this.x;
  6734. array[ offset + 1 ] = this.y;
  6735. array[ offset + 2 ] = this.z;
  6736. array[ offset + 3 ] = this.w;
  6737. return array;
  6738. }
  6739. /**
  6740. * Sets the components of this vector from the given buffer attribute.
  6741. *
  6742. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6743. * @param {number} index - The index into the attribute.
  6744. * @return {Vector4} A reference to this vector.
  6745. */
  6746. fromBufferAttribute( attribute, index ) {
  6747. this.x = attribute.getX( index );
  6748. this.y = attribute.getY( index );
  6749. this.z = attribute.getZ( index );
  6750. this.w = attribute.getW( index );
  6751. return this;
  6752. }
  6753. /**
  6754. * Sets each component of this vector to a pseudo-random value between `0` and
  6755. * `1`, excluding `1`.
  6756. *
  6757. * @return {Vector4} A reference to this vector.
  6758. */
  6759. random() {
  6760. this.x = Math.random();
  6761. this.y = Math.random();
  6762. this.z = Math.random();
  6763. this.w = Math.random();
  6764. return this;
  6765. }
  6766. *[ Symbol.iterator ]() {
  6767. yield this.x;
  6768. yield this.y;
  6769. yield this.z;
  6770. yield this.w;
  6771. }
  6772. }
  6773. /**
  6774. * A render target is a buffer where the video card draws pixels for a scene
  6775. * that is being rendered in the background. It is used in different effects,
  6776. * such as applying postprocessing to a rendered image before displaying it
  6777. * on the screen.
  6778. *
  6779. * @augments EventDispatcher
  6780. */
  6781. class RenderTarget extends EventDispatcher {
  6782. /**
  6783. * Render target options.
  6784. *
  6785. * @typedef {Object} RenderTarget~Options
  6786. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6787. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6788. * @property {number} [minFilter=LinearFilter] - The min filter.
  6789. * @property {number} [format=RGBAFormat] - The texture format.
  6790. * @property {number} [type=UnsignedByteType] - The texture type.
  6791. * @property {?string} [internalFormat=null] - The texture's internal format.
  6792. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6793. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6794. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6795. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6796. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6797. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6798. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6799. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6800. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6801. * @property {number} [samples=0] - The MSAA samples count.
  6802. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6803. * @property {number} [depth=1] - The texture depth.
  6804. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6805. */
  6806. /**
  6807. * Constructs a new render target.
  6808. *
  6809. * @param {number} [width=1] - The width of the render target.
  6810. * @param {number} [height=1] - The height of the render target.
  6811. * @param {RenderTarget~Options} [options] - The configuration object.
  6812. */
  6813. constructor( width = 1, height = 1, options = {} ) {
  6814. super();
  6815. options = Object.assign( {
  6816. generateMipmaps: false,
  6817. internalFormat: null,
  6818. minFilter: LinearFilter,
  6819. depthBuffer: true,
  6820. stencilBuffer: false,
  6821. resolveDepthBuffer: true,
  6822. resolveStencilBuffer: true,
  6823. depthTexture: null,
  6824. samples: 0,
  6825. count: 1,
  6826. depth: 1,
  6827. multiview: false
  6828. }, options );
  6829. /**
  6830. * This flag can be used for type testing.
  6831. *
  6832. * @type {boolean}
  6833. * @readonly
  6834. * @default true
  6835. */
  6836. this.isRenderTarget = true;
  6837. /**
  6838. * The width of the render target.
  6839. *
  6840. * @type {number}
  6841. * @default 1
  6842. */
  6843. this.width = width;
  6844. /**
  6845. * The height of the render target.
  6846. *
  6847. * @type {number}
  6848. * @default 1
  6849. */
  6850. this.height = height;
  6851. /**
  6852. * The depth of the render target.
  6853. *
  6854. * @type {number}
  6855. * @default 1
  6856. */
  6857. this.depth = options.depth;
  6858. /**
  6859. * A rectangular area inside the render target's viewport. Fragments that are
  6860. * outside the area will be discarded.
  6861. *
  6862. * @type {Vector4}
  6863. * @default (0,0,width,height)
  6864. */
  6865. this.scissor = new Vector4( 0, 0, width, height );
  6866. /**
  6867. * Indicates whether the scissor test should be enabled when rendering into
  6868. * this render target or not.
  6869. *
  6870. * @type {boolean}
  6871. * @default false
  6872. */
  6873. this.scissorTest = false;
  6874. /**
  6875. * A rectangular area representing the render target's viewport.
  6876. *
  6877. * @type {Vector4}
  6878. * @default (0,0,width,height)
  6879. */
  6880. this.viewport = new Vector4( 0, 0, width, height );
  6881. const image = { width: width, height: height, depth: options.depth };
  6882. const texture = new Texture( image );
  6883. /**
  6884. * An array of textures. Each color attachment is represented as a separate texture.
  6885. * Has at least a single entry for the default color attachment.
  6886. *
  6887. * @type {Array<Texture>}
  6888. */
  6889. this.textures = [];
  6890. const count = options.count;
  6891. for ( let i = 0; i < count; i ++ ) {
  6892. this.textures[ i ] = texture.clone();
  6893. this.textures[ i ].isRenderTargetTexture = true;
  6894. this.textures[ i ].renderTarget = this;
  6895. }
  6896. this._setTextureOptions( options );
  6897. /**
  6898. * Whether to allocate a depth buffer or not.
  6899. *
  6900. * @type {boolean}
  6901. * @default true
  6902. */
  6903. this.depthBuffer = options.depthBuffer;
  6904. /**
  6905. * Whether to allocate a stencil buffer or not.
  6906. *
  6907. * @type {boolean}
  6908. * @default false
  6909. */
  6910. this.stencilBuffer = options.stencilBuffer;
  6911. /**
  6912. * Whether to resolve the depth buffer or not.
  6913. *
  6914. * @type {boolean}
  6915. * @default true
  6916. */
  6917. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6918. /**
  6919. * Whether to resolve the stencil buffer or not.
  6920. *
  6921. * @type {boolean}
  6922. * @default true
  6923. */
  6924. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6925. this._depthTexture = null;
  6926. this.depthTexture = options.depthTexture;
  6927. /**
  6928. * The number of MSAA samples.
  6929. *
  6930. * A value of `0` disables MSAA.
  6931. *
  6932. * @type {number}
  6933. * @default 0
  6934. */
  6935. this.samples = options.samples;
  6936. /**
  6937. * Whether to this target is used in multiview rendering.
  6938. *
  6939. * @type {boolean}
  6940. * @default false
  6941. */
  6942. this.multiview = options.multiview;
  6943. }
  6944. _setTextureOptions( options = {} ) {
  6945. const values = {
  6946. minFilter: LinearFilter,
  6947. generateMipmaps: false,
  6948. flipY: false,
  6949. internalFormat: null
  6950. };
  6951. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6952. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6953. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6954. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6955. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6956. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6957. if ( options.format !== undefined ) values.format = options.format;
  6958. if ( options.type !== undefined ) values.type = options.type;
  6959. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6960. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6961. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6962. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6963. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6964. for ( let i = 0; i < this.textures.length; i ++ ) {
  6965. const texture = this.textures[ i ];
  6966. texture.setValues( values );
  6967. }
  6968. }
  6969. /**
  6970. * The texture representing the default color attachment.
  6971. *
  6972. * @type {Texture}
  6973. */
  6974. get texture() {
  6975. return this.textures[ 0 ];
  6976. }
  6977. set texture( value ) {
  6978. this.textures[ 0 ] = value;
  6979. }
  6980. set depthTexture( current ) {
  6981. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  6982. if ( current !== null ) current.renderTarget = this;
  6983. this._depthTexture = current;
  6984. }
  6985. /**
  6986. * Instead of saving the depth in a renderbuffer, a texture
  6987. * can be used instead which is useful for further processing
  6988. * e.g. in context of post-processing.
  6989. *
  6990. * @type {?DepthTexture}
  6991. * @default null
  6992. */
  6993. get depthTexture() {
  6994. return this._depthTexture;
  6995. }
  6996. /**
  6997. * Sets the size of this render target.
  6998. *
  6999. * @param {number} width - The width.
  7000. * @param {number} height - The height.
  7001. * @param {number} [depth=1] - The depth.
  7002. */
  7003. setSize( width, height, depth = 1 ) {
  7004. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7005. this.width = width;
  7006. this.height = height;
  7007. this.depth = depth;
  7008. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7009. this.textures[ i ].image.width = width;
  7010. this.textures[ i ].image.height = height;
  7011. this.textures[ i ].image.depth = depth;
  7012. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7013. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7014. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7015. // both are evaluated on each call?
  7016. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7017. }
  7018. }
  7019. this.dispose();
  7020. }
  7021. this.viewport.set( 0, 0, width, height );
  7022. this.scissor.set( 0, 0, width, height );
  7023. }
  7024. /**
  7025. * Returns a new render target with copied values from this instance.
  7026. *
  7027. * @return {RenderTarget} A clone of this instance.
  7028. */
  7029. clone() {
  7030. return new this.constructor().copy( this );
  7031. }
  7032. /**
  7033. * Copies the settings of the given render target. This is a structural copy so
  7034. * no resources are shared between render targets after the copy. That includes
  7035. * all MRT textures and the depth texture.
  7036. *
  7037. * @param {RenderTarget} source - The render target to copy.
  7038. * @return {RenderTarget} A reference to this instance.
  7039. */
  7040. copy( source ) {
  7041. this.width = source.width;
  7042. this.height = source.height;
  7043. this.depth = source.depth;
  7044. this.scissor.copy( source.scissor );
  7045. this.scissorTest = source.scissorTest;
  7046. this.viewport.copy( source.viewport );
  7047. this.textures.length = 0;
  7048. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7049. this.textures[ i ] = source.textures[ i ].clone();
  7050. this.textures[ i ].isRenderTargetTexture = true;
  7051. this.textures[ i ].renderTarget = this;
  7052. // ensure image object is not shared, see #20328
  7053. const image = Object.assign( {}, source.textures[ i ].image );
  7054. this.textures[ i ].source = new Source( image );
  7055. }
  7056. this.depthBuffer = source.depthBuffer;
  7057. this.stencilBuffer = source.stencilBuffer;
  7058. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7059. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7060. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7061. this.samples = source.samples;
  7062. return this;
  7063. }
  7064. /**
  7065. * Frees the GPU-related resources allocated by this instance. Call this
  7066. * method whenever this instance is no longer used in your app.
  7067. *
  7068. * @fires RenderTarget#dispose
  7069. */
  7070. dispose() {
  7071. this.dispatchEvent( { type: 'dispose' } );
  7072. }
  7073. }
  7074. /**
  7075. * A render target used in context of {@link WebGLRenderer}.
  7076. *
  7077. * @augments RenderTarget
  7078. */
  7079. class WebGLRenderTarget extends RenderTarget {
  7080. /**
  7081. * Constructs a new 3D render target.
  7082. *
  7083. * @param {number} [width=1] - The width of the render target.
  7084. * @param {number} [height=1] - The height of the render target.
  7085. * @param {RenderTarget~Options} [options] - The configuration object.
  7086. */
  7087. constructor( width = 1, height = 1, options = {} ) {
  7088. super( width, height, options );
  7089. /**
  7090. * This flag can be used for type testing.
  7091. *
  7092. * @type {boolean}
  7093. * @readonly
  7094. * @default true
  7095. */
  7096. this.isWebGLRenderTarget = true;
  7097. }
  7098. }
  7099. /**
  7100. * Creates an array of textures directly from raw buffer data.
  7101. *
  7102. * @augments Texture
  7103. */
  7104. class DataArrayTexture extends Texture {
  7105. /**
  7106. * Constructs a new data array texture.
  7107. *
  7108. * @param {?TypedArray} [data=null] - The buffer data.
  7109. * @param {number} [width=1] - The width of the texture.
  7110. * @param {number} [height=1] - The height of the texture.
  7111. * @param {number} [depth=1] - The depth of the texture.
  7112. */
  7113. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7114. super( null );
  7115. /**
  7116. * This flag can be used for type testing.
  7117. *
  7118. * @type {boolean}
  7119. * @readonly
  7120. * @default true
  7121. */
  7122. this.isDataArrayTexture = true;
  7123. /**
  7124. * The image definition of a data texture.
  7125. *
  7126. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7127. */
  7128. this.image = { data, width, height, depth };
  7129. /**
  7130. * How the texture is sampled when a texel covers more than one pixel.
  7131. *
  7132. * Overwritten and set to `NearestFilter` by default.
  7133. *
  7134. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7135. * @default NearestFilter
  7136. */
  7137. this.magFilter = NearestFilter;
  7138. /**
  7139. * How the texture is sampled when a texel covers less than one pixel.
  7140. *
  7141. * Overwritten and set to `NearestFilter` by default.
  7142. *
  7143. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7144. * @default NearestFilter
  7145. */
  7146. this.minFilter = NearestFilter;
  7147. /**
  7148. * This defines how the texture is wrapped in the depth and corresponds to
  7149. * *W* in UVW mapping.
  7150. *
  7151. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7152. * @default ClampToEdgeWrapping
  7153. */
  7154. this.wrapR = ClampToEdgeWrapping;
  7155. /**
  7156. * Whether to generate mipmaps (if possible) for a texture.
  7157. *
  7158. * Overwritten and set to `false` by default.
  7159. *
  7160. * @type {boolean}
  7161. * @default false
  7162. */
  7163. this.generateMipmaps = false;
  7164. /**
  7165. * If set to `true`, the texture is flipped along the vertical axis when
  7166. * uploaded to the GPU.
  7167. *
  7168. * Overwritten and set to `false` by default.
  7169. *
  7170. * @type {boolean}
  7171. * @default false
  7172. */
  7173. this.flipY = false;
  7174. /**
  7175. * Specifies the alignment requirements for the start of each pixel row in memory.
  7176. *
  7177. * Overwritten and set to `1` by default.
  7178. *
  7179. * @type {boolean}
  7180. * @default 1
  7181. */
  7182. this.unpackAlignment = 1;
  7183. /**
  7184. * A set of all layers which need to be updated in the texture.
  7185. *
  7186. * @type {Set<number>}
  7187. */
  7188. this.layerUpdates = new Set();
  7189. }
  7190. /**
  7191. * Describes that a specific layer of the texture needs to be updated.
  7192. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7193. * entire data texture array is sent to the GPU. Marking specific
  7194. * layers will only transmit subsets of all mipmaps associated with a
  7195. * specific depth in the array which is often much more performant.
  7196. *
  7197. * @param {number} layerIndex - The layer index that should be updated.
  7198. */
  7199. addLayerUpdate( layerIndex ) {
  7200. this.layerUpdates.add( layerIndex );
  7201. }
  7202. /**
  7203. * Resets the layer updates registry.
  7204. */
  7205. clearLayerUpdates() {
  7206. this.layerUpdates.clear();
  7207. }
  7208. }
  7209. /**
  7210. * An array render target used in context of {@link WebGLRenderer}.
  7211. *
  7212. * @augments WebGLRenderTarget
  7213. */
  7214. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7215. /**
  7216. * Constructs a new array render target.
  7217. *
  7218. * @param {number} [width=1] - The width of the render target.
  7219. * @param {number} [height=1] - The height of the render target.
  7220. * @param {number} [depth=1] - The height of the render target.
  7221. * @param {RenderTarget~Options} [options] - The configuration object.
  7222. */
  7223. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7224. super( width, height, options );
  7225. /**
  7226. * This flag can be used for type testing.
  7227. *
  7228. * @type {boolean}
  7229. * @readonly
  7230. * @default true
  7231. */
  7232. this.isWebGLArrayRenderTarget = true;
  7233. this.depth = depth;
  7234. /**
  7235. * Overwritten with a different texture type.
  7236. *
  7237. * @type {DataArrayTexture}
  7238. */
  7239. this.texture = new DataArrayTexture( null, width, height, depth );
  7240. this._setTextureOptions( options );
  7241. this.texture.isRenderTargetTexture = true;
  7242. }
  7243. }
  7244. /**
  7245. * Creates a three-dimensional texture from raw data, with parameters to
  7246. * divide it into width, height, and depth.
  7247. *
  7248. * @augments Texture
  7249. */
  7250. class Data3DTexture extends Texture {
  7251. /**
  7252. * Constructs a new data array texture.
  7253. *
  7254. * @param {?TypedArray} [data=null] - The buffer data.
  7255. * @param {number} [width=1] - The width of the texture.
  7256. * @param {number} [height=1] - The height of the texture.
  7257. * @param {number} [depth=1] - The depth of the texture.
  7258. */
  7259. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7260. // We're going to add .setXXX() methods for setting properties later.
  7261. // Users can still set in Data3DTexture directly.
  7262. //
  7263. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7264. // texture.anisotropy = 16;
  7265. //
  7266. // See #14839
  7267. super( null );
  7268. /**
  7269. * This flag can be used for type testing.
  7270. *
  7271. * @type {boolean}
  7272. * @readonly
  7273. * @default true
  7274. */
  7275. this.isData3DTexture = true;
  7276. /**
  7277. * The image definition of a data texture.
  7278. *
  7279. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7280. */
  7281. this.image = { data, width, height, depth };
  7282. /**
  7283. * How the texture is sampled when a texel covers more than one pixel.
  7284. *
  7285. * Overwritten and set to `NearestFilter` by default.
  7286. *
  7287. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7288. * @default NearestFilter
  7289. */
  7290. this.magFilter = NearestFilter;
  7291. /**
  7292. * How the texture is sampled when a texel covers less than one pixel.
  7293. *
  7294. * Overwritten and set to `NearestFilter` by default.
  7295. *
  7296. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7297. * @default NearestFilter
  7298. */
  7299. this.minFilter = NearestFilter;
  7300. /**
  7301. * This defines how the texture is wrapped in the depth and corresponds to
  7302. * *W* in UVW mapping.
  7303. *
  7304. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7305. * @default ClampToEdgeWrapping
  7306. */
  7307. this.wrapR = ClampToEdgeWrapping;
  7308. /**
  7309. * Whether to generate mipmaps (if possible) for a texture.
  7310. *
  7311. * Overwritten and set to `false` by default.
  7312. *
  7313. * @type {boolean}
  7314. * @default false
  7315. */
  7316. this.generateMipmaps = false;
  7317. /**
  7318. * If set to `true`, the texture is flipped along the vertical axis when
  7319. * uploaded to the GPU.
  7320. *
  7321. * Overwritten and set to `false` by default.
  7322. *
  7323. * @type {boolean}
  7324. * @default false
  7325. */
  7326. this.flipY = false;
  7327. /**
  7328. * Specifies the alignment requirements for the start of each pixel row in memory.
  7329. *
  7330. * Overwritten and set to `1` by default.
  7331. *
  7332. * @type {boolean}
  7333. * @default 1
  7334. */
  7335. this.unpackAlignment = 1;
  7336. }
  7337. }
  7338. /**
  7339. * A 3D render target used in context of {@link WebGLRenderer}.
  7340. *
  7341. * @augments WebGLRenderTarget
  7342. */
  7343. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7344. /**
  7345. * Constructs a new 3D render target.
  7346. *
  7347. * @param {number} [width=1] - The width of the render target.
  7348. * @param {number} [height=1] - The height of the render target.
  7349. * @param {number} [depth=1] - The height of the render target.
  7350. * @param {RenderTarget~Options} [options] - The configuration object.
  7351. */
  7352. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7353. super( width, height, options );
  7354. /**
  7355. * This flag can be used for type testing.
  7356. *
  7357. * @type {boolean}
  7358. * @readonly
  7359. * @default true
  7360. */
  7361. this.isWebGL3DRenderTarget = true;
  7362. this.depth = depth;
  7363. /**
  7364. * Overwritten with a different texture type.
  7365. *
  7366. * @type {Data3DTexture}
  7367. */
  7368. this.texture = new Data3DTexture( null, width, height, depth );
  7369. this._setTextureOptions( options );
  7370. this.texture.isRenderTargetTexture = true;
  7371. }
  7372. }
  7373. /**
  7374. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7375. */
  7376. class Box3 {
  7377. /**
  7378. * Constructs a new bounding box.
  7379. *
  7380. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7381. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7382. */
  7383. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7384. /**
  7385. * This flag can be used for type testing.
  7386. *
  7387. * @type {boolean}
  7388. * @readonly
  7389. * @default true
  7390. */
  7391. this.isBox3 = true;
  7392. /**
  7393. * The lower boundary of the box.
  7394. *
  7395. * @type {Vector3}
  7396. */
  7397. this.min = min;
  7398. /**
  7399. * The upper boundary of the box.
  7400. *
  7401. * @type {Vector3}
  7402. */
  7403. this.max = max;
  7404. }
  7405. /**
  7406. * Sets the lower and upper boundaries of this box.
  7407. * Please note that this method only copies the values from the given objects.
  7408. *
  7409. * @param {Vector3} min - The lower boundary of the box.
  7410. * @param {Vector3} max - The upper boundary of the box.
  7411. * @return {Box3} A reference to this bounding box.
  7412. */
  7413. set( min, max ) {
  7414. this.min.copy( min );
  7415. this.max.copy( max );
  7416. return this;
  7417. }
  7418. /**
  7419. * Sets the upper and lower bounds of this box so it encloses the position data
  7420. * in the given array.
  7421. *
  7422. * @param {Array<number>} array - An array holding 3D position data.
  7423. * @return {Box3} A reference to this bounding box.
  7424. */
  7425. setFromArray( array ) {
  7426. this.makeEmpty();
  7427. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7428. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7429. }
  7430. return this;
  7431. }
  7432. /**
  7433. * Sets the upper and lower bounds of this box so it encloses the position data
  7434. * in the given buffer attribute.
  7435. *
  7436. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7437. * @return {Box3} A reference to this bounding box.
  7438. */
  7439. setFromBufferAttribute( attribute ) {
  7440. this.makeEmpty();
  7441. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7442. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7443. }
  7444. return this;
  7445. }
  7446. /**
  7447. * Sets the upper and lower bounds of this box so it encloses the position data
  7448. * in the given array.
  7449. *
  7450. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7451. * @return {Box3} A reference to this bounding box.
  7452. */
  7453. setFromPoints( points ) {
  7454. this.makeEmpty();
  7455. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7456. this.expandByPoint( points[ i ] );
  7457. }
  7458. return this;
  7459. }
  7460. /**
  7461. * Centers this box on the given center vector and sets this box's width, height and
  7462. * depth to the given size values.
  7463. *
  7464. * @param {Vector3} center - The center of the box.
  7465. * @param {Vector3} size - The x, y and z dimensions of the box.
  7466. * @return {Box3} A reference to this bounding box.
  7467. */
  7468. setFromCenterAndSize( center, size ) {
  7469. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7470. this.min.copy( center ).sub( halfSize );
  7471. this.max.copy( center ).add( halfSize );
  7472. return this;
  7473. }
  7474. /**
  7475. * Computes the world-axis-aligned bounding box for the given 3D object
  7476. * (including its children), accounting for the object's, and children's,
  7477. * world transforms. The function may result in a larger box than strictly necessary.
  7478. *
  7479. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7480. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7481. * world-axis-aligned bounding box at the expense of more computation.
  7482. * @return {Box3} A reference to this bounding box.
  7483. */
  7484. setFromObject( object, precise = false ) {
  7485. this.makeEmpty();
  7486. return this.expandByObject( object, precise );
  7487. }
  7488. /**
  7489. * Returns a new box with copied values from this instance.
  7490. *
  7491. * @return {Box3} A clone of this instance.
  7492. */
  7493. clone() {
  7494. return new this.constructor().copy( this );
  7495. }
  7496. /**
  7497. * Copies the values of the given box to this instance.
  7498. *
  7499. * @param {Box3} box - The box to copy.
  7500. * @return {Box3} A reference to this bounding box.
  7501. */
  7502. copy( box ) {
  7503. this.min.copy( box.min );
  7504. this.max.copy( box.max );
  7505. return this;
  7506. }
  7507. /**
  7508. * Makes this box empty which means in encloses a zero space in 3D.
  7509. *
  7510. * @return {Box3} A reference to this bounding box.
  7511. */
  7512. makeEmpty() {
  7513. this.min.x = this.min.y = this.min.z = + Infinity;
  7514. this.max.x = this.max.y = this.max.z = - Infinity;
  7515. return this;
  7516. }
  7517. /**
  7518. * Returns true if this box includes zero points within its bounds.
  7519. * Note that a box with equal lower and upper bounds still includes one
  7520. * point, the one both bounds share.
  7521. *
  7522. * @return {boolean} Whether this box is empty or not.
  7523. */
  7524. isEmpty() {
  7525. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7526. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7527. }
  7528. /**
  7529. * Returns the center point of this box.
  7530. *
  7531. * @param {Vector3} target - The target vector that is used to store the method's result.
  7532. * @return {Vector3} The center point.
  7533. */
  7534. getCenter( target ) {
  7535. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7536. }
  7537. /**
  7538. * Returns the dimensions of this box.
  7539. *
  7540. * @param {Vector3} target - The target vector that is used to store the method's result.
  7541. * @return {Vector3} The size.
  7542. */
  7543. getSize( target ) {
  7544. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7545. }
  7546. /**
  7547. * Expands the boundaries of this box to include the given point.
  7548. *
  7549. * @param {Vector3} point - The point that should be included by the bounding box.
  7550. * @return {Box3} A reference to this bounding box.
  7551. */
  7552. expandByPoint( point ) {
  7553. this.min.min( point );
  7554. this.max.max( point );
  7555. return this;
  7556. }
  7557. /**
  7558. * Expands this box equilaterally by the given vector. The width of this
  7559. * box will be expanded by the x component of the vector in both
  7560. * directions. The height of this box will be expanded by the y component of
  7561. * the vector in both directions. The depth of this box will be
  7562. * expanded by the z component of the vector in both directions.
  7563. *
  7564. * @param {Vector3} vector - The vector that should expand the bounding box.
  7565. * @return {Box3} A reference to this bounding box.
  7566. */
  7567. expandByVector( vector ) {
  7568. this.min.sub( vector );
  7569. this.max.add( vector );
  7570. return this;
  7571. }
  7572. /**
  7573. * Expands each dimension of the box by the given scalar. If negative, the
  7574. * dimensions of the box will be contracted.
  7575. *
  7576. * @param {number} scalar - The scalar value that should expand the bounding box.
  7577. * @return {Box3} A reference to this bounding box.
  7578. */
  7579. expandByScalar( scalar ) {
  7580. this.min.addScalar( - scalar );
  7581. this.max.addScalar( scalar );
  7582. return this;
  7583. }
  7584. /**
  7585. * Expands the boundaries of this box to include the given 3D object and
  7586. * its children, accounting for the object's, and children's, world
  7587. * transforms. The function may result in a larger box than strictly
  7588. * necessary (unless the precise parameter is set to true).
  7589. *
  7590. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7591. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7592. * as little as necessary at the expense of more computation.
  7593. * @return {Box3} A reference to this bounding box.
  7594. */
  7595. expandByObject( object, precise = false ) {
  7596. // Computes the world-axis-aligned bounding box of an object (including its children),
  7597. // accounting for both the object's, and children's, world transforms
  7598. object.updateWorldMatrix( false, false );
  7599. const geometry = object.geometry;
  7600. if ( geometry !== undefined ) {
  7601. const positionAttribute = geometry.getAttribute( 'position' );
  7602. // precise AABB computation based on vertex data requires at least a position attribute.
  7603. // instancing isn't supported so far and uses the normal (conservative) code path.
  7604. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7605. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7606. if ( object.isMesh === true ) {
  7607. object.getVertexPosition( i, _vector$b );
  7608. } else {
  7609. _vector$b.fromBufferAttribute( positionAttribute, i );
  7610. }
  7611. _vector$b.applyMatrix4( object.matrixWorld );
  7612. this.expandByPoint( _vector$b );
  7613. }
  7614. } else {
  7615. if ( object.boundingBox !== undefined ) {
  7616. // object-level bounding box
  7617. if ( object.boundingBox === null ) {
  7618. object.computeBoundingBox();
  7619. }
  7620. _box$4.copy( object.boundingBox );
  7621. } else {
  7622. // geometry-level bounding box
  7623. if ( geometry.boundingBox === null ) {
  7624. geometry.computeBoundingBox();
  7625. }
  7626. _box$4.copy( geometry.boundingBox );
  7627. }
  7628. _box$4.applyMatrix4( object.matrixWorld );
  7629. this.union( _box$4 );
  7630. }
  7631. }
  7632. const children = object.children;
  7633. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7634. this.expandByObject( children[ i ], precise );
  7635. }
  7636. return this;
  7637. }
  7638. /**
  7639. * Returns `true` if the given point lies within or on the boundaries of this box.
  7640. *
  7641. * @param {Vector3} point - The point to test.
  7642. * @return {boolean} Whether the bounding box contains the given point or not.
  7643. */
  7644. containsPoint( point ) {
  7645. return point.x >= this.min.x && point.x <= this.max.x &&
  7646. point.y >= this.min.y && point.y <= this.max.y &&
  7647. point.z >= this.min.z && point.z <= this.max.z;
  7648. }
  7649. /**
  7650. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7651. * If this box and the given one are identical, this function also returns `true`.
  7652. *
  7653. * @param {Box3} box - The bounding box to test.
  7654. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7655. */
  7656. containsBox( box ) {
  7657. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7658. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7659. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7660. }
  7661. /**
  7662. * Returns a point as a proportion of this box's width, height and depth.
  7663. *
  7664. * @param {Vector3} point - A point in 3D space.
  7665. * @param {Vector3} target - The target vector that is used to store the method's result.
  7666. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7667. */
  7668. getParameter( point, target ) {
  7669. // This can potentially have a divide by zero if the box
  7670. // has a size dimension of 0.
  7671. return target.set(
  7672. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7673. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7674. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7675. );
  7676. }
  7677. /**
  7678. * Returns `true` if the given bounding box intersects with this bounding box.
  7679. *
  7680. * @param {Box3} box - The bounding box to test.
  7681. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7682. */
  7683. intersectsBox( box ) {
  7684. // using 6 splitting planes to rule out intersections.
  7685. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7686. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7687. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7688. }
  7689. /**
  7690. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7691. *
  7692. * @param {Sphere} sphere - The bounding sphere to test.
  7693. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7694. */
  7695. intersectsSphere( sphere ) {
  7696. // Find the point on the AABB closest to the sphere center.
  7697. this.clampPoint( sphere.center, _vector$b );
  7698. // If that point is inside the sphere, the AABB and sphere intersect.
  7699. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7700. }
  7701. /**
  7702. * Returns `true` if the given plane intersects with this bounding box.
  7703. *
  7704. * @param {Plane} plane - The plane to test.
  7705. * @return {boolean} Whether the given plane intersects with this bounding box.
  7706. */
  7707. intersectsPlane( plane ) {
  7708. // We compute the minimum and maximum dot product values. If those values
  7709. // are on the same side (back or front) of the plane, then there is no intersection.
  7710. let min, max;
  7711. if ( plane.normal.x > 0 ) {
  7712. min = plane.normal.x * this.min.x;
  7713. max = plane.normal.x * this.max.x;
  7714. } else {
  7715. min = plane.normal.x * this.max.x;
  7716. max = plane.normal.x * this.min.x;
  7717. }
  7718. if ( plane.normal.y > 0 ) {
  7719. min += plane.normal.y * this.min.y;
  7720. max += plane.normal.y * this.max.y;
  7721. } else {
  7722. min += plane.normal.y * this.max.y;
  7723. max += plane.normal.y * this.min.y;
  7724. }
  7725. if ( plane.normal.z > 0 ) {
  7726. min += plane.normal.z * this.min.z;
  7727. max += plane.normal.z * this.max.z;
  7728. } else {
  7729. min += plane.normal.z * this.max.z;
  7730. max += plane.normal.z * this.min.z;
  7731. }
  7732. return ( min <= - plane.constant && max >= - plane.constant );
  7733. }
  7734. /**
  7735. * Returns `true` if the given triangle intersects with this bounding box.
  7736. *
  7737. * @param {Triangle} triangle - The triangle to test.
  7738. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7739. */
  7740. intersectsTriangle( triangle ) {
  7741. if ( this.isEmpty() ) {
  7742. return false;
  7743. }
  7744. // compute box center and extents
  7745. this.getCenter( _center );
  7746. _extents.subVectors( this.max, _center );
  7747. // translate triangle to aabb origin
  7748. _v0$3.subVectors( triangle.a, _center );
  7749. _v1$7.subVectors( triangle.b, _center );
  7750. _v2$4.subVectors( triangle.c, _center );
  7751. // compute edge vectors for triangle
  7752. _f0.subVectors( _v1$7, _v0$3 );
  7753. _f1.subVectors( _v2$4, _v1$7 );
  7754. _f2.subVectors( _v0$3, _v2$4 );
  7755. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7756. // 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
  7757. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7758. let axes = [
  7759. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7760. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7761. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7762. ];
  7763. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7764. return false;
  7765. }
  7766. // test 3 face normals from the aabb
  7767. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7768. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7769. return false;
  7770. }
  7771. // finally testing the face normal of the triangle
  7772. // use already existing triangle edge vectors here
  7773. _triangleNormal.crossVectors( _f0, _f1 );
  7774. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7775. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7776. }
  7777. /**
  7778. * Clamps the given point within the bounds of this box.
  7779. *
  7780. * @param {Vector3} point - The point to clamp.
  7781. * @param {Vector3} target - The target vector that is used to store the method's result.
  7782. * @return {Vector3} The clamped point.
  7783. */
  7784. clampPoint( point, target ) {
  7785. return target.copy( point ).clamp( this.min, this.max );
  7786. }
  7787. /**
  7788. * Returns the euclidean distance from any edge of this box to the specified point. If
  7789. * the given point lies inside of this box, the distance will be `0`.
  7790. *
  7791. * @param {Vector3} point - The point to compute the distance to.
  7792. * @return {number} The euclidean distance.
  7793. */
  7794. distanceToPoint( point ) {
  7795. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7796. }
  7797. /**
  7798. * Returns a bounding sphere that encloses this bounding box.
  7799. *
  7800. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7801. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7802. */
  7803. getBoundingSphere( target ) {
  7804. if ( this.isEmpty() ) {
  7805. target.makeEmpty();
  7806. } else {
  7807. this.getCenter( target.center );
  7808. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7809. }
  7810. return target;
  7811. }
  7812. /**
  7813. * Computes the intersection of this bounding box and the given one, setting the upper
  7814. * bound of this box to the lesser of the two boxes' upper bounds and the
  7815. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7816. * there's no overlap, makes this box empty.
  7817. *
  7818. * @param {Box3} box - The bounding box to intersect with.
  7819. * @return {Box3} A reference to this bounding box.
  7820. */
  7821. intersect( box ) {
  7822. this.min.max( box.min );
  7823. this.max.min( box.max );
  7824. // 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.
  7825. if ( this.isEmpty() ) this.makeEmpty();
  7826. return this;
  7827. }
  7828. /**
  7829. * Computes the union of this box and another and the given one, setting the upper
  7830. * bound of this box to the greater of the two boxes' upper bounds and the
  7831. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7832. *
  7833. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7834. * @return {Box3} A reference to this bounding box.
  7835. */
  7836. union( box ) {
  7837. this.min.min( box.min );
  7838. this.max.max( box.max );
  7839. return this;
  7840. }
  7841. /**
  7842. * Transforms this bounding box by the given 4x4 transformation matrix.
  7843. *
  7844. * @param {Matrix4} matrix - The transformation matrix.
  7845. * @return {Box3} A reference to this bounding box.
  7846. */
  7847. applyMatrix4( matrix ) {
  7848. // transform of empty box is an empty box.
  7849. if ( this.isEmpty() ) return this;
  7850. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7851. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7852. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7853. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7854. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7855. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7856. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7857. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7858. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7859. this.setFromPoints( _points );
  7860. return this;
  7861. }
  7862. /**
  7863. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7864. * effectively moving it in 3D space.
  7865. *
  7866. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7867. * @return {Box3} A reference to this bounding box.
  7868. */
  7869. translate( offset ) {
  7870. this.min.add( offset );
  7871. this.max.add( offset );
  7872. return this;
  7873. }
  7874. /**
  7875. * Returns `true` if this bounding box is equal with the given one.
  7876. *
  7877. * @param {Box3} box - The box to test for equality.
  7878. * @return {boolean} Whether this bounding box is equal with the given one.
  7879. */
  7880. equals( box ) {
  7881. return box.min.equals( this.min ) && box.max.equals( this.max );
  7882. }
  7883. /**
  7884. * Returns a serialized structure of the bounding box.
  7885. *
  7886. * @return {Object} Serialized structure with fields representing the object state.
  7887. */
  7888. toJSON() {
  7889. return {
  7890. min: this.min.toArray(),
  7891. max: this.max.toArray()
  7892. };
  7893. }
  7894. /**
  7895. * Returns a serialized structure of the bounding box.
  7896. *
  7897. * @param {Object} json - The serialized json to set the box from.
  7898. * @return {Box3} A reference to this bounding box.
  7899. */
  7900. fromJSON( json ) {
  7901. this.min.fromArray( json.min );
  7902. this.max.fromArray( json.max );
  7903. return this;
  7904. }
  7905. }
  7906. const _points = [
  7907. /*@__PURE__*/ new Vector3(),
  7908. /*@__PURE__*/ new Vector3(),
  7909. /*@__PURE__*/ new Vector3(),
  7910. /*@__PURE__*/ new Vector3(),
  7911. /*@__PURE__*/ new Vector3(),
  7912. /*@__PURE__*/ new Vector3(),
  7913. /*@__PURE__*/ new Vector3(),
  7914. /*@__PURE__*/ new Vector3()
  7915. ];
  7916. const _vector$b = /*@__PURE__*/ new Vector3();
  7917. const _box$4 = /*@__PURE__*/ new Box3();
  7918. // triangle centered vertices
  7919. const _v0$3 = /*@__PURE__*/ new Vector3();
  7920. const _v1$7 = /*@__PURE__*/ new Vector3();
  7921. const _v2$4 = /*@__PURE__*/ new Vector3();
  7922. // triangle edge vectors
  7923. const _f0 = /*@__PURE__*/ new Vector3();
  7924. const _f1 = /*@__PURE__*/ new Vector3();
  7925. const _f2 = /*@__PURE__*/ new Vector3();
  7926. const _center = /*@__PURE__*/ new Vector3();
  7927. const _extents = /*@__PURE__*/ new Vector3();
  7928. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7929. const _testAxis = /*@__PURE__*/ new Vector3();
  7930. function satForAxes( axes, v0, v1, v2, extents ) {
  7931. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7932. _testAxis.fromArray( axes, i );
  7933. // project the aabb onto the separating axis
  7934. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7935. // project all 3 vertices of the triangle onto the separating axis
  7936. const p0 = v0.dot( _testAxis );
  7937. const p1 = v1.dot( _testAxis );
  7938. const p2 = v2.dot( _testAxis );
  7939. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7940. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7941. // points of the projected triangle are outside the projected half-length of the aabb
  7942. // the axis is separating and we can exit
  7943. return false;
  7944. }
  7945. }
  7946. return true;
  7947. }
  7948. const _box$3 = /*@__PURE__*/ new Box3();
  7949. const _v1$6 = /*@__PURE__*/ new Vector3();
  7950. const _v2$3 = /*@__PURE__*/ new Vector3();
  7951. /**
  7952. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7953. * used as a Bounding Sphere for 3D objects.
  7954. */
  7955. class Sphere {
  7956. /**
  7957. * Constructs a new sphere.
  7958. *
  7959. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7960. * @param {number} [radius=-1] - The radius of the sphere.
  7961. */
  7962. constructor( center = new Vector3(), radius = -1 ) {
  7963. /**
  7964. * This flag can be used for type testing.
  7965. *
  7966. * @type {boolean}
  7967. * @readonly
  7968. * @default true
  7969. */
  7970. this.isSphere = true;
  7971. /**
  7972. * The center of the sphere
  7973. *
  7974. * @type {Vector3}
  7975. */
  7976. this.center = center;
  7977. /**
  7978. * The radius of the sphere.
  7979. *
  7980. * @type {number}
  7981. */
  7982. this.radius = radius;
  7983. }
  7984. /**
  7985. * Sets the sphere's components by copying the given values.
  7986. *
  7987. * @param {Vector3} center - The center.
  7988. * @param {number} radius - The radius.
  7989. * @return {Sphere} A reference to this sphere.
  7990. */
  7991. set( center, radius ) {
  7992. this.center.copy( center );
  7993. this.radius = radius;
  7994. return this;
  7995. }
  7996. /**
  7997. * Computes the minimum bounding sphere for list of points.
  7998. * If the optional center point is given, it is used as the sphere's
  7999. * center. Otherwise, the center of the axis-aligned bounding box
  8000. * encompassing the points is calculated.
  8001. *
  8002. * @param {Array<Vector3>} points - A list of points in 3D space.
  8003. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8004. * @return {Sphere} A reference to this sphere.
  8005. */
  8006. setFromPoints( points, optionalCenter ) {
  8007. const center = this.center;
  8008. if ( optionalCenter !== undefined ) {
  8009. center.copy( optionalCenter );
  8010. } else {
  8011. _box$3.setFromPoints( points ).getCenter( center );
  8012. }
  8013. let maxRadiusSq = 0;
  8014. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8015. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8016. }
  8017. this.radius = Math.sqrt( maxRadiusSq );
  8018. return this;
  8019. }
  8020. /**
  8021. * Copies the values of the given sphere to this instance.
  8022. *
  8023. * @param {Sphere} sphere - The sphere to copy.
  8024. * @return {Sphere} A reference to this sphere.
  8025. */
  8026. copy( sphere ) {
  8027. this.center.copy( sphere.center );
  8028. this.radius = sphere.radius;
  8029. return this;
  8030. }
  8031. /**
  8032. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8033. *
  8034. * Spheres with a radius of `0` contain only their center point and are not
  8035. * considered to be empty.
  8036. *
  8037. * @return {boolean} Whether this sphere is empty or not.
  8038. */
  8039. isEmpty() {
  8040. return ( this.radius < 0 );
  8041. }
  8042. /**
  8043. * Makes this sphere empty which means in encloses a zero space in 3D.
  8044. *
  8045. * @return {Sphere} A reference to this sphere.
  8046. */
  8047. makeEmpty() {
  8048. this.center.set( 0, 0, 0 );
  8049. this.radius = -1;
  8050. return this;
  8051. }
  8052. /**
  8053. * Returns `true` if this sphere contains the given point inclusive of
  8054. * the surface of the sphere.
  8055. *
  8056. * @param {Vector3} point - The point to check.
  8057. * @return {boolean} Whether this sphere contains the given point or not.
  8058. */
  8059. containsPoint( point ) {
  8060. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8061. }
  8062. /**
  8063. * Returns the closest distance from the boundary of the sphere to the
  8064. * given point. If the sphere contains the point, the distance will
  8065. * be negative.
  8066. *
  8067. * @param {Vector3} point - The point to compute the distance to.
  8068. * @return {number} The distance to the point.
  8069. */
  8070. distanceToPoint( point ) {
  8071. return ( point.distanceTo( this.center ) - this.radius );
  8072. }
  8073. /**
  8074. * Returns `true` if this sphere intersects with the given one.
  8075. *
  8076. * @param {Sphere} sphere - The sphere to test.
  8077. * @return {boolean} Whether this sphere intersects with the given one or not.
  8078. */
  8079. intersectsSphere( sphere ) {
  8080. const radiusSum = this.radius + sphere.radius;
  8081. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8082. }
  8083. /**
  8084. * Returns `true` if this sphere intersects with the given box.
  8085. *
  8086. * @param {Box3} box - The box to test.
  8087. * @return {boolean} Whether this sphere intersects with the given box or not.
  8088. */
  8089. intersectsBox( box ) {
  8090. return box.intersectsSphere( this );
  8091. }
  8092. /**
  8093. * Returns `true` if this sphere intersects with the given plane.
  8094. *
  8095. * @param {Plane} plane - The plane to test.
  8096. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8097. */
  8098. intersectsPlane( plane ) {
  8099. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8100. }
  8101. /**
  8102. * Clamps a point within the sphere. If the point is outside the sphere, it
  8103. * will clamp it to the closest point on the edge of the sphere. Points
  8104. * already inside the sphere will not be affected.
  8105. *
  8106. * @param {Vector3} point - The plane to clamp.
  8107. * @param {Vector3} target - The target vector that is used to store the method's result.
  8108. * @return {Vector3} The clamped point.
  8109. */
  8110. clampPoint( point, target ) {
  8111. const deltaLengthSq = this.center.distanceToSquared( point );
  8112. target.copy( point );
  8113. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8114. target.sub( this.center ).normalize();
  8115. target.multiplyScalar( this.radius ).add( this.center );
  8116. }
  8117. return target;
  8118. }
  8119. /**
  8120. * Returns a bounding box that encloses this sphere.
  8121. *
  8122. * @param {Box3} target - The target box that is used to store the method's result.
  8123. * @return {Box3} The bounding box that encloses this sphere.
  8124. */
  8125. getBoundingBox( target ) {
  8126. if ( this.isEmpty() ) {
  8127. // Empty sphere produces empty bounding box
  8128. target.makeEmpty();
  8129. return target;
  8130. }
  8131. target.set( this.center, this.center );
  8132. target.expandByScalar( this.radius );
  8133. return target;
  8134. }
  8135. /**
  8136. * Transforms this sphere with the given 4x4 transformation matrix.
  8137. *
  8138. * @param {Matrix4} matrix - The transformation matrix.
  8139. * @return {Sphere} A reference to this sphere.
  8140. */
  8141. applyMatrix4( matrix ) {
  8142. this.center.applyMatrix4( matrix );
  8143. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8144. return this;
  8145. }
  8146. /**
  8147. * Translates the sphere's center by the given offset.
  8148. *
  8149. * @param {Vector3} offset - The offset.
  8150. * @return {Sphere} A reference to this sphere.
  8151. */
  8152. translate( offset ) {
  8153. this.center.add( offset );
  8154. return this;
  8155. }
  8156. /**
  8157. * Expands the boundaries of this sphere to include the given point.
  8158. *
  8159. * @param {Vector3} point - The point to include.
  8160. * @return {Sphere} A reference to this sphere.
  8161. */
  8162. expandByPoint( point ) {
  8163. if ( this.isEmpty() ) {
  8164. this.center.copy( point );
  8165. this.radius = 0;
  8166. return this;
  8167. }
  8168. _v1$6.subVectors( point, this.center );
  8169. const lengthSq = _v1$6.lengthSq();
  8170. if ( lengthSq > ( this.radius * this.radius ) ) {
  8171. // calculate the minimal sphere
  8172. const length = Math.sqrt( lengthSq );
  8173. const delta = ( length - this.radius ) * 0.5;
  8174. this.center.addScaledVector( _v1$6, delta / length );
  8175. this.radius += delta;
  8176. }
  8177. return this;
  8178. }
  8179. /**
  8180. * Expands this sphere to enclose both the original sphere and the given sphere.
  8181. *
  8182. * @param {Sphere} sphere - The sphere to include.
  8183. * @return {Sphere} A reference to this sphere.
  8184. */
  8185. union( sphere ) {
  8186. if ( sphere.isEmpty() ) {
  8187. return this;
  8188. }
  8189. if ( this.isEmpty() ) {
  8190. this.copy( sphere );
  8191. return this;
  8192. }
  8193. if ( this.center.equals( sphere.center ) === true ) {
  8194. this.radius = Math.max( this.radius, sphere.radius );
  8195. } else {
  8196. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8197. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8198. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8199. }
  8200. return this;
  8201. }
  8202. /**
  8203. * Returns `true` if this sphere is equal with the given one.
  8204. *
  8205. * @param {Sphere} sphere - The sphere to test for equality.
  8206. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8207. */
  8208. equals( sphere ) {
  8209. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8210. }
  8211. /**
  8212. * Returns a new sphere with copied values from this instance.
  8213. *
  8214. * @return {Sphere} A clone of this instance.
  8215. */
  8216. clone() {
  8217. return new this.constructor().copy( this );
  8218. }
  8219. /**
  8220. * Returns a serialized structure of the bounding sphere.
  8221. *
  8222. * @return {Object} Serialized structure with fields representing the object state.
  8223. */
  8224. toJSON() {
  8225. return {
  8226. radius: this.radius,
  8227. center: this.center.toArray()
  8228. };
  8229. }
  8230. /**
  8231. * Returns a serialized structure of the bounding sphere.
  8232. *
  8233. * @param {Object} json - The serialized json to set the sphere from.
  8234. * @return {Sphere} A reference to this bounding sphere.
  8235. */
  8236. fromJSON( json ) {
  8237. this.radius = json.radius;
  8238. this.center.fromArray( json.center );
  8239. return this;
  8240. }
  8241. }
  8242. const _vector$a = /*@__PURE__*/ new Vector3();
  8243. const _segCenter = /*@__PURE__*/ new Vector3();
  8244. const _segDir = /*@__PURE__*/ new Vector3();
  8245. const _diff = /*@__PURE__*/ new Vector3();
  8246. const _edge1 = /*@__PURE__*/ new Vector3();
  8247. const _edge2 = /*@__PURE__*/ new Vector3();
  8248. const _normal$1 = /*@__PURE__*/ new Vector3();
  8249. /**
  8250. * A ray that emits from an origin in a certain direction. The class is used by
  8251. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8252. * mouse picking (working out what objects in the 3D space the mouse is over)
  8253. * amongst other things.
  8254. */
  8255. class Ray {
  8256. /**
  8257. * Constructs a new ray.
  8258. *
  8259. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8260. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8261. */
  8262. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8263. /**
  8264. * The origin of the ray.
  8265. *
  8266. * @type {Vector3}
  8267. */
  8268. this.origin = origin;
  8269. /**
  8270. * The (normalized) direction of the ray.
  8271. *
  8272. * @type {Vector3}
  8273. */
  8274. this.direction = direction;
  8275. }
  8276. /**
  8277. * Sets the ray's components by copying the given values.
  8278. *
  8279. * @param {Vector3} origin - The origin.
  8280. * @param {Vector3} direction - The direction.
  8281. * @return {Ray} A reference to this ray.
  8282. */
  8283. set( origin, direction ) {
  8284. this.origin.copy( origin );
  8285. this.direction.copy( direction );
  8286. return this;
  8287. }
  8288. /**
  8289. * Copies the values of the given ray to this instance.
  8290. *
  8291. * @param {Ray} ray - The ray to copy.
  8292. * @return {Ray} A reference to this ray.
  8293. */
  8294. copy( ray ) {
  8295. this.origin.copy( ray.origin );
  8296. this.direction.copy( ray.direction );
  8297. return this;
  8298. }
  8299. /**
  8300. * Returns a vector that is located at a given distance along this ray.
  8301. *
  8302. * @param {number} t - The distance along the ray to retrieve a position for.
  8303. * @param {Vector3} target - The target vector that is used to store the method's result.
  8304. * @return {Vector3} A position on the ray.
  8305. */
  8306. at( t, target ) {
  8307. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8308. }
  8309. /**
  8310. * Adjusts the direction of the ray to point at the given vector in world space.
  8311. *
  8312. * @param {Vector3} v - The target position.
  8313. * @return {Ray} A reference to this ray.
  8314. */
  8315. lookAt( v ) {
  8316. this.direction.copy( v ).sub( this.origin ).normalize();
  8317. return this;
  8318. }
  8319. /**
  8320. * Shift the origin of this ray along its direction by the given distance.
  8321. *
  8322. * @param {number} t - The distance along the ray to interpolate.
  8323. * @return {Ray} A reference to this ray.
  8324. */
  8325. recast( t ) {
  8326. this.origin.copy( this.at( t, _vector$a ) );
  8327. return this;
  8328. }
  8329. /**
  8330. * Returns the point along this ray that is closest to the given point.
  8331. *
  8332. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8333. * @param {Vector3} target - The target vector that is used to store the method's result.
  8334. * @return {Vector3} The closest point on this ray.
  8335. */
  8336. closestPointToPoint( point, target ) {
  8337. target.subVectors( point, this.origin );
  8338. const directionDistance = target.dot( this.direction );
  8339. if ( directionDistance < 0 ) {
  8340. return target.copy( this.origin );
  8341. }
  8342. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8343. }
  8344. /**
  8345. * Returns the distance of the closest approach between this ray and the given point.
  8346. *
  8347. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8348. * @return {number} The distance.
  8349. */
  8350. distanceToPoint( point ) {
  8351. return Math.sqrt( this.distanceSqToPoint( point ) );
  8352. }
  8353. /**
  8354. * Returns the squared distance of the closest approach between this ray and the given point.
  8355. *
  8356. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8357. * @return {number} The squared distance.
  8358. */
  8359. distanceSqToPoint( point ) {
  8360. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8361. // point behind the ray
  8362. if ( directionDistance < 0 ) {
  8363. return this.origin.distanceToSquared( point );
  8364. }
  8365. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8366. return _vector$a.distanceToSquared( point );
  8367. }
  8368. /**
  8369. * Returns the squared distance between this ray and the given line segment.
  8370. *
  8371. * @param {Vector3} v0 - The start point of the line segment.
  8372. * @param {Vector3} v1 - The end point of the line segment.
  8373. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8374. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8375. * @return {number} The squared distance.
  8376. */
  8377. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8378. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8379. // It returns the min distance between the ray and the segment
  8380. // defined by v0 and v1
  8381. // It can also set two optional targets :
  8382. // - The closest point on the ray
  8383. // - The closest point on the segment
  8384. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8385. _segDir.copy( v1 ).sub( v0 ).normalize();
  8386. _diff.copy( this.origin ).sub( _segCenter );
  8387. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8388. const a01 = - this.direction.dot( _segDir );
  8389. const b0 = _diff.dot( this.direction );
  8390. const b1 = - _diff.dot( _segDir );
  8391. const c = _diff.lengthSq();
  8392. const det = Math.abs( 1 - a01 * a01 );
  8393. let s0, s1, sqrDist, extDet;
  8394. if ( det > 0 ) {
  8395. // The ray and segment are not parallel.
  8396. s0 = a01 * b1 - b0;
  8397. s1 = a01 * b0 - b1;
  8398. extDet = segExtent * det;
  8399. if ( s0 >= 0 ) {
  8400. if ( s1 >= - extDet ) {
  8401. if ( s1 <= extDet ) {
  8402. // region 0
  8403. // Minimum at interior points of ray and segment.
  8404. const invDet = 1 / det;
  8405. s0 *= invDet;
  8406. s1 *= invDet;
  8407. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8408. } else {
  8409. // region 1
  8410. s1 = segExtent;
  8411. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8412. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8413. }
  8414. } else {
  8415. // region 5
  8416. s1 = - segExtent;
  8417. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8418. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8419. }
  8420. } else {
  8421. if ( s1 <= - extDet ) {
  8422. // region 4
  8423. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8424. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8425. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8426. } else if ( s1 <= extDet ) {
  8427. // region 3
  8428. s0 = 0;
  8429. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8430. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8431. } else {
  8432. // region 2
  8433. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8434. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8435. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8436. }
  8437. }
  8438. } else {
  8439. // Ray and segment are parallel.
  8440. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8441. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8442. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8443. }
  8444. if ( optionalPointOnRay ) {
  8445. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8446. }
  8447. if ( optionalPointOnSegment ) {
  8448. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8449. }
  8450. return sqrDist;
  8451. }
  8452. /**
  8453. * Intersects this ray with the given sphere, returning the intersection
  8454. * point or `null` if there is no intersection.
  8455. *
  8456. * @param {Sphere} sphere - The sphere to intersect.
  8457. * @param {Vector3} target - The target vector that is used to store the method's result.
  8458. * @return {?Vector3} The intersection point.
  8459. */
  8460. intersectSphere( sphere, target ) {
  8461. _vector$a.subVectors( sphere.center, this.origin );
  8462. const tca = _vector$a.dot( this.direction );
  8463. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8464. const radius2 = sphere.radius * sphere.radius;
  8465. if ( d2 > radius2 ) return null;
  8466. const thc = Math.sqrt( radius2 - d2 );
  8467. // t0 = first intersect point - entrance on front of sphere
  8468. const t0 = tca - thc;
  8469. // t1 = second intersect point - exit point on back of sphere
  8470. const t1 = tca + thc;
  8471. // test to see if t1 is behind the ray - if so, return null
  8472. if ( t1 < 0 ) return null;
  8473. // test to see if t0 is behind the ray:
  8474. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8475. // in order to always return an intersect point that is in front of the ray.
  8476. if ( t0 < 0 ) return this.at( t1, target );
  8477. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8478. return this.at( t0, target );
  8479. }
  8480. /**
  8481. * Returns `true` if this ray intersects with the given sphere.
  8482. *
  8483. * @param {Sphere} sphere - The sphere to intersect.
  8484. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8485. */
  8486. intersectsSphere( sphere ) {
  8487. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8488. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8489. }
  8490. /**
  8491. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8492. * does not intersect with the plane.
  8493. *
  8494. * @param {Plane} plane - The plane to compute the distance to.
  8495. * @return {?number} Whether this ray intersects with the given sphere or not.
  8496. */
  8497. distanceToPlane( plane ) {
  8498. const denominator = plane.normal.dot( this.direction );
  8499. if ( denominator === 0 ) {
  8500. // line is coplanar, return origin
  8501. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8502. return 0;
  8503. }
  8504. // Null is preferable to undefined since undefined means.... it is undefined
  8505. return null;
  8506. }
  8507. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8508. // Return if the ray never intersects the plane
  8509. return t >= 0 ? t : null;
  8510. }
  8511. /**
  8512. * Intersects this ray with the given plane, returning the intersection
  8513. * point or `null` if there is no intersection.
  8514. *
  8515. * @param {Plane} plane - The plane to intersect.
  8516. * @param {Vector3} target - The target vector that is used to store the method's result.
  8517. * @return {?Vector3} The intersection point.
  8518. */
  8519. intersectPlane( plane, target ) {
  8520. const t = this.distanceToPlane( plane );
  8521. if ( t === null ) {
  8522. return null;
  8523. }
  8524. return this.at( t, target );
  8525. }
  8526. /**
  8527. * Returns `true` if this ray intersects with the given plane.
  8528. *
  8529. * @param {Plane} plane - The plane to intersect.
  8530. * @return {boolean} Whether this ray intersects with the given plane or not.
  8531. */
  8532. intersectsPlane( plane ) {
  8533. // check if the ray lies on the plane first
  8534. const distToPoint = plane.distanceToPoint( this.origin );
  8535. if ( distToPoint === 0 ) {
  8536. return true;
  8537. }
  8538. const denominator = plane.normal.dot( this.direction );
  8539. if ( denominator * distToPoint < 0 ) {
  8540. return true;
  8541. }
  8542. // ray origin is behind the plane (and is pointing behind it)
  8543. return false;
  8544. }
  8545. /**
  8546. * Intersects this ray with the given bounding box, returning the intersection
  8547. * point or `null` if there is no intersection.
  8548. *
  8549. * @param {Box3} box - The box to intersect.
  8550. * @param {Vector3} target - The target vector that is used to store the method's result.
  8551. * @return {?Vector3} The intersection point.
  8552. */
  8553. intersectBox( box, target ) {
  8554. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8555. const invdirx = 1 / this.direction.x,
  8556. invdiry = 1 / this.direction.y,
  8557. invdirz = 1 / this.direction.z;
  8558. const origin = this.origin;
  8559. if ( invdirx >= 0 ) {
  8560. tmin = ( box.min.x - origin.x ) * invdirx;
  8561. tmax = ( box.max.x - origin.x ) * invdirx;
  8562. } else {
  8563. tmin = ( box.max.x - origin.x ) * invdirx;
  8564. tmax = ( box.min.x - origin.x ) * invdirx;
  8565. }
  8566. if ( invdiry >= 0 ) {
  8567. tymin = ( box.min.y - origin.y ) * invdiry;
  8568. tymax = ( box.max.y - origin.y ) * invdiry;
  8569. } else {
  8570. tymin = ( box.max.y - origin.y ) * invdiry;
  8571. tymax = ( box.min.y - origin.y ) * invdiry;
  8572. }
  8573. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8574. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8575. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8576. if ( invdirz >= 0 ) {
  8577. tzmin = ( box.min.z - origin.z ) * invdirz;
  8578. tzmax = ( box.max.z - origin.z ) * invdirz;
  8579. } else {
  8580. tzmin = ( box.max.z - origin.z ) * invdirz;
  8581. tzmax = ( box.min.z - origin.z ) * invdirz;
  8582. }
  8583. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8584. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8585. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8586. //return point closest to the ray (positive side)
  8587. if ( tmax < 0 ) return null;
  8588. return this.at( tmin >= 0 ? tmin : tmax, target );
  8589. }
  8590. /**
  8591. * Returns `true` if this ray intersects with the given box.
  8592. *
  8593. * @param {Box3} box - The box to intersect.
  8594. * @return {boolean} Whether this ray intersects with the given box or not.
  8595. */
  8596. intersectsBox( box ) {
  8597. return this.intersectBox( box, _vector$a ) !== null;
  8598. }
  8599. /**
  8600. * Intersects this ray with the given triangle, returning the intersection
  8601. * point or `null` if there is no intersection.
  8602. *
  8603. * @param {Vector3} a - The first vertex of the triangle.
  8604. * @param {Vector3} b - The second vertex of the triangle.
  8605. * @param {Vector3} c - The third vertex of the triangle.
  8606. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8607. * @param {Vector3} target - The target vector that is used to store the method's result.
  8608. * @return {?Vector3} The intersection point.
  8609. */
  8610. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8611. // Compute the offset origin, edges, and normal.
  8612. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8613. _edge1.subVectors( b, a );
  8614. _edge2.subVectors( c, a );
  8615. _normal$1.crossVectors( _edge1, _edge2 );
  8616. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8617. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8618. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8619. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8620. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8621. let DdN = this.direction.dot( _normal$1 );
  8622. let sign;
  8623. if ( DdN > 0 ) {
  8624. if ( backfaceCulling ) return null;
  8625. sign = 1;
  8626. } else if ( DdN < 0 ) {
  8627. sign = -1;
  8628. DdN = - DdN;
  8629. } else {
  8630. return null;
  8631. }
  8632. _diff.subVectors( this.origin, a );
  8633. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8634. // b1 < 0, no intersection
  8635. if ( DdQxE2 < 0 ) {
  8636. return null;
  8637. }
  8638. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8639. // b2 < 0, no intersection
  8640. if ( DdE1xQ < 0 ) {
  8641. return null;
  8642. }
  8643. // b1+b2 > 1, no intersection
  8644. if ( DdQxE2 + DdE1xQ > DdN ) {
  8645. return null;
  8646. }
  8647. // Line intersects triangle, check if ray does.
  8648. const QdN = - sign * _diff.dot( _normal$1 );
  8649. // t < 0, no intersection
  8650. if ( QdN < 0 ) {
  8651. return null;
  8652. }
  8653. // Ray intersects triangle.
  8654. return this.at( QdN / DdN, target );
  8655. }
  8656. /**
  8657. * Transforms this ray with the given 4x4 transformation matrix.
  8658. *
  8659. * @param {Matrix4} matrix4 - The transformation matrix.
  8660. * @return {Ray} A reference to this ray.
  8661. */
  8662. applyMatrix4( matrix4 ) {
  8663. this.origin.applyMatrix4( matrix4 );
  8664. this.direction.transformDirection( matrix4 );
  8665. return this;
  8666. }
  8667. /**
  8668. * Returns `true` if this ray is equal with the given one.
  8669. *
  8670. * @param {Ray} ray - The ray to test for equality.
  8671. * @return {boolean} Whether this ray is equal with the given one.
  8672. */
  8673. equals( ray ) {
  8674. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8675. }
  8676. /**
  8677. * Returns a new ray with copied values from this instance.
  8678. *
  8679. * @return {Ray} A clone of this instance.
  8680. */
  8681. clone() {
  8682. return new this.constructor().copy( this );
  8683. }
  8684. }
  8685. /**
  8686. * Represents a 4x4 matrix.
  8687. *
  8688. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8689. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8690. *
  8691. * This allows a 3D vector representing a point in 3D space to undergo
  8692. * transformations such as translation, rotation, shear, scale, reflection,
  8693. * orthogonal or perspective projection and so on, by being multiplied by the
  8694. * matrix. This is known as `applying` the matrix to the vector.
  8695. *
  8696. * A Note on Row-Major and Column-Major Ordering:
  8697. *
  8698. * The constructor and {@link Matrix3#set} method take arguments in
  8699. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8700. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8701. * This means that calling:
  8702. * ```js
  8703. * const m = new THREE.Matrix4();
  8704. * m.set( 11, 12, 13, 14,
  8705. * 21, 22, 23, 24,
  8706. * 31, 32, 33, 34,
  8707. * 41, 42, 43, 44 );
  8708. * ```
  8709. * will result in the elements array containing:
  8710. * ```js
  8711. * m.elements = [ 11, 21, 31, 41,
  8712. * 12, 22, 32, 42,
  8713. * 13, 23, 33, 43,
  8714. * 14, 24, 34, 44 ];
  8715. * ```
  8716. * and internally all calculations are performed using column-major ordering.
  8717. * However, as the actual ordering makes no difference mathematically and
  8718. * most people are used to thinking about matrices in row-major order, the
  8719. * three.js documentation shows matrices in row-major order. Just bear in
  8720. * mind that if you are reading the source code, you'll have to take the
  8721. * transpose of any matrices outlined here to make sense of the calculations.
  8722. */
  8723. class Matrix4 {
  8724. /**
  8725. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8726. * in row-major order. If no arguments are provided, the constructor
  8727. * initializes the matrix as an identity matrix.
  8728. *
  8729. * @param {number} [n11] - 1-1 matrix element.
  8730. * @param {number} [n12] - 1-2 matrix element.
  8731. * @param {number} [n13] - 1-3 matrix element.
  8732. * @param {number} [n14] - 1-4 matrix element.
  8733. * @param {number} [n21] - 2-1 matrix element.
  8734. * @param {number} [n22] - 2-2 matrix element.
  8735. * @param {number} [n23] - 2-3 matrix element.
  8736. * @param {number} [n24] - 2-4 matrix element.
  8737. * @param {number} [n31] - 3-1 matrix element.
  8738. * @param {number} [n32] - 3-2 matrix element.
  8739. * @param {number} [n33] - 3-3 matrix element.
  8740. * @param {number} [n34] - 3-4 matrix element.
  8741. * @param {number} [n41] - 4-1 matrix element.
  8742. * @param {number} [n42] - 4-2 matrix element.
  8743. * @param {number} [n43] - 4-3 matrix element.
  8744. * @param {number} [n44] - 4-4 matrix element.
  8745. */
  8746. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8747. /**
  8748. * This flag can be used for type testing.
  8749. *
  8750. * @type {boolean}
  8751. * @readonly
  8752. * @default true
  8753. */
  8754. Matrix4.prototype.isMatrix4 = true;
  8755. /**
  8756. * A column-major list of matrix values.
  8757. *
  8758. * @type {Array<number>}
  8759. */
  8760. this.elements = [
  8761. 1, 0, 0, 0,
  8762. 0, 1, 0, 0,
  8763. 0, 0, 1, 0,
  8764. 0, 0, 0, 1
  8765. ];
  8766. if ( n11 !== undefined ) {
  8767. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8768. }
  8769. }
  8770. /**
  8771. * Sets the elements of the matrix.The arguments are supposed to be
  8772. * in row-major order.
  8773. *
  8774. * @param {number} [n11] - 1-1 matrix element.
  8775. * @param {number} [n12] - 1-2 matrix element.
  8776. * @param {number} [n13] - 1-3 matrix element.
  8777. * @param {number} [n14] - 1-4 matrix element.
  8778. * @param {number} [n21] - 2-1 matrix element.
  8779. * @param {number} [n22] - 2-2 matrix element.
  8780. * @param {number} [n23] - 2-3 matrix element.
  8781. * @param {number} [n24] - 2-4 matrix element.
  8782. * @param {number} [n31] - 3-1 matrix element.
  8783. * @param {number} [n32] - 3-2 matrix element.
  8784. * @param {number} [n33] - 3-3 matrix element.
  8785. * @param {number} [n34] - 3-4 matrix element.
  8786. * @param {number} [n41] - 4-1 matrix element.
  8787. * @param {number} [n42] - 4-2 matrix element.
  8788. * @param {number} [n43] - 4-3 matrix element.
  8789. * @param {number} [n44] - 4-4 matrix element.
  8790. * @return {Matrix4} A reference to this matrix.
  8791. */
  8792. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8793. const te = this.elements;
  8794. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8795. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8796. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8797. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8798. return this;
  8799. }
  8800. /**
  8801. * Sets this matrix to the 4x4 identity matrix.
  8802. *
  8803. * @return {Matrix4} A reference to this matrix.
  8804. */
  8805. identity() {
  8806. this.set(
  8807. 1, 0, 0, 0,
  8808. 0, 1, 0, 0,
  8809. 0, 0, 1, 0,
  8810. 0, 0, 0, 1
  8811. );
  8812. return this;
  8813. }
  8814. /**
  8815. * Returns a matrix with copied values from this instance.
  8816. *
  8817. * @return {Matrix4} A clone of this instance.
  8818. */
  8819. clone() {
  8820. return new Matrix4().fromArray( this.elements );
  8821. }
  8822. /**
  8823. * Copies the values of the given matrix to this instance.
  8824. *
  8825. * @param {Matrix4} m - The matrix to copy.
  8826. * @return {Matrix4} A reference to this matrix.
  8827. */
  8828. copy( m ) {
  8829. const te = this.elements;
  8830. const me = m.elements;
  8831. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8832. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8833. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8834. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8835. return this;
  8836. }
  8837. /**
  8838. * Copies the translation component of the given matrix
  8839. * into this matrix's translation component.
  8840. *
  8841. * @param {Matrix4} m - The matrix to copy the translation component.
  8842. * @return {Matrix4} A reference to this matrix.
  8843. */
  8844. copyPosition( m ) {
  8845. const te = this.elements, me = m.elements;
  8846. te[ 12 ] = me[ 12 ];
  8847. te[ 13 ] = me[ 13 ];
  8848. te[ 14 ] = me[ 14 ];
  8849. return this;
  8850. }
  8851. /**
  8852. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8853. *
  8854. * @param {Matrix3} m - The 3x3 matrix.
  8855. * @return {Matrix4} A reference to this matrix.
  8856. */
  8857. setFromMatrix3( m ) {
  8858. const me = m.elements;
  8859. this.set(
  8860. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8861. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8862. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8863. 0, 0, 0, 1
  8864. );
  8865. return this;
  8866. }
  8867. /**
  8868. * Extracts the basis of this matrix into the three axis vectors provided.
  8869. *
  8870. * @param {Vector3} xAxis - The basis's x axis.
  8871. * @param {Vector3} yAxis - The basis's y axis.
  8872. * @param {Vector3} zAxis - The basis's z axis.
  8873. * @return {Matrix4} A reference to this matrix.
  8874. */
  8875. extractBasis( xAxis, yAxis, zAxis ) {
  8876. if ( this.determinant() === 0 ) {
  8877. xAxis.set( 1, 0, 0 );
  8878. yAxis.set( 0, 1, 0 );
  8879. zAxis.set( 0, 0, 1 );
  8880. return this;
  8881. }
  8882. xAxis.setFromMatrixColumn( this, 0 );
  8883. yAxis.setFromMatrixColumn( this, 1 );
  8884. zAxis.setFromMatrixColumn( this, 2 );
  8885. return this;
  8886. }
  8887. /**
  8888. * Sets the given basis vectors to this matrix.
  8889. *
  8890. * @param {Vector3} xAxis - The basis's x axis.
  8891. * @param {Vector3} yAxis - The basis's y axis.
  8892. * @param {Vector3} zAxis - The basis's z axis.
  8893. * @return {Matrix4} A reference to this matrix.
  8894. */
  8895. makeBasis( xAxis, yAxis, zAxis ) {
  8896. this.set(
  8897. xAxis.x, yAxis.x, zAxis.x, 0,
  8898. xAxis.y, yAxis.y, zAxis.y, 0,
  8899. xAxis.z, yAxis.z, zAxis.z, 0,
  8900. 0, 0, 0, 1
  8901. );
  8902. return this;
  8903. }
  8904. /**
  8905. * Extracts the rotation component of the given matrix
  8906. * into this matrix's rotation component.
  8907. *
  8908. * Note: This method does not support reflection matrices.
  8909. *
  8910. * @param {Matrix4} m - The matrix.
  8911. * @return {Matrix4} A reference to this matrix.
  8912. */
  8913. extractRotation( m ) {
  8914. if ( m.determinant() === 0 ) {
  8915. return this.identity();
  8916. }
  8917. const te = this.elements;
  8918. const me = m.elements;
  8919. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8920. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8921. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8922. te[ 0 ] = me[ 0 ] * scaleX;
  8923. te[ 1 ] = me[ 1 ] * scaleX;
  8924. te[ 2 ] = me[ 2 ] * scaleX;
  8925. te[ 3 ] = 0;
  8926. te[ 4 ] = me[ 4 ] * scaleY;
  8927. te[ 5 ] = me[ 5 ] * scaleY;
  8928. te[ 6 ] = me[ 6 ] * scaleY;
  8929. te[ 7 ] = 0;
  8930. te[ 8 ] = me[ 8 ] * scaleZ;
  8931. te[ 9 ] = me[ 9 ] * scaleZ;
  8932. te[ 10 ] = me[ 10 ] * scaleZ;
  8933. te[ 11 ] = 0;
  8934. te[ 12 ] = 0;
  8935. te[ 13 ] = 0;
  8936. te[ 14 ] = 0;
  8937. te[ 15 ] = 1;
  8938. return this;
  8939. }
  8940. /**
  8941. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8942. * the rotation specified by the given Euler angles. The rest of
  8943. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8944. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  8945. * for a complete list.
  8946. *
  8947. * @param {Euler} euler - The Euler angles.
  8948. * @return {Matrix4} A reference to this matrix.
  8949. */
  8950. makeRotationFromEuler( euler ) {
  8951. const te = this.elements;
  8952. const x = euler.x, y = euler.y, z = euler.z;
  8953. const a = Math.cos( x ), b = Math.sin( x );
  8954. const c = Math.cos( y ), d = Math.sin( y );
  8955. const e = Math.cos( z ), f = Math.sin( z );
  8956. if ( euler.order === 'XYZ' ) {
  8957. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8958. te[ 0 ] = c * e;
  8959. te[ 4 ] = - c * f;
  8960. te[ 8 ] = d;
  8961. te[ 1 ] = af + be * d;
  8962. te[ 5 ] = ae - bf * d;
  8963. te[ 9 ] = - b * c;
  8964. te[ 2 ] = bf - ae * d;
  8965. te[ 6 ] = be + af * d;
  8966. te[ 10 ] = a * c;
  8967. } else if ( euler.order === 'YXZ' ) {
  8968. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8969. te[ 0 ] = ce + df * b;
  8970. te[ 4 ] = de * b - cf;
  8971. te[ 8 ] = a * d;
  8972. te[ 1 ] = a * f;
  8973. te[ 5 ] = a * e;
  8974. te[ 9 ] = - b;
  8975. te[ 2 ] = cf * b - de;
  8976. te[ 6 ] = df + ce * b;
  8977. te[ 10 ] = a * c;
  8978. } else if ( euler.order === 'ZXY' ) {
  8979. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8980. te[ 0 ] = ce - df * b;
  8981. te[ 4 ] = - a * f;
  8982. te[ 8 ] = de + cf * b;
  8983. te[ 1 ] = cf + de * b;
  8984. te[ 5 ] = a * e;
  8985. te[ 9 ] = df - ce * b;
  8986. te[ 2 ] = - a * d;
  8987. te[ 6 ] = b;
  8988. te[ 10 ] = a * c;
  8989. } else if ( euler.order === 'ZYX' ) {
  8990. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8991. te[ 0 ] = c * e;
  8992. te[ 4 ] = be * d - af;
  8993. te[ 8 ] = ae * d + bf;
  8994. te[ 1 ] = c * f;
  8995. te[ 5 ] = bf * d + ae;
  8996. te[ 9 ] = af * d - be;
  8997. te[ 2 ] = - d;
  8998. te[ 6 ] = b * c;
  8999. te[ 10 ] = a * c;
  9000. } else if ( euler.order === 'YZX' ) {
  9001. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9002. te[ 0 ] = c * e;
  9003. te[ 4 ] = bd - ac * f;
  9004. te[ 8 ] = bc * f + ad;
  9005. te[ 1 ] = f;
  9006. te[ 5 ] = a * e;
  9007. te[ 9 ] = - b * e;
  9008. te[ 2 ] = - d * e;
  9009. te[ 6 ] = ad * f + bc;
  9010. te[ 10 ] = ac - bd * f;
  9011. } else if ( euler.order === 'XZY' ) {
  9012. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9013. te[ 0 ] = c * e;
  9014. te[ 4 ] = - f;
  9015. te[ 8 ] = d * e;
  9016. te[ 1 ] = ac * f + bd;
  9017. te[ 5 ] = a * e;
  9018. te[ 9 ] = ad * f - bc;
  9019. te[ 2 ] = bc * f - ad;
  9020. te[ 6 ] = b * e;
  9021. te[ 10 ] = bd * f + ac;
  9022. }
  9023. // bottom row
  9024. te[ 3 ] = 0;
  9025. te[ 7 ] = 0;
  9026. te[ 11 ] = 0;
  9027. // last column
  9028. te[ 12 ] = 0;
  9029. te[ 13 ] = 0;
  9030. te[ 14 ] = 0;
  9031. te[ 15 ] = 1;
  9032. return this;
  9033. }
  9034. /**
  9035. * Sets the rotation component of this matrix to the rotation specified by
  9036. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9037. * The rest of the matrix is set to the identity.
  9038. *
  9039. * @param {Quaternion} q - The Quaternion.
  9040. * @return {Matrix4} A reference to this matrix.
  9041. */
  9042. makeRotationFromQuaternion( q ) {
  9043. return this.compose( _zero, q, _one );
  9044. }
  9045. /**
  9046. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9047. * `target`, and oriented by the up-direction.
  9048. *
  9049. * @param {Vector3} eye - The eye vector.
  9050. * @param {Vector3} target - The target vector.
  9051. * @param {Vector3} up - The up vector.
  9052. * @return {Matrix4} A reference to this matrix.
  9053. */
  9054. lookAt( eye, target, up ) {
  9055. const te = this.elements;
  9056. _z.subVectors( eye, target );
  9057. if ( _z.lengthSq() === 0 ) {
  9058. // eye and target are in the same position
  9059. _z.z = 1;
  9060. }
  9061. _z.normalize();
  9062. _x.crossVectors( up, _z );
  9063. if ( _x.lengthSq() === 0 ) {
  9064. // up and z are parallel
  9065. if ( Math.abs( up.z ) === 1 ) {
  9066. _z.x += 0.0001;
  9067. } else {
  9068. _z.z += 0.0001;
  9069. }
  9070. _z.normalize();
  9071. _x.crossVectors( up, _z );
  9072. }
  9073. _x.normalize();
  9074. _y.crossVectors( _z, _x );
  9075. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9076. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9077. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9078. return this;
  9079. }
  9080. /**
  9081. * Post-multiplies this matrix by the given 4x4 matrix.
  9082. *
  9083. * @param {Matrix4} m - The matrix to multiply with.
  9084. * @return {Matrix4} A reference to this matrix.
  9085. */
  9086. multiply( m ) {
  9087. return this.multiplyMatrices( this, m );
  9088. }
  9089. /**
  9090. * Pre-multiplies this matrix by the given 4x4 matrix.
  9091. *
  9092. * @param {Matrix4} m - The matrix to multiply with.
  9093. * @return {Matrix4} A reference to this matrix.
  9094. */
  9095. premultiply( m ) {
  9096. return this.multiplyMatrices( m, this );
  9097. }
  9098. /**
  9099. * Multiples the given 4x4 matrices and stores the result
  9100. * in this matrix.
  9101. *
  9102. * @param {Matrix4} a - The first matrix.
  9103. * @param {Matrix4} b - The second matrix.
  9104. * @return {Matrix4} A reference to this matrix.
  9105. */
  9106. multiplyMatrices( a, b ) {
  9107. const ae = a.elements;
  9108. const be = b.elements;
  9109. const te = this.elements;
  9110. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9111. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9112. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9113. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9114. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9115. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9116. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9117. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9118. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9119. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9120. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9121. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9122. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9123. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9124. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9125. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9126. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9127. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9128. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9129. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9130. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9131. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9132. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9133. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9134. return this;
  9135. }
  9136. /**
  9137. * Multiplies every component of the matrix by the given scalar.
  9138. *
  9139. * @param {number} s - The scalar.
  9140. * @return {Matrix4} A reference to this matrix.
  9141. */
  9142. multiplyScalar( s ) {
  9143. const te = this.elements;
  9144. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9145. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9146. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9147. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9148. return this;
  9149. }
  9150. /**
  9151. * Computes and returns the determinant of this matrix.
  9152. *
  9153. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9154. *
  9155. * @return {number} The determinant.
  9156. */
  9157. determinant() {
  9158. const te = this.elements;
  9159. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9160. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9161. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9162. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9163. const t11 = n23 * n34 - n24 * n33;
  9164. const t12 = n22 * n34 - n24 * n32;
  9165. const t13 = n22 * n33 - n23 * n32;
  9166. const t21 = n21 * n34 - n24 * n31;
  9167. const t22 = n21 * n33 - n23 * n31;
  9168. const t23 = n21 * n32 - n22 * n31;
  9169. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9170. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9171. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9172. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9173. }
  9174. /**
  9175. * Transposes this matrix in place.
  9176. *
  9177. * @return {Matrix4} A reference to this matrix.
  9178. */
  9179. transpose() {
  9180. const te = this.elements;
  9181. let tmp;
  9182. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9183. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9184. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9185. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9186. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9187. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9188. return this;
  9189. }
  9190. /**
  9191. * Sets the position component for this matrix from the given vector,
  9192. * without affecting the rest of the matrix.
  9193. *
  9194. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9195. * @param {number} y - The y component of the vector.
  9196. * @param {number} z - The z component of the vector.
  9197. * @return {Matrix4} A reference to this matrix.
  9198. */
  9199. setPosition( x, y, z ) {
  9200. const te = this.elements;
  9201. if ( x.isVector3 ) {
  9202. te[ 12 ] = x.x;
  9203. te[ 13 ] = x.y;
  9204. te[ 14 ] = x.z;
  9205. } else {
  9206. te[ 12 ] = x;
  9207. te[ 13 ] = y;
  9208. te[ 14 ] = z;
  9209. }
  9210. return this;
  9211. }
  9212. /**
  9213. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9214. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9215. * a zero matrix instead.
  9216. *
  9217. * @return {Matrix4} A reference to this matrix.
  9218. */
  9219. invert() {
  9220. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9221. const te = this.elements,
  9222. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9223. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9224. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9225. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9226. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9227. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9228. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9229. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9230. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9231. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9232. const detInv = 1 / det;
  9233. te[ 0 ] = t11 * detInv;
  9234. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9235. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9236. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9237. te[ 4 ] = t12 * detInv;
  9238. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9239. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9240. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9241. te[ 8 ] = t13 * detInv;
  9242. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9243. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9244. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9245. te[ 12 ] = t14 * detInv;
  9246. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9247. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9248. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9249. return this;
  9250. }
  9251. /**
  9252. * Multiplies the columns of this matrix by the given vector.
  9253. *
  9254. * @param {Vector3} v - The scale vector.
  9255. * @return {Matrix4} A reference to this matrix.
  9256. */
  9257. scale( v ) {
  9258. const te = this.elements;
  9259. const x = v.x, y = v.y, z = v.z;
  9260. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9261. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9262. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9263. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9264. return this;
  9265. }
  9266. /**
  9267. * Gets the maximum scale value of the three axes.
  9268. *
  9269. * @return {number} The maximum scale.
  9270. */
  9271. getMaxScaleOnAxis() {
  9272. const te = this.elements;
  9273. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9274. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9275. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9276. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9277. }
  9278. /**
  9279. * Sets this matrix as a translation transform from the given vector.
  9280. *
  9281. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9282. * @param {number} y - The amount to translate in the Y axis.
  9283. * @param {number} z - The amount to translate in the z axis.
  9284. * @return {Matrix4} A reference to this matrix.
  9285. */
  9286. makeTranslation( x, y, z ) {
  9287. if ( x.isVector3 ) {
  9288. this.set(
  9289. 1, 0, 0, x.x,
  9290. 0, 1, 0, x.y,
  9291. 0, 0, 1, x.z,
  9292. 0, 0, 0, 1
  9293. );
  9294. } else {
  9295. this.set(
  9296. 1, 0, 0, x,
  9297. 0, 1, 0, y,
  9298. 0, 0, 1, z,
  9299. 0, 0, 0, 1
  9300. );
  9301. }
  9302. return this;
  9303. }
  9304. /**
  9305. * Sets this matrix as a rotational transformation around the X axis by
  9306. * the given angle.
  9307. *
  9308. * @param {number} theta - The rotation in radians.
  9309. * @return {Matrix4} A reference to this matrix.
  9310. */
  9311. makeRotationX( theta ) {
  9312. const c = Math.cos( theta ), s = Math.sin( theta );
  9313. this.set(
  9314. 1, 0, 0, 0,
  9315. 0, c, - s, 0,
  9316. 0, s, c, 0,
  9317. 0, 0, 0, 1
  9318. );
  9319. return this;
  9320. }
  9321. /**
  9322. * Sets this matrix as a rotational transformation around the Y axis by
  9323. * the given angle.
  9324. *
  9325. * @param {number} theta - The rotation in radians.
  9326. * @return {Matrix4} A reference to this matrix.
  9327. */
  9328. makeRotationY( theta ) {
  9329. const c = Math.cos( theta ), s = Math.sin( theta );
  9330. this.set(
  9331. c, 0, s, 0,
  9332. 0, 1, 0, 0,
  9333. - s, 0, c, 0,
  9334. 0, 0, 0, 1
  9335. );
  9336. return this;
  9337. }
  9338. /**
  9339. * Sets this matrix as a rotational transformation around the Z axis by
  9340. * the given angle.
  9341. *
  9342. * @param {number} theta - The rotation in radians.
  9343. * @return {Matrix4} A reference to this matrix.
  9344. */
  9345. makeRotationZ( theta ) {
  9346. const c = Math.cos( theta ), s = Math.sin( theta );
  9347. this.set(
  9348. c, - s, 0, 0,
  9349. s, c, 0, 0,
  9350. 0, 0, 1, 0,
  9351. 0, 0, 0, 1
  9352. );
  9353. return this;
  9354. }
  9355. /**
  9356. * Sets this matrix as a rotational transformation around the given axis by
  9357. * the given angle.
  9358. *
  9359. * This is a somewhat controversial but mathematically sound alternative to
  9360. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9361. *
  9362. * @param {Vector3} axis - The normalized rotation axis.
  9363. * @param {number} angle - The rotation in radians.
  9364. * @return {Matrix4} A reference to this matrix.
  9365. */
  9366. makeRotationAxis( axis, angle ) {
  9367. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9368. const c = Math.cos( angle );
  9369. const s = Math.sin( angle );
  9370. const t = 1 - c;
  9371. const x = axis.x, y = axis.y, z = axis.z;
  9372. const tx = t * x, ty = t * y;
  9373. this.set(
  9374. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9375. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9376. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9377. 0, 0, 0, 1
  9378. );
  9379. return this;
  9380. }
  9381. /**
  9382. * Sets this matrix as a scale transformation.
  9383. *
  9384. * @param {number} x - The amount to scale in the X axis.
  9385. * @param {number} y - The amount to scale in the Y axis.
  9386. * @param {number} z - The amount to scale in the Z axis.
  9387. * @return {Matrix4} A reference to this matrix.
  9388. */
  9389. makeScale( x, y, z ) {
  9390. this.set(
  9391. x, 0, 0, 0,
  9392. 0, y, 0, 0,
  9393. 0, 0, z, 0,
  9394. 0, 0, 0, 1
  9395. );
  9396. return this;
  9397. }
  9398. /**
  9399. * Sets this matrix as a shear transformation.
  9400. *
  9401. * @param {number} xy - The amount to shear X by Y.
  9402. * @param {number} xz - The amount to shear X by Z.
  9403. * @param {number} yx - The amount to shear Y by X.
  9404. * @param {number} yz - The amount to shear Y by Z.
  9405. * @param {number} zx - The amount to shear Z by X.
  9406. * @param {number} zy - The amount to shear Z by Y.
  9407. * @return {Matrix4} A reference to this matrix.
  9408. */
  9409. makeShear( xy, xz, yx, yz, zx, zy ) {
  9410. this.set(
  9411. 1, yx, zx, 0,
  9412. xy, 1, zy, 0,
  9413. xz, yz, 1, 0,
  9414. 0, 0, 0, 1
  9415. );
  9416. return this;
  9417. }
  9418. /**
  9419. * Sets this matrix to the transformation composed of the given position,
  9420. * rotation (Quaternion) and scale.
  9421. *
  9422. * @param {Vector3} position - The position vector.
  9423. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9424. * @param {Vector3} scale - The scale vector.
  9425. * @return {Matrix4} A reference to this matrix.
  9426. */
  9427. compose( position, quaternion, scale ) {
  9428. const te = this.elements;
  9429. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9430. const x2 = x + x, y2 = y + y, z2 = z + z;
  9431. const xx = x * x2, xy = x * y2, xz = x * z2;
  9432. const yy = y * y2, yz = y * z2, zz = z * z2;
  9433. const wx = w * x2, wy = w * y2, wz = w * z2;
  9434. const sx = scale.x, sy = scale.y, sz = scale.z;
  9435. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9436. te[ 1 ] = ( xy + wz ) * sx;
  9437. te[ 2 ] = ( xz - wy ) * sx;
  9438. te[ 3 ] = 0;
  9439. te[ 4 ] = ( xy - wz ) * sy;
  9440. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9441. te[ 6 ] = ( yz + wx ) * sy;
  9442. te[ 7 ] = 0;
  9443. te[ 8 ] = ( xz + wy ) * sz;
  9444. te[ 9 ] = ( yz - wx ) * sz;
  9445. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9446. te[ 11 ] = 0;
  9447. te[ 12 ] = position.x;
  9448. te[ 13 ] = position.y;
  9449. te[ 14 ] = position.z;
  9450. te[ 15 ] = 1;
  9451. return this;
  9452. }
  9453. /**
  9454. * Decomposes this matrix into its position, rotation and scale components
  9455. * and provides the result in the given objects.
  9456. *
  9457. * Note: Not all matrices are decomposable in this way. For example, if an
  9458. * object has a non-uniformly scaled parent, then the object's world matrix
  9459. * may not be decomposable, and this method may not be appropriate.
  9460. *
  9461. * @param {Vector3} position - The position vector.
  9462. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9463. * @param {Vector3} scale - The scale vector.
  9464. * @return {Matrix4} A reference to this matrix.
  9465. */
  9466. decompose( position, quaternion, scale ) {
  9467. const te = this.elements;
  9468. position.x = te[ 12 ];
  9469. position.y = te[ 13 ];
  9470. position.z = te[ 14 ];
  9471. if ( this.determinant() === 0 ) {
  9472. scale.set( 1, 1, 1 );
  9473. quaternion.identity();
  9474. return this;
  9475. }
  9476. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9477. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9478. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9479. // if determine is negative, we need to invert one scale
  9480. const det = this.determinant();
  9481. if ( det < 0 ) sx = - sx;
  9482. // scale the rotation part
  9483. _m1$4.copy( this );
  9484. const invSX = 1 / sx;
  9485. const invSY = 1 / sy;
  9486. const invSZ = 1 / sz;
  9487. _m1$4.elements[ 0 ] *= invSX;
  9488. _m1$4.elements[ 1 ] *= invSX;
  9489. _m1$4.elements[ 2 ] *= invSX;
  9490. _m1$4.elements[ 4 ] *= invSY;
  9491. _m1$4.elements[ 5 ] *= invSY;
  9492. _m1$4.elements[ 6 ] *= invSY;
  9493. _m1$4.elements[ 8 ] *= invSZ;
  9494. _m1$4.elements[ 9 ] *= invSZ;
  9495. _m1$4.elements[ 10 ] *= invSZ;
  9496. quaternion.setFromRotationMatrix( _m1$4 );
  9497. scale.x = sx;
  9498. scale.y = sy;
  9499. scale.z = sz;
  9500. return this;
  9501. }
  9502. /**
  9503. * Creates a perspective projection matrix. This is used internally by
  9504. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9505. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9506. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9507. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9508. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9509. * @param {number} near - The distance from the camera to the near plane.
  9510. * @param {number} far - The distance from the camera to the far plane.
  9511. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9512. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9513. * @return {Matrix4} A reference to this matrix.
  9514. */
  9515. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9516. const te = this.elements;
  9517. const x = 2 * near / ( right - left );
  9518. const y = 2 * near / ( top - bottom );
  9519. const a = ( right + left ) / ( right - left );
  9520. const b = ( top + bottom ) / ( top - bottom );
  9521. let c, d;
  9522. if ( reversedDepth ) {
  9523. c = near / ( far - near );
  9524. d = ( far * near ) / ( far - near );
  9525. } else {
  9526. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9527. c = - ( far + near ) / ( far - near );
  9528. d = ( -2 * far * near ) / ( far - near );
  9529. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9530. c = - far / ( far - near );
  9531. d = ( - far * near ) / ( far - near );
  9532. } else {
  9533. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9534. }
  9535. }
  9536. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9537. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9538. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9539. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9540. return this;
  9541. }
  9542. /**
  9543. * Creates a orthographic projection matrix. This is used internally by
  9544. * {@link OrthographicCamera#updateProjectionMatrix}.
  9545. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9546. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9547. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9548. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9549. * @param {number} near - The distance from the camera to the near plane.
  9550. * @param {number} far - The distance from the camera to the far plane.
  9551. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9552. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9553. * @return {Matrix4} A reference to this matrix.
  9554. */
  9555. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9556. const te = this.elements;
  9557. const x = 2 / ( right - left );
  9558. const y = 2 / ( top - bottom );
  9559. const a = - ( right + left ) / ( right - left );
  9560. const b = - ( top + bottom ) / ( top - bottom );
  9561. let c, d;
  9562. if ( reversedDepth ) {
  9563. c = 1 / ( far - near );
  9564. d = far / ( far - near );
  9565. } else {
  9566. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9567. c = -2 / ( far - near );
  9568. d = - ( far + near ) / ( far - near );
  9569. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9570. c = -1 / ( far - near );
  9571. d = - near / ( far - near );
  9572. } else {
  9573. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9574. }
  9575. }
  9576. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9577. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9578. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9579. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9580. return this;
  9581. }
  9582. /**
  9583. * Returns `true` if this matrix is equal with the given one.
  9584. *
  9585. * @param {Matrix4} matrix - The matrix to test for equality.
  9586. * @return {boolean} Whether this matrix is equal with the given one.
  9587. */
  9588. equals( matrix ) {
  9589. const te = this.elements;
  9590. const me = matrix.elements;
  9591. for ( let i = 0; i < 16; i ++ ) {
  9592. if ( te[ i ] !== me[ i ] ) return false;
  9593. }
  9594. return true;
  9595. }
  9596. /**
  9597. * Sets the elements of the matrix from the given array.
  9598. *
  9599. * @param {Array<number>} array - The matrix elements in column-major order.
  9600. * @param {number} [offset=0] - Index of the first element in the array.
  9601. * @return {Matrix4} A reference to this matrix.
  9602. */
  9603. fromArray( array, offset = 0 ) {
  9604. for ( let i = 0; i < 16; i ++ ) {
  9605. this.elements[ i ] = array[ i + offset ];
  9606. }
  9607. return this;
  9608. }
  9609. /**
  9610. * Writes the elements of this matrix to the given array. If no array is provided,
  9611. * the method returns a new instance.
  9612. *
  9613. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9614. * @param {number} [offset=0] - Index of the first element in the array.
  9615. * @return {Array<number>} The matrix elements in column-major order.
  9616. */
  9617. toArray( array = [], offset = 0 ) {
  9618. const te = this.elements;
  9619. array[ offset ] = te[ 0 ];
  9620. array[ offset + 1 ] = te[ 1 ];
  9621. array[ offset + 2 ] = te[ 2 ];
  9622. array[ offset + 3 ] = te[ 3 ];
  9623. array[ offset + 4 ] = te[ 4 ];
  9624. array[ offset + 5 ] = te[ 5 ];
  9625. array[ offset + 6 ] = te[ 6 ];
  9626. array[ offset + 7 ] = te[ 7 ];
  9627. array[ offset + 8 ] = te[ 8 ];
  9628. array[ offset + 9 ] = te[ 9 ];
  9629. array[ offset + 10 ] = te[ 10 ];
  9630. array[ offset + 11 ] = te[ 11 ];
  9631. array[ offset + 12 ] = te[ 12 ];
  9632. array[ offset + 13 ] = te[ 13 ];
  9633. array[ offset + 14 ] = te[ 14 ];
  9634. array[ offset + 15 ] = te[ 15 ];
  9635. return array;
  9636. }
  9637. }
  9638. const _v1$5 = /*@__PURE__*/ new Vector3();
  9639. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9640. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9641. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9642. const _x = /*@__PURE__*/ new Vector3();
  9643. const _y = /*@__PURE__*/ new Vector3();
  9644. const _z = /*@__PURE__*/ new Vector3();
  9645. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9646. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9647. /**
  9648. * A class representing Euler angles.
  9649. *
  9650. * Euler angles describe a rotational transformation by rotating an object on
  9651. * its various axes in specified amounts per axis, and a specified axis
  9652. * order.
  9653. *
  9654. * Iterating through an instance will yield its components (x, y, z,
  9655. * order) in the corresponding order.
  9656. *
  9657. * ```js
  9658. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9659. * const b = new THREE.Vector3( 1, 0, 1 );
  9660. * b.applyEuler(a);
  9661. * ```
  9662. */
  9663. class Euler {
  9664. /**
  9665. * Constructs a new euler instance.
  9666. *
  9667. * @param {number} [x=0] - The angle of the x axis in radians.
  9668. * @param {number} [y=0] - The angle of the y axis in radians.
  9669. * @param {number} [z=0] - The angle of the z axis in radians.
  9670. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9671. */
  9672. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9673. /**
  9674. * This flag can be used for type testing.
  9675. *
  9676. * @type {boolean}
  9677. * @readonly
  9678. * @default true
  9679. */
  9680. this.isEuler = true;
  9681. this._x = x;
  9682. this._y = y;
  9683. this._z = z;
  9684. this._order = order;
  9685. }
  9686. /**
  9687. * The angle of the x axis in radians.
  9688. *
  9689. * @type {number}
  9690. * @default 0
  9691. */
  9692. get x() {
  9693. return this._x;
  9694. }
  9695. set x( value ) {
  9696. this._x = value;
  9697. this._onChangeCallback();
  9698. }
  9699. /**
  9700. * The angle of the y axis in radians.
  9701. *
  9702. * @type {number}
  9703. * @default 0
  9704. */
  9705. get y() {
  9706. return this._y;
  9707. }
  9708. set y( value ) {
  9709. this._y = value;
  9710. this._onChangeCallback();
  9711. }
  9712. /**
  9713. * The angle of the z axis in radians.
  9714. *
  9715. * @type {number}
  9716. * @default 0
  9717. */
  9718. get z() {
  9719. return this._z;
  9720. }
  9721. set z( value ) {
  9722. this._z = value;
  9723. this._onChangeCallback();
  9724. }
  9725. /**
  9726. * A string representing the order that the rotations are applied.
  9727. *
  9728. * @type {string}
  9729. * @default 'XYZ'
  9730. */
  9731. get order() {
  9732. return this._order;
  9733. }
  9734. set order( value ) {
  9735. this._order = value;
  9736. this._onChangeCallback();
  9737. }
  9738. /**
  9739. * Sets the Euler components.
  9740. *
  9741. * @param {number} x - The angle of the x axis in radians.
  9742. * @param {number} y - The angle of the y axis in radians.
  9743. * @param {number} z - The angle of the z axis in radians.
  9744. * @param {string} [order] - A string representing the order that the rotations are applied.
  9745. * @return {Euler} A reference to this Euler instance.
  9746. */
  9747. set( x, y, z, order = this._order ) {
  9748. this._x = x;
  9749. this._y = y;
  9750. this._z = z;
  9751. this._order = order;
  9752. this._onChangeCallback();
  9753. return this;
  9754. }
  9755. /**
  9756. * Returns a new Euler instance with copied values from this instance.
  9757. *
  9758. * @return {Euler} A clone of this instance.
  9759. */
  9760. clone() {
  9761. return new this.constructor( this._x, this._y, this._z, this._order );
  9762. }
  9763. /**
  9764. * Copies the values of the given Euler instance to this instance.
  9765. *
  9766. * @param {Euler} euler - The Euler instance to copy.
  9767. * @return {Euler} A reference to this Euler instance.
  9768. */
  9769. copy( euler ) {
  9770. this._x = euler._x;
  9771. this._y = euler._y;
  9772. this._z = euler._z;
  9773. this._order = euler._order;
  9774. this._onChangeCallback();
  9775. return this;
  9776. }
  9777. /**
  9778. * Sets the angles of this Euler instance from a pure rotation matrix.
  9779. *
  9780. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9781. * @param {string} [order] - A string representing the order that the rotations are applied.
  9782. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9783. * @return {Euler} A reference to this Euler instance.
  9784. */
  9785. setFromRotationMatrix( m, order = this._order, update = true ) {
  9786. const te = m.elements;
  9787. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9788. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9789. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9790. switch ( order ) {
  9791. case 'XYZ':
  9792. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9793. if ( Math.abs( m13 ) < 0.9999999 ) {
  9794. this._x = Math.atan2( - m23, m33 );
  9795. this._z = Math.atan2( - m12, m11 );
  9796. } else {
  9797. this._x = Math.atan2( m32, m22 );
  9798. this._z = 0;
  9799. }
  9800. break;
  9801. case 'YXZ':
  9802. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9803. if ( Math.abs( m23 ) < 0.9999999 ) {
  9804. this._y = Math.atan2( m13, m33 );
  9805. this._z = Math.atan2( m21, m22 );
  9806. } else {
  9807. this._y = Math.atan2( - m31, m11 );
  9808. this._z = 0;
  9809. }
  9810. break;
  9811. case 'ZXY':
  9812. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9813. if ( Math.abs( m32 ) < 0.9999999 ) {
  9814. this._y = Math.atan2( - m31, m33 );
  9815. this._z = Math.atan2( - m12, m22 );
  9816. } else {
  9817. this._y = 0;
  9818. this._z = Math.atan2( m21, m11 );
  9819. }
  9820. break;
  9821. case 'ZYX':
  9822. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9823. if ( Math.abs( m31 ) < 0.9999999 ) {
  9824. this._x = Math.atan2( m32, m33 );
  9825. this._z = Math.atan2( m21, m11 );
  9826. } else {
  9827. this._x = 0;
  9828. this._z = Math.atan2( - m12, m22 );
  9829. }
  9830. break;
  9831. case 'YZX':
  9832. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9833. if ( Math.abs( m21 ) < 0.9999999 ) {
  9834. this._x = Math.atan2( - m23, m22 );
  9835. this._y = Math.atan2( - m31, m11 );
  9836. } else {
  9837. this._x = 0;
  9838. this._y = Math.atan2( m13, m33 );
  9839. }
  9840. break;
  9841. case 'XZY':
  9842. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9843. if ( Math.abs( m12 ) < 0.9999999 ) {
  9844. this._x = Math.atan2( m32, m22 );
  9845. this._y = Math.atan2( m13, m11 );
  9846. } else {
  9847. this._x = Math.atan2( - m23, m33 );
  9848. this._y = 0;
  9849. }
  9850. break;
  9851. default:
  9852. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9853. }
  9854. this._order = order;
  9855. if ( update === true ) this._onChangeCallback();
  9856. return this;
  9857. }
  9858. /**
  9859. * Sets the angles of this Euler instance from a normalized quaternion.
  9860. *
  9861. * @param {Quaternion} q - A normalized Quaternion.
  9862. * @param {string} [order] - A string representing the order that the rotations are applied.
  9863. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9864. * @return {Euler} A reference to this Euler instance.
  9865. */
  9866. setFromQuaternion( q, order, update ) {
  9867. _matrix$2.makeRotationFromQuaternion( q );
  9868. return this.setFromRotationMatrix( _matrix$2, order, update );
  9869. }
  9870. /**
  9871. * Sets the angles of this Euler instance from the given vector.
  9872. *
  9873. * @param {Vector3} v - The vector.
  9874. * @param {string} [order] - A string representing the order that the rotations are applied.
  9875. * @return {Euler} A reference to this Euler instance.
  9876. */
  9877. setFromVector3( v, order = this._order ) {
  9878. return this.set( v.x, v.y, v.z, order );
  9879. }
  9880. /**
  9881. * Resets the euler angle with a new order by creating a quaternion from this
  9882. * euler angle and then setting this euler angle with the quaternion and the
  9883. * new order.
  9884. *
  9885. * Warning: This discards revolution information.
  9886. *
  9887. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9888. * @return {Euler} A reference to this Euler instance.
  9889. */
  9890. reorder( newOrder ) {
  9891. _quaternion$3.setFromEuler( this );
  9892. return this.setFromQuaternion( _quaternion$3, newOrder );
  9893. }
  9894. /**
  9895. * Returns `true` if this Euler instance is equal with the given one.
  9896. *
  9897. * @param {Euler} euler - The Euler instance to test for equality.
  9898. * @return {boolean} Whether this Euler instance is equal with the given one.
  9899. */
  9900. equals( euler ) {
  9901. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9902. }
  9903. /**
  9904. * Sets this Euler instance's components to values from the given array. The first three
  9905. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9906. * defines the Euler order.
  9907. *
  9908. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9909. * @return {Euler} A reference to this Euler instance.
  9910. */
  9911. fromArray( array ) {
  9912. this._x = array[ 0 ];
  9913. this._y = array[ 1 ];
  9914. this._z = array[ 2 ];
  9915. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9916. this._onChangeCallback();
  9917. return this;
  9918. }
  9919. /**
  9920. * Writes the components of this Euler instance to the given array. If no array is provided,
  9921. * the method returns a new instance.
  9922. *
  9923. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9924. * @param {number} [offset=0] - Index of the first element in the array.
  9925. * @return {Array<number,number,number,string>} The Euler components.
  9926. */
  9927. toArray( array = [], offset = 0 ) {
  9928. array[ offset ] = this._x;
  9929. array[ offset + 1 ] = this._y;
  9930. array[ offset + 2 ] = this._z;
  9931. array[ offset + 3 ] = this._order;
  9932. return array;
  9933. }
  9934. _onChange( callback ) {
  9935. this._onChangeCallback = callback;
  9936. return this;
  9937. }
  9938. _onChangeCallback() {}
  9939. *[ Symbol.iterator ]() {
  9940. yield this._x;
  9941. yield this._y;
  9942. yield this._z;
  9943. yield this._order;
  9944. }
  9945. }
  9946. /**
  9947. * The default Euler angle order.
  9948. *
  9949. * @static
  9950. * @type {string}
  9951. * @default 'XYZ'
  9952. */
  9953. Euler.DEFAULT_ORDER = 'XYZ';
  9954. /**
  9955. * A layers object assigns an 3D object to 1 or more of 32
  9956. * layers numbered `0` to `31` - internally the layers are stored as a
  9957. * bit mask], and by default all 3D objects are a member of layer `0`.
  9958. *
  9959. * This can be used to control visibility - an object must share a layer with
  9960. * a camera to be visible when that camera's view is
  9961. * rendered.
  9962. *
  9963. * All classes that inherit from {@link Object3D} have an `layers` property which
  9964. * is an instance of this class.
  9965. */
  9966. class Layers {
  9967. /**
  9968. * Constructs a new layers instance, with membership
  9969. * initially set to layer `0`.
  9970. */
  9971. constructor() {
  9972. /**
  9973. * A bit mask storing which of the 32 layers this layers object is currently
  9974. * a member of.
  9975. *
  9976. * @type {number}
  9977. */
  9978. this.mask = 1 | 0;
  9979. }
  9980. /**
  9981. * Sets membership to the given layer, and remove membership all other layers.
  9982. *
  9983. * @param {number} layer - The layer to set.
  9984. */
  9985. set( layer ) {
  9986. this.mask = ( 1 << layer | 0 ) >>> 0;
  9987. }
  9988. /**
  9989. * Adds membership of the given layer.
  9990. *
  9991. * @param {number} layer - The layer to enable.
  9992. */
  9993. enable( layer ) {
  9994. this.mask |= 1 << layer | 0;
  9995. }
  9996. /**
  9997. * Adds membership to all layers.
  9998. */
  9999. enableAll() {
  10000. this.mask = 0xffffffff | 0;
  10001. }
  10002. /**
  10003. * Toggles the membership of the given layer.
  10004. *
  10005. * @param {number} layer - The layer to toggle.
  10006. */
  10007. toggle( layer ) {
  10008. this.mask ^= 1 << layer | 0;
  10009. }
  10010. /**
  10011. * Removes membership of the given layer.
  10012. *
  10013. * @param {number} layer - The layer to enable.
  10014. */
  10015. disable( layer ) {
  10016. this.mask &= ~ ( 1 << layer | 0 );
  10017. }
  10018. /**
  10019. * Removes the membership from all layers.
  10020. */
  10021. disableAll() {
  10022. this.mask = 0;
  10023. }
  10024. /**
  10025. * Returns `true` if this and the given layers object have at least one
  10026. * layer in common.
  10027. *
  10028. * @param {Layers} layers - The layers to test.
  10029. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10030. */
  10031. test( layers ) {
  10032. return ( this.mask & layers.mask ) !== 0;
  10033. }
  10034. /**
  10035. * Returns `true` if the given layer is enabled.
  10036. *
  10037. * @param {number} layer - The layer to test.
  10038. * @return {boolean } Whether the given layer is enabled or not.
  10039. */
  10040. isEnabled( layer ) {
  10041. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10042. }
  10043. }
  10044. let _object3DId = 0;
  10045. const _v1$4 = /*@__PURE__*/ new Vector3();
  10046. const _q1 = /*@__PURE__*/ new Quaternion();
  10047. const _m1$3 = /*@__PURE__*/ new Matrix4();
  10048. const _target = /*@__PURE__*/ new Vector3();
  10049. const _position$3 = /*@__PURE__*/ new Vector3();
  10050. const _scale$2 = /*@__PURE__*/ new Vector3();
  10051. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10052. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10053. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10054. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10055. /**
  10056. * Fires when the object has been added to its parent object.
  10057. *
  10058. * @event Object3D#added
  10059. * @type {Object}
  10060. */
  10061. const _addedEvent = { type: 'added' };
  10062. /**
  10063. * Fires when the object has been removed from its parent object.
  10064. *
  10065. * @event Object3D#removed
  10066. * @type {Object}
  10067. */
  10068. const _removedEvent = { type: 'removed' };
  10069. /**
  10070. * Fires when a new child object has been added.
  10071. *
  10072. * @event Object3D#childadded
  10073. * @type {Object}
  10074. */
  10075. const _childaddedEvent = { type: 'childadded', child: null };
  10076. /**
  10077. * Fires when a child object has been removed.
  10078. *
  10079. * @event Object3D#childremoved
  10080. * @type {Object}
  10081. */
  10082. const _childremovedEvent = { type: 'childremoved', child: null };
  10083. /**
  10084. * This is the base class for most objects in three.js and provides a set of
  10085. * properties and methods for manipulating objects in 3D space.
  10086. *
  10087. * @augments EventDispatcher
  10088. */
  10089. class Object3D extends EventDispatcher {
  10090. /**
  10091. * Constructs a new 3D object.
  10092. */
  10093. constructor() {
  10094. super();
  10095. /**
  10096. * This flag can be used for type testing.
  10097. *
  10098. * @type {boolean}
  10099. * @readonly
  10100. * @default true
  10101. */
  10102. this.isObject3D = true;
  10103. /**
  10104. * The ID of the 3D object.
  10105. *
  10106. * @name Object3D#id
  10107. * @type {number}
  10108. * @readonly
  10109. */
  10110. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10111. /**
  10112. * The UUID of the 3D object.
  10113. *
  10114. * @type {string}
  10115. * @readonly
  10116. */
  10117. this.uuid = generateUUID();
  10118. /**
  10119. * The name of the 3D object.
  10120. *
  10121. * @type {string}
  10122. */
  10123. this.name = '';
  10124. /**
  10125. * The type property is used for detecting the object type
  10126. * in context of serialization/deserialization.
  10127. *
  10128. * @type {string}
  10129. * @readonly
  10130. */
  10131. this.type = 'Object3D';
  10132. /**
  10133. * A reference to the parent object.
  10134. *
  10135. * @type {?Object3D}
  10136. * @default null
  10137. */
  10138. this.parent = null;
  10139. /**
  10140. * An array holding the child 3D objects of this instance.
  10141. *
  10142. * @type {Array<Object3D>}
  10143. */
  10144. this.children = [];
  10145. /**
  10146. * Defines the `up` direction of the 3D object which influences
  10147. * the orientation via methods like {@link Object3D#lookAt}.
  10148. *
  10149. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10150. *
  10151. * @type {Vector3}
  10152. */
  10153. this.up = Object3D.DEFAULT_UP.clone();
  10154. const position = new Vector3();
  10155. const rotation = new Euler();
  10156. const quaternion = new Quaternion();
  10157. const scale = new Vector3( 1, 1, 1 );
  10158. function onRotationChange() {
  10159. quaternion.setFromEuler( rotation, false );
  10160. }
  10161. function onQuaternionChange() {
  10162. rotation.setFromQuaternion( quaternion, undefined, false );
  10163. }
  10164. rotation._onChange( onRotationChange );
  10165. quaternion._onChange( onQuaternionChange );
  10166. Object.defineProperties( this, {
  10167. /**
  10168. * Represents the object's local position.
  10169. *
  10170. * @name Object3D#position
  10171. * @type {Vector3}
  10172. * @default (0,0,0)
  10173. */
  10174. position: {
  10175. configurable: true,
  10176. enumerable: true,
  10177. value: position
  10178. },
  10179. /**
  10180. * Represents the object's local rotation as Euler angles, in radians.
  10181. *
  10182. * @name Object3D#rotation
  10183. * @type {Euler}
  10184. * @default (0,0,0)
  10185. */
  10186. rotation: {
  10187. configurable: true,
  10188. enumerable: true,
  10189. value: rotation
  10190. },
  10191. /**
  10192. * Represents the object's local rotation as Quaternions.
  10193. *
  10194. * @name Object3D#quaternion
  10195. * @type {Quaternion}
  10196. */
  10197. quaternion: {
  10198. configurable: true,
  10199. enumerable: true,
  10200. value: quaternion
  10201. },
  10202. /**
  10203. * Represents the object's local scale.
  10204. *
  10205. * @name Object3D#scale
  10206. * @type {Vector3}
  10207. * @default (1,1,1)
  10208. */
  10209. scale: {
  10210. configurable: true,
  10211. enumerable: true,
  10212. value: scale
  10213. },
  10214. /**
  10215. * Represents the object's model-view matrix.
  10216. *
  10217. * @name Object3D#modelViewMatrix
  10218. * @type {Matrix4}
  10219. */
  10220. modelViewMatrix: {
  10221. value: new Matrix4()
  10222. },
  10223. /**
  10224. * Represents the object's normal matrix.
  10225. *
  10226. * @name Object3D#normalMatrix
  10227. * @type {Matrix3}
  10228. */
  10229. normalMatrix: {
  10230. value: new Matrix3()
  10231. }
  10232. } );
  10233. /**
  10234. * Represents the object's transformation matrix in local space.
  10235. *
  10236. * @type {Matrix4}
  10237. */
  10238. this.matrix = new Matrix4();
  10239. /**
  10240. * Represents the object's transformation matrix in world space.
  10241. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10242. *
  10243. * @type {Matrix4}
  10244. */
  10245. this.matrixWorld = new Matrix4();
  10246. /**
  10247. * When set to `true`, the engine automatically computes the local matrix from position,
  10248. * rotation and scale every frame.
  10249. *
  10250. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10251. *
  10252. * @type {boolean}
  10253. * @default true
  10254. */
  10255. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10256. /**
  10257. * When set to `true`, the engine automatically computes the world matrix from the current local
  10258. * matrix and the object's transformation hierarchy.
  10259. *
  10260. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10261. *
  10262. * @type {boolean}
  10263. * @default true
  10264. */
  10265. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10266. /**
  10267. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10268. * to `false`.
  10269. *
  10270. * @type {boolean}
  10271. * @default false
  10272. */
  10273. this.matrixWorldNeedsUpdate = false;
  10274. /**
  10275. * The layer membership of the 3D object. The 3D object is only visible if it has
  10276. * at least one layer in common with the camera in use. This property can also be
  10277. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10278. *
  10279. * @type {Layers}
  10280. */
  10281. this.layers = new Layers();
  10282. /**
  10283. * When set to `true`, the 3D object gets rendered.
  10284. *
  10285. * @type {boolean}
  10286. * @default true
  10287. */
  10288. this.visible = true;
  10289. /**
  10290. * When set to `true`, the 3D object gets rendered into shadow maps.
  10291. *
  10292. * @type {boolean}
  10293. * @default false
  10294. */
  10295. this.castShadow = false;
  10296. /**
  10297. * When set to `true`, the 3D object is affected by shadows in the scene.
  10298. *
  10299. * @type {boolean}
  10300. * @default false
  10301. */
  10302. this.receiveShadow = false;
  10303. /**
  10304. * When set to `true`, the 3D object is honored by view frustum culling.
  10305. *
  10306. * @type {boolean}
  10307. * @default true
  10308. */
  10309. this.frustumCulled = true;
  10310. /**
  10311. * This value allows the default rendering order of scene graph objects to be
  10312. * overridden although opaque and transparent objects remain sorted independently.
  10313. * When this property is set for an instance of {@link Group},all descendants
  10314. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10315. * render order.
  10316. *
  10317. * @type {number}
  10318. * @default 0
  10319. */
  10320. this.renderOrder = 0;
  10321. /**
  10322. * An array holding the animation clips of the 3D object.
  10323. *
  10324. * @type {Array<AnimationClip>}
  10325. */
  10326. this.animations = [];
  10327. /**
  10328. * Custom depth material to be used when rendering to the depth map. Can only be used
  10329. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10330. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10331. * material for proper shadows.
  10332. *
  10333. * Only relevant in context of {@link WebGLRenderer}.
  10334. *
  10335. * @type {(Material|undefined)}
  10336. * @default undefined
  10337. */
  10338. this.customDepthMaterial = undefined;
  10339. /**
  10340. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10341. *
  10342. * Only relevant in context of {@link WebGLRenderer}.
  10343. *
  10344. * @type {(Material|undefined)}
  10345. * @default undefined
  10346. */
  10347. this.customDistanceMaterial = undefined;
  10348. /**
  10349. * An object that can be used to store custom data about the 3D object. It
  10350. * should not hold references to functions as these will not be cloned.
  10351. *
  10352. * @type {Object}
  10353. */
  10354. this.userData = {};
  10355. }
  10356. /**
  10357. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10358. *
  10359. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10360. * @param {Object3D} object - The 3D object.
  10361. * @param {Camera} camera - The camera that is used to render the scene.
  10362. * @param {Camera} shadowCamera - The shadow camera.
  10363. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10364. * @param {Material} depthMaterial - The depth material.
  10365. * @param {Object} group - The geometry group data.
  10366. */
  10367. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10368. /**
  10369. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10370. *
  10371. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10372. * @param {Object3D} object - The 3D object.
  10373. * @param {Camera} camera - The camera that is used to render the scene.
  10374. * @param {Camera} shadowCamera - The shadow camera.
  10375. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10376. * @param {Material} depthMaterial - The depth material.
  10377. * @param {Object} group - The geometry group data.
  10378. */
  10379. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10380. /**
  10381. * A callback that is executed immediately before a 3D object is rendered.
  10382. *
  10383. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10384. * @param {Object3D} object - The 3D object.
  10385. * @param {Camera} camera - The camera that is used to render the scene.
  10386. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10387. * @param {Material} material - The 3D object's material.
  10388. * @param {Object} group - The geometry group data.
  10389. */
  10390. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10391. /**
  10392. * A callback that is executed immediately after a 3D object is rendered.
  10393. *
  10394. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10395. * @param {Object3D} object - The 3D object.
  10396. * @param {Camera} camera - The camera that is used to render the scene.
  10397. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10398. * @param {Material} material - The 3D object's material.
  10399. * @param {Object} group - The geometry group data.
  10400. */
  10401. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10402. /**
  10403. * Applies the given transformation matrix to the object and updates the object's position,
  10404. * rotation and scale.
  10405. *
  10406. * @param {Matrix4} matrix - The transformation matrix.
  10407. */
  10408. applyMatrix4( matrix ) {
  10409. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10410. this.matrix.premultiply( matrix );
  10411. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10412. }
  10413. /**
  10414. * Applies a rotation represented by given the quaternion to the 3D object.
  10415. *
  10416. * @param {Quaternion} q - The quaternion.
  10417. * @return {Object3D} A reference to this instance.
  10418. */
  10419. applyQuaternion( q ) {
  10420. this.quaternion.premultiply( q );
  10421. return this;
  10422. }
  10423. /**
  10424. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10425. *
  10426. * @param {Vector3} axis - The (normalized) axis vector.
  10427. * @param {number} angle - The angle in radians.
  10428. */
  10429. setRotationFromAxisAngle( axis, angle ) {
  10430. // assumes axis is normalized
  10431. this.quaternion.setFromAxisAngle( axis, angle );
  10432. }
  10433. /**
  10434. * Sets the given rotation represented as Euler angles to the 3D object.
  10435. *
  10436. * @param {Euler} euler - The Euler angles.
  10437. */
  10438. setRotationFromEuler( euler ) {
  10439. this.quaternion.setFromEuler( euler, true );
  10440. }
  10441. /**
  10442. * Sets the given rotation represented as rotation matrix to the 3D object.
  10443. *
  10444. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10445. * a pure rotation matrix (i.e, unscaled).
  10446. */
  10447. setRotationFromMatrix( m ) {
  10448. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10449. this.quaternion.setFromRotationMatrix( m );
  10450. }
  10451. /**
  10452. * Sets the given rotation represented as a Quaternion to the 3D object.
  10453. *
  10454. * @param {Quaternion} q - The Quaternion
  10455. */
  10456. setRotationFromQuaternion( q ) {
  10457. // assumes q is normalized
  10458. this.quaternion.copy( q );
  10459. }
  10460. /**
  10461. * Rotates the 3D object along an axis in local space.
  10462. *
  10463. * @param {Vector3} axis - The (normalized) axis vector.
  10464. * @param {number} angle - The angle in radians.
  10465. * @return {Object3D} A reference to this instance.
  10466. */
  10467. rotateOnAxis( axis, angle ) {
  10468. // rotate object on axis in object space
  10469. // axis is assumed to be normalized
  10470. _q1.setFromAxisAngle( axis, angle );
  10471. this.quaternion.multiply( _q1 );
  10472. return this;
  10473. }
  10474. /**
  10475. * Rotates the 3D object along an axis in world space.
  10476. *
  10477. * @param {Vector3} axis - The (normalized) axis vector.
  10478. * @param {number} angle - The angle in radians.
  10479. * @return {Object3D} A reference to this instance.
  10480. */
  10481. rotateOnWorldAxis( axis, angle ) {
  10482. // rotate object on axis in world space
  10483. // axis is assumed to be normalized
  10484. // method assumes no rotated parent
  10485. _q1.setFromAxisAngle( axis, angle );
  10486. this.quaternion.premultiply( _q1 );
  10487. return this;
  10488. }
  10489. /**
  10490. * Rotates the 3D object around its X axis in local space.
  10491. *
  10492. * @param {number} angle - The angle in radians.
  10493. * @return {Object3D} A reference to this instance.
  10494. */
  10495. rotateX( angle ) {
  10496. return this.rotateOnAxis( _xAxis, angle );
  10497. }
  10498. /**
  10499. * Rotates the 3D object around its Y axis in local space.
  10500. *
  10501. * @param {number} angle - The angle in radians.
  10502. * @return {Object3D} A reference to this instance.
  10503. */
  10504. rotateY( angle ) {
  10505. return this.rotateOnAxis( _yAxis, angle );
  10506. }
  10507. /**
  10508. * Rotates the 3D object around its Z axis in local space.
  10509. *
  10510. * @param {number} angle - The angle in radians.
  10511. * @return {Object3D} A reference to this instance.
  10512. */
  10513. rotateZ( angle ) {
  10514. return this.rotateOnAxis( _zAxis, angle );
  10515. }
  10516. /**
  10517. * Translate the 3D object by a distance along the given axis in local space.
  10518. *
  10519. * @param {Vector3} axis - The (normalized) axis vector.
  10520. * @param {number} distance - The distance in world units.
  10521. * @return {Object3D} A reference to this instance.
  10522. */
  10523. translateOnAxis( axis, distance ) {
  10524. // translate object by distance along axis in object space
  10525. // axis is assumed to be normalized
  10526. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10527. this.position.add( _v1$4.multiplyScalar( distance ) );
  10528. return this;
  10529. }
  10530. /**
  10531. * Translate the 3D object by a distance along its X-axis in local space.
  10532. *
  10533. * @param {number} distance - The distance in world units.
  10534. * @return {Object3D} A reference to this instance.
  10535. */
  10536. translateX( distance ) {
  10537. return this.translateOnAxis( _xAxis, distance );
  10538. }
  10539. /**
  10540. * Translate the 3D object by a distance along its Y-axis in local space.
  10541. *
  10542. * @param {number} distance - The distance in world units.
  10543. * @return {Object3D} A reference to this instance.
  10544. */
  10545. translateY( distance ) {
  10546. return this.translateOnAxis( _yAxis, distance );
  10547. }
  10548. /**
  10549. * Translate the 3D object by a distance along its Z-axis in local space.
  10550. *
  10551. * @param {number} distance - The distance in world units.
  10552. * @return {Object3D} A reference to this instance.
  10553. */
  10554. translateZ( distance ) {
  10555. return this.translateOnAxis( _zAxis, distance );
  10556. }
  10557. /**
  10558. * Converts the given vector from this 3D object's local space to world space.
  10559. *
  10560. * @param {Vector3} vector - The vector to convert.
  10561. * @return {Vector3} The converted vector.
  10562. */
  10563. localToWorld( vector ) {
  10564. this.updateWorldMatrix( true, false );
  10565. return vector.applyMatrix4( this.matrixWorld );
  10566. }
  10567. /**
  10568. * Converts the given vector from this 3D object's word space to local space.
  10569. *
  10570. * @param {Vector3} vector - The vector to convert.
  10571. * @return {Vector3} The converted vector.
  10572. */
  10573. worldToLocal( vector ) {
  10574. this.updateWorldMatrix( true, false );
  10575. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10576. }
  10577. /**
  10578. * Rotates the object to face a point in world space.
  10579. *
  10580. * This method does not support objects having non-uniformly-scaled parent(s).
  10581. *
  10582. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10583. * @param {number} [y] - The y coordinate in world space.
  10584. * @param {number} [z] - The z coordinate in world space.
  10585. */
  10586. lookAt( x, y, z ) {
  10587. // This method does not support objects having non-uniformly-scaled parent(s)
  10588. if ( x.isVector3 ) {
  10589. _target.copy( x );
  10590. } else {
  10591. _target.set( x, y, z );
  10592. }
  10593. const parent = this.parent;
  10594. this.updateWorldMatrix( true, false );
  10595. _position$3.setFromMatrixPosition( this.matrixWorld );
  10596. if ( this.isCamera || this.isLight ) {
  10597. _m1$3.lookAt( _position$3, _target, this.up );
  10598. } else {
  10599. _m1$3.lookAt( _target, _position$3, this.up );
  10600. }
  10601. this.quaternion.setFromRotationMatrix( _m1$3 );
  10602. if ( parent ) {
  10603. _m1$3.extractRotation( parent.matrixWorld );
  10604. _q1.setFromRotationMatrix( _m1$3 );
  10605. this.quaternion.premultiply( _q1.invert() );
  10606. }
  10607. }
  10608. /**
  10609. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10610. * objects may be added. Any current parent on an object passed in here will be
  10611. * removed, since an object can have at most one parent.
  10612. *
  10613. * @fires Object3D#added
  10614. * @fires Object3D#childadded
  10615. * @param {Object3D} object - The 3D object to add.
  10616. * @return {Object3D} A reference to this instance.
  10617. */
  10618. add( object ) {
  10619. if ( arguments.length > 1 ) {
  10620. for ( let i = 0; i < arguments.length; i ++ ) {
  10621. this.add( arguments[ i ] );
  10622. }
  10623. return this;
  10624. }
  10625. if ( object === this ) {
  10626. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10627. return this;
  10628. }
  10629. if ( object && object.isObject3D ) {
  10630. object.removeFromParent();
  10631. object.parent = this;
  10632. this.children.push( object );
  10633. object.dispatchEvent( _addedEvent );
  10634. _childaddedEvent.child = object;
  10635. this.dispatchEvent( _childaddedEvent );
  10636. _childaddedEvent.child = null;
  10637. } else {
  10638. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10639. }
  10640. return this;
  10641. }
  10642. /**
  10643. * Removes the given 3D object as child from this 3D object.
  10644. * An arbitrary number of objects may be removed.
  10645. *
  10646. * @fires Object3D#removed
  10647. * @fires Object3D#childremoved
  10648. * @param {Object3D} object - The 3D object to remove.
  10649. * @return {Object3D} A reference to this instance.
  10650. */
  10651. remove( object ) {
  10652. if ( arguments.length > 1 ) {
  10653. for ( let i = 0; i < arguments.length; i ++ ) {
  10654. this.remove( arguments[ i ] );
  10655. }
  10656. return this;
  10657. }
  10658. const index = this.children.indexOf( object );
  10659. if ( index !== -1 ) {
  10660. object.parent = null;
  10661. this.children.splice( index, 1 );
  10662. object.dispatchEvent( _removedEvent );
  10663. _childremovedEvent.child = object;
  10664. this.dispatchEvent( _childremovedEvent );
  10665. _childremovedEvent.child = null;
  10666. }
  10667. return this;
  10668. }
  10669. /**
  10670. * Removes this 3D object from its current parent.
  10671. *
  10672. * @fires Object3D#removed
  10673. * @fires Object3D#childremoved
  10674. * @return {Object3D} A reference to this instance.
  10675. */
  10676. removeFromParent() {
  10677. const parent = this.parent;
  10678. if ( parent !== null ) {
  10679. parent.remove( this );
  10680. }
  10681. return this;
  10682. }
  10683. /**
  10684. * Removes all child objects.
  10685. *
  10686. * @fires Object3D#removed
  10687. * @fires Object3D#childremoved
  10688. * @return {Object3D} A reference to this instance.
  10689. */
  10690. clear() {
  10691. return this.remove( ... this.children );
  10692. }
  10693. /**
  10694. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10695. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10696. *
  10697. * @fires Object3D#added
  10698. * @fires Object3D#childadded
  10699. * @param {Object3D} object - The 3D object to attach.
  10700. * @return {Object3D} A reference to this instance.
  10701. */
  10702. attach( object ) {
  10703. // adds object as a child of this, while maintaining the object's world transform
  10704. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10705. this.updateWorldMatrix( true, false );
  10706. _m1$3.copy( this.matrixWorld ).invert();
  10707. if ( object.parent !== null ) {
  10708. object.parent.updateWorldMatrix( true, false );
  10709. _m1$3.multiply( object.parent.matrixWorld );
  10710. }
  10711. object.applyMatrix4( _m1$3 );
  10712. object.removeFromParent();
  10713. object.parent = this;
  10714. this.children.push( object );
  10715. object.updateWorldMatrix( false, true );
  10716. object.dispatchEvent( _addedEvent );
  10717. _childaddedEvent.child = object;
  10718. this.dispatchEvent( _childaddedEvent );
  10719. _childaddedEvent.child = null;
  10720. return this;
  10721. }
  10722. /**
  10723. * Searches through the 3D object and its children, starting with the 3D object
  10724. * itself, and returns the first with a matching ID.
  10725. *
  10726. * @param {number} id - The id.
  10727. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10728. */
  10729. getObjectById( id ) {
  10730. return this.getObjectByProperty( 'id', id );
  10731. }
  10732. /**
  10733. * Searches through the 3D object and its children, starting with the 3D object
  10734. * itself, and returns the first with a matching name.
  10735. *
  10736. * @param {string} name - The name.
  10737. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10738. */
  10739. getObjectByName( name ) {
  10740. return this.getObjectByProperty( 'name', name );
  10741. }
  10742. /**
  10743. * Searches through the 3D object and its children, starting with the 3D object
  10744. * itself, and returns the first with a matching property value.
  10745. *
  10746. * @param {string} name - The name of the property.
  10747. * @param {any} value - The value.
  10748. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10749. */
  10750. getObjectByProperty( name, value ) {
  10751. if ( this[ name ] === value ) return this;
  10752. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10753. const child = this.children[ i ];
  10754. const object = child.getObjectByProperty( name, value );
  10755. if ( object !== undefined ) {
  10756. return object;
  10757. }
  10758. }
  10759. return undefined;
  10760. }
  10761. /**
  10762. * Searches through the 3D object and its children, starting with the 3D object
  10763. * itself, and returns all 3D objects with a matching property value.
  10764. *
  10765. * @param {string} name - The name of the property.
  10766. * @param {any} value - The value.
  10767. * @param {Array<Object3D>} result - The method stores the result in this array.
  10768. * @return {Array<Object3D>} The found 3D objects.
  10769. */
  10770. getObjectsByProperty( name, value, result = [] ) {
  10771. if ( this[ name ] === value ) result.push( this );
  10772. const children = this.children;
  10773. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10774. children[ i ].getObjectsByProperty( name, value, result );
  10775. }
  10776. return result;
  10777. }
  10778. /**
  10779. * Returns a vector representing the position of the 3D object in world space.
  10780. *
  10781. * @param {Vector3} target - The target vector the result is stored to.
  10782. * @return {Vector3} The 3D object's position in world space.
  10783. */
  10784. getWorldPosition( target ) {
  10785. this.updateWorldMatrix( true, false );
  10786. return target.setFromMatrixPosition( this.matrixWorld );
  10787. }
  10788. /**
  10789. * Returns a Quaternion representing the position of the 3D object in world space.
  10790. *
  10791. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10792. * @return {Quaternion} The 3D object's rotation in world space.
  10793. */
  10794. getWorldQuaternion( target ) {
  10795. this.updateWorldMatrix( true, false );
  10796. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10797. return target;
  10798. }
  10799. /**
  10800. * Returns a vector representing the scale of the 3D object in world space.
  10801. *
  10802. * @param {Vector3} target - The target vector the result is stored to.
  10803. * @return {Vector3} The 3D object's scale in world space.
  10804. */
  10805. getWorldScale( target ) {
  10806. this.updateWorldMatrix( true, false );
  10807. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10808. return target;
  10809. }
  10810. /**
  10811. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10812. *
  10813. * @param {Vector3} target - The target vector the result is stored to.
  10814. * @return {Vector3} The 3D object's direction in world space.
  10815. */
  10816. getWorldDirection( target ) {
  10817. this.updateWorldMatrix( true, false );
  10818. const e = this.matrixWorld.elements;
  10819. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10820. }
  10821. /**
  10822. * Abstract method to get intersections between a casted ray and this
  10823. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10824. * implement this method in order to use raycasting.
  10825. *
  10826. * @abstract
  10827. * @param {Raycaster} raycaster - The raycaster.
  10828. * @param {Array<Object>} intersects - An array holding the result of the method.
  10829. */
  10830. raycast( /* raycaster, intersects */ ) {}
  10831. /**
  10832. * Executes the callback on this 3D object and all descendants.
  10833. *
  10834. * Note: Modifying the scene graph inside the callback is discouraged.
  10835. *
  10836. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10837. */
  10838. traverse( callback ) {
  10839. callback( this );
  10840. const children = this.children;
  10841. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10842. children[ i ].traverse( callback );
  10843. }
  10844. }
  10845. /**
  10846. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10847. * Descendants of invisible 3D objects are not traversed.
  10848. *
  10849. * Note: Modifying the scene graph inside the callback is discouraged.
  10850. *
  10851. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10852. */
  10853. traverseVisible( callback ) {
  10854. if ( this.visible === false ) return;
  10855. callback( this );
  10856. const children = this.children;
  10857. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10858. children[ i ].traverseVisible( callback );
  10859. }
  10860. }
  10861. /**
  10862. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10863. *
  10864. * Note: Modifying the scene graph inside the callback is discouraged.
  10865. *
  10866. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10867. */
  10868. traverseAncestors( callback ) {
  10869. const parent = this.parent;
  10870. if ( parent !== null ) {
  10871. callback( parent );
  10872. parent.traverseAncestors( callback );
  10873. }
  10874. }
  10875. /**
  10876. * Updates the transformation matrix in local space by computing it from the current
  10877. * position, rotation and scale values.
  10878. */
  10879. updateMatrix() {
  10880. this.matrix.compose( this.position, this.quaternion, this.scale );
  10881. this.matrixWorldNeedsUpdate = true;
  10882. }
  10883. /**
  10884. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10885. *
  10886. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10887. * local space. The computation of the local and world matrix can be controlled with the
  10888. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10889. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10890. *
  10891. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10892. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10893. */
  10894. updateMatrixWorld( force ) {
  10895. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10896. if ( this.matrixWorldNeedsUpdate || force ) {
  10897. if ( this.matrixWorldAutoUpdate === true ) {
  10898. if ( this.parent === null ) {
  10899. this.matrixWorld.copy( this.matrix );
  10900. } else {
  10901. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10902. }
  10903. }
  10904. this.matrixWorldNeedsUpdate = false;
  10905. force = true;
  10906. }
  10907. // make sure descendants are updated if required
  10908. const children = this.children;
  10909. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10910. const child = children[ i ];
  10911. child.updateMatrixWorld( force );
  10912. }
  10913. }
  10914. /**
  10915. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10916. * update of ancestor and descendant nodes.
  10917. *
  10918. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10919. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10920. */
  10921. updateWorldMatrix( updateParents, updateChildren ) {
  10922. const parent = this.parent;
  10923. if ( updateParents === true && parent !== null ) {
  10924. parent.updateWorldMatrix( true, false );
  10925. }
  10926. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10927. if ( this.matrixWorldAutoUpdate === true ) {
  10928. if ( this.parent === null ) {
  10929. this.matrixWorld.copy( this.matrix );
  10930. } else {
  10931. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10932. }
  10933. }
  10934. // make sure descendants are updated
  10935. if ( updateChildren === true ) {
  10936. const children = this.children;
  10937. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10938. const child = children[ i ];
  10939. child.updateWorldMatrix( false, true );
  10940. }
  10941. }
  10942. }
  10943. /**
  10944. * Serializes the 3D object into JSON.
  10945. *
  10946. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10947. * @return {Object} A JSON object representing the serialized 3D object.
  10948. * @see {@link ObjectLoader#parse}
  10949. */
  10950. toJSON( meta ) {
  10951. // meta is a string when called from JSON.stringify
  10952. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10953. const output = {};
  10954. // meta is a hash used to collect geometries, materials.
  10955. // not providing it implies that this is the root object
  10956. // being serialized.
  10957. if ( isRootObject ) {
  10958. // initialize meta obj
  10959. meta = {
  10960. geometries: {},
  10961. materials: {},
  10962. textures: {},
  10963. images: {},
  10964. shapes: {},
  10965. skeletons: {},
  10966. animations: {},
  10967. nodes: {}
  10968. };
  10969. output.metadata = {
  10970. version: 4.7,
  10971. type: 'Object',
  10972. generator: 'Object3D.toJSON'
  10973. };
  10974. }
  10975. // standard Object3D serialization
  10976. const object = {};
  10977. object.uuid = this.uuid;
  10978. object.type = this.type;
  10979. if ( this.name !== '' ) object.name = this.name;
  10980. if ( this.castShadow === true ) object.castShadow = true;
  10981. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10982. if ( this.visible === false ) object.visible = false;
  10983. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10984. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10985. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10986. object.layers = this.layers.mask;
  10987. object.matrix = this.matrix.toArray();
  10988. object.up = this.up.toArray();
  10989. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  10990. // object specific properties
  10991. if ( this.isInstancedMesh ) {
  10992. object.type = 'InstancedMesh';
  10993. object.count = this.count;
  10994. object.instanceMatrix = this.instanceMatrix.toJSON();
  10995. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  10996. }
  10997. if ( this.isBatchedMesh ) {
  10998. object.type = 'BatchedMesh';
  10999. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11000. object.sortObjects = this.sortObjects;
  11001. object.drawRanges = this._drawRanges;
  11002. object.reservedRanges = this._reservedRanges;
  11003. object.geometryInfo = this._geometryInfo.map( info => ( {
  11004. ...info,
  11005. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11006. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11007. } ) );
  11008. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11009. object.availableInstanceIds = this._availableInstanceIds.slice();
  11010. object.availableGeometryIds = this._availableGeometryIds.slice();
  11011. object.nextIndexStart = this._nextIndexStart;
  11012. object.nextVertexStart = this._nextVertexStart;
  11013. object.geometryCount = this._geometryCount;
  11014. object.maxInstanceCount = this._maxInstanceCount;
  11015. object.maxVertexCount = this._maxVertexCount;
  11016. object.maxIndexCount = this._maxIndexCount;
  11017. object.geometryInitialized = this._geometryInitialized;
  11018. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11019. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11020. if ( this._colorsTexture !== null ) {
  11021. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11022. }
  11023. if ( this.boundingSphere !== null ) {
  11024. object.boundingSphere = this.boundingSphere.toJSON();
  11025. }
  11026. if ( this.boundingBox !== null ) {
  11027. object.boundingBox = this.boundingBox.toJSON();
  11028. }
  11029. }
  11030. //
  11031. function serialize( library, element ) {
  11032. if ( library[ element.uuid ] === undefined ) {
  11033. library[ element.uuid ] = element.toJSON( meta );
  11034. }
  11035. return element.uuid;
  11036. }
  11037. if ( this.isScene ) {
  11038. if ( this.background ) {
  11039. if ( this.background.isColor ) {
  11040. object.background = this.background.toJSON();
  11041. } else if ( this.background.isTexture ) {
  11042. object.background = this.background.toJSON( meta ).uuid;
  11043. }
  11044. }
  11045. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11046. object.environment = this.environment.toJSON( meta ).uuid;
  11047. }
  11048. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11049. object.geometry = serialize( meta.geometries, this.geometry );
  11050. const parameters = this.geometry.parameters;
  11051. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11052. const shapes = parameters.shapes;
  11053. if ( Array.isArray( shapes ) ) {
  11054. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11055. const shape = shapes[ i ];
  11056. serialize( meta.shapes, shape );
  11057. }
  11058. } else {
  11059. serialize( meta.shapes, shapes );
  11060. }
  11061. }
  11062. }
  11063. if ( this.isSkinnedMesh ) {
  11064. object.bindMode = this.bindMode;
  11065. object.bindMatrix = this.bindMatrix.toArray();
  11066. if ( this.skeleton !== undefined ) {
  11067. serialize( meta.skeletons, this.skeleton );
  11068. object.skeleton = this.skeleton.uuid;
  11069. }
  11070. }
  11071. if ( this.material !== undefined ) {
  11072. if ( Array.isArray( this.material ) ) {
  11073. const uuids = [];
  11074. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11075. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11076. }
  11077. object.material = uuids;
  11078. } else {
  11079. object.material = serialize( meta.materials, this.material );
  11080. }
  11081. }
  11082. //
  11083. if ( this.children.length > 0 ) {
  11084. object.children = [];
  11085. for ( let i = 0; i < this.children.length; i ++ ) {
  11086. object.children.push( this.children[ i ].toJSON( meta ).object );
  11087. }
  11088. }
  11089. //
  11090. if ( this.animations.length > 0 ) {
  11091. object.animations = [];
  11092. for ( let i = 0; i < this.animations.length; i ++ ) {
  11093. const animation = this.animations[ i ];
  11094. object.animations.push( serialize( meta.animations, animation ) );
  11095. }
  11096. }
  11097. if ( isRootObject ) {
  11098. const geometries = extractFromCache( meta.geometries );
  11099. const materials = extractFromCache( meta.materials );
  11100. const textures = extractFromCache( meta.textures );
  11101. const images = extractFromCache( meta.images );
  11102. const shapes = extractFromCache( meta.shapes );
  11103. const skeletons = extractFromCache( meta.skeletons );
  11104. const animations = extractFromCache( meta.animations );
  11105. const nodes = extractFromCache( meta.nodes );
  11106. if ( geometries.length > 0 ) output.geometries = geometries;
  11107. if ( materials.length > 0 ) output.materials = materials;
  11108. if ( textures.length > 0 ) output.textures = textures;
  11109. if ( images.length > 0 ) output.images = images;
  11110. if ( shapes.length > 0 ) output.shapes = shapes;
  11111. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11112. if ( animations.length > 0 ) output.animations = animations;
  11113. if ( nodes.length > 0 ) output.nodes = nodes;
  11114. }
  11115. output.object = object;
  11116. return output;
  11117. // extract data from the cache hash
  11118. // remove metadata on each item
  11119. // and return as array
  11120. function extractFromCache( cache ) {
  11121. const values = [];
  11122. for ( const key in cache ) {
  11123. const data = cache[ key ];
  11124. delete data.metadata;
  11125. values.push( data );
  11126. }
  11127. return values;
  11128. }
  11129. }
  11130. /**
  11131. * Returns a new 3D object with copied values from this instance.
  11132. *
  11133. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11134. * @return {Object3D} A clone of this instance.
  11135. */
  11136. clone( recursive ) {
  11137. return new this.constructor().copy( this, recursive );
  11138. }
  11139. /**
  11140. * Copies the values of the given 3D object to this instance.
  11141. *
  11142. * @param {Object3D} source - The 3D object to copy.
  11143. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11144. * @return {Object3D} A reference to this instance.
  11145. */
  11146. copy( source, recursive = true ) {
  11147. this.name = source.name;
  11148. this.up.copy( source.up );
  11149. this.position.copy( source.position );
  11150. this.rotation.order = source.rotation.order;
  11151. this.quaternion.copy( source.quaternion );
  11152. this.scale.copy( source.scale );
  11153. this.matrix.copy( source.matrix );
  11154. this.matrixWorld.copy( source.matrixWorld );
  11155. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11156. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11157. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11158. this.layers.mask = source.layers.mask;
  11159. this.visible = source.visible;
  11160. this.castShadow = source.castShadow;
  11161. this.receiveShadow = source.receiveShadow;
  11162. this.frustumCulled = source.frustumCulled;
  11163. this.renderOrder = source.renderOrder;
  11164. this.animations = source.animations.slice();
  11165. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11166. if ( recursive === true ) {
  11167. for ( let i = 0; i < source.children.length; i ++ ) {
  11168. const child = source.children[ i ];
  11169. this.add( child.clone() );
  11170. }
  11171. }
  11172. return this;
  11173. }
  11174. }
  11175. /**
  11176. * The default up direction for objects, also used as the default
  11177. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11178. *
  11179. * @static
  11180. * @type {Vector3}
  11181. * @default (0,1,0)
  11182. */
  11183. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11184. /**
  11185. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11186. * newly created 3D objects.
  11187. *
  11188. * @static
  11189. * @type {boolean}
  11190. * @default true
  11191. */
  11192. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11193. /**
  11194. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11195. * newly created 3D objects.
  11196. *
  11197. * @static
  11198. * @type {boolean}
  11199. * @default true
  11200. */
  11201. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11202. const _v0$2 = /*@__PURE__*/ new Vector3();
  11203. const _v1$3 = /*@__PURE__*/ new Vector3();
  11204. const _v2$2 = /*@__PURE__*/ new Vector3();
  11205. const _v3$2 = /*@__PURE__*/ new Vector3();
  11206. const _vab = /*@__PURE__*/ new Vector3();
  11207. const _vac = /*@__PURE__*/ new Vector3();
  11208. const _vbc = /*@__PURE__*/ new Vector3();
  11209. const _vap = /*@__PURE__*/ new Vector3();
  11210. const _vbp = /*@__PURE__*/ new Vector3();
  11211. const _vcp = /*@__PURE__*/ new Vector3();
  11212. const _v40 = /*@__PURE__*/ new Vector4();
  11213. const _v41 = /*@__PURE__*/ new Vector4();
  11214. const _v42 = /*@__PURE__*/ new Vector4();
  11215. /**
  11216. * A geometric triangle as defined by three vectors representing its three corners.
  11217. */
  11218. class Triangle {
  11219. /**
  11220. * Constructs a new triangle.
  11221. *
  11222. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11223. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11224. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11225. */
  11226. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11227. /**
  11228. * The first corner of the triangle.
  11229. *
  11230. * @type {Vector3}
  11231. */
  11232. this.a = a;
  11233. /**
  11234. * The second corner of the triangle.
  11235. *
  11236. * @type {Vector3}
  11237. */
  11238. this.b = b;
  11239. /**
  11240. * The third corner of the triangle.
  11241. *
  11242. * @type {Vector3}
  11243. */
  11244. this.c = c;
  11245. }
  11246. /**
  11247. * Computes the normal vector of a triangle.
  11248. *
  11249. * @param {Vector3} a - The first corner of the triangle.
  11250. * @param {Vector3} b - The second corner of the triangle.
  11251. * @param {Vector3} c - The third corner of the triangle.
  11252. * @param {Vector3} target - The target vector that is used to store the method's result.
  11253. * @return {Vector3} The triangle's normal.
  11254. */
  11255. static getNormal( a, b, c, target ) {
  11256. target.subVectors( c, b );
  11257. _v0$2.subVectors( a, b );
  11258. target.cross( _v0$2 );
  11259. const targetLengthSq = target.lengthSq();
  11260. if ( targetLengthSq > 0 ) {
  11261. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11262. }
  11263. return target.set( 0, 0, 0 );
  11264. }
  11265. /**
  11266. * Computes a barycentric coordinates from the given vector.
  11267. * Returns `null` if the triangle is degenerate.
  11268. *
  11269. * @param {Vector3} point - A point in 3D space.
  11270. * @param {Vector3} a - The first corner of the triangle.
  11271. * @param {Vector3} b - The second corner of the triangle.
  11272. * @param {Vector3} c - The third corner of the triangle.
  11273. * @param {Vector3} target - The target vector that is used to store the method's result.
  11274. * @return {?Vector3} The barycentric coordinates for the given point
  11275. */
  11276. static getBarycoord( point, a, b, c, target ) {
  11277. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11278. _v0$2.subVectors( c, a );
  11279. _v1$3.subVectors( b, a );
  11280. _v2$2.subVectors( point, a );
  11281. const dot00 = _v0$2.dot( _v0$2 );
  11282. const dot01 = _v0$2.dot( _v1$3 );
  11283. const dot02 = _v0$2.dot( _v2$2 );
  11284. const dot11 = _v1$3.dot( _v1$3 );
  11285. const dot12 = _v1$3.dot( _v2$2 );
  11286. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11287. // collinear or singular triangle
  11288. if ( denom === 0 ) {
  11289. target.set( 0, 0, 0 );
  11290. return null;
  11291. }
  11292. const invDenom = 1 / denom;
  11293. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11294. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11295. // barycentric coordinates must always sum to 1
  11296. return target.set( 1 - u - v, v, u );
  11297. }
  11298. /**
  11299. * Returns `true` if the given point, when projected onto the plane of the
  11300. * triangle, lies within the triangle.
  11301. *
  11302. * @param {Vector3} point - The point in 3D space to test.
  11303. * @param {Vector3} a - The first corner of the triangle.
  11304. * @param {Vector3} b - The second corner of the triangle.
  11305. * @param {Vector3} c - The third corner of the triangle.
  11306. * @return {boolean} Whether the given point, when projected onto the plane of the
  11307. * triangle, lies within the triangle or not.
  11308. */
  11309. static containsPoint( point, a, b, c ) {
  11310. // if the triangle is degenerate then we can't contain a point
  11311. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11312. return false;
  11313. }
  11314. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11315. }
  11316. /**
  11317. * Computes the value barycentrically interpolated for the given point on the
  11318. * triangle. Returns `null` if the triangle is degenerate.
  11319. *
  11320. * @param {Vector3} point - Position of interpolated point.
  11321. * @param {Vector3} p1 - The first corner of the triangle.
  11322. * @param {Vector3} p2 - The second corner of the triangle.
  11323. * @param {Vector3} p3 - The third corner of the triangle.
  11324. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11325. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11326. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11327. * @param {Vector3} target - The target vector that is used to store the method's result.
  11328. * @return {?Vector3} The interpolated value.
  11329. */
  11330. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11331. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11332. target.x = 0;
  11333. target.y = 0;
  11334. if ( 'z' in target ) target.z = 0;
  11335. if ( 'w' in target ) target.w = 0;
  11336. return null;
  11337. }
  11338. target.setScalar( 0 );
  11339. target.addScaledVector( v1, _v3$2.x );
  11340. target.addScaledVector( v2, _v3$2.y );
  11341. target.addScaledVector( v3, _v3$2.z );
  11342. return target;
  11343. }
  11344. /**
  11345. * Computes the value barycentrically interpolated for the given attribute and indices.
  11346. *
  11347. * @param {BufferAttribute} attr - The attribute to interpolate.
  11348. * @param {number} i1 - Index of first vertex.
  11349. * @param {number} i2 - Index of second vertex.
  11350. * @param {number} i3 - Index of third vertex.
  11351. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11352. * @param {Vector3} target - The target vector that is used to store the method's result.
  11353. * @return {Vector3} The interpolated attribute value.
  11354. */
  11355. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11356. _v40.setScalar( 0 );
  11357. _v41.setScalar( 0 );
  11358. _v42.setScalar( 0 );
  11359. _v40.fromBufferAttribute( attr, i1 );
  11360. _v41.fromBufferAttribute( attr, i2 );
  11361. _v42.fromBufferAttribute( attr, i3 );
  11362. target.setScalar( 0 );
  11363. target.addScaledVector( _v40, barycoord.x );
  11364. target.addScaledVector( _v41, barycoord.y );
  11365. target.addScaledVector( _v42, barycoord.z );
  11366. return target;
  11367. }
  11368. /**
  11369. * Returns `true` if the triangle is oriented towards the given direction.
  11370. *
  11371. * @param {Vector3} a - The first corner of the triangle.
  11372. * @param {Vector3} b - The second corner of the triangle.
  11373. * @param {Vector3} c - The third corner of the triangle.
  11374. * @param {Vector3} direction - The (normalized) direction vector.
  11375. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11376. */
  11377. static isFrontFacing( a, b, c, direction ) {
  11378. _v0$2.subVectors( c, b );
  11379. _v1$3.subVectors( a, b );
  11380. // strictly front facing
  11381. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11382. }
  11383. /**
  11384. * Sets the triangle's vertices by copying the given values.
  11385. *
  11386. * @param {Vector3} a - The first corner of the triangle.
  11387. * @param {Vector3} b - The second corner of the triangle.
  11388. * @param {Vector3} c - The third corner of the triangle.
  11389. * @return {Triangle} A reference to this triangle.
  11390. */
  11391. set( a, b, c ) {
  11392. this.a.copy( a );
  11393. this.b.copy( b );
  11394. this.c.copy( c );
  11395. return this;
  11396. }
  11397. /**
  11398. * Sets the triangle's vertices by copying the given array values.
  11399. *
  11400. * @param {Array<Vector3>} points - An array with 3D points.
  11401. * @param {number} i0 - The array index representing the first corner of the triangle.
  11402. * @param {number} i1 - The array index representing the second corner of the triangle.
  11403. * @param {number} i2 - The array index representing the third corner of the triangle.
  11404. * @return {Triangle} A reference to this triangle.
  11405. */
  11406. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11407. this.a.copy( points[ i0 ] );
  11408. this.b.copy( points[ i1 ] );
  11409. this.c.copy( points[ i2 ] );
  11410. return this;
  11411. }
  11412. /**
  11413. * Sets the triangle's vertices by copying the given attribute values.
  11414. *
  11415. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11416. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11417. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11418. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11419. * @return {Triangle} A reference to this triangle.
  11420. */
  11421. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11422. this.a.fromBufferAttribute( attribute, i0 );
  11423. this.b.fromBufferAttribute( attribute, i1 );
  11424. this.c.fromBufferAttribute( attribute, i2 );
  11425. return this;
  11426. }
  11427. /**
  11428. * Returns a new triangle with copied values from this instance.
  11429. *
  11430. * @return {Triangle} A clone of this instance.
  11431. */
  11432. clone() {
  11433. return new this.constructor().copy( this );
  11434. }
  11435. /**
  11436. * Copies the values of the given triangle to this instance.
  11437. *
  11438. * @param {Triangle} triangle - The triangle to copy.
  11439. * @return {Triangle} A reference to this triangle.
  11440. */
  11441. copy( triangle ) {
  11442. this.a.copy( triangle.a );
  11443. this.b.copy( triangle.b );
  11444. this.c.copy( triangle.c );
  11445. return this;
  11446. }
  11447. /**
  11448. * Computes the area of the triangle.
  11449. *
  11450. * @return {number} The triangle's area.
  11451. */
  11452. getArea() {
  11453. _v0$2.subVectors( this.c, this.b );
  11454. _v1$3.subVectors( this.a, this.b );
  11455. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11456. }
  11457. /**
  11458. * Computes the midpoint of the triangle.
  11459. *
  11460. * @param {Vector3} target - The target vector that is used to store the method's result.
  11461. * @return {Vector3} The triangle's midpoint.
  11462. */
  11463. getMidpoint( target ) {
  11464. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11465. }
  11466. /**
  11467. * Computes the normal of the triangle.
  11468. *
  11469. * @param {Vector3} target - The target vector that is used to store the method's result.
  11470. * @return {Vector3} The triangle's normal.
  11471. */
  11472. getNormal( target ) {
  11473. return Triangle.getNormal( this.a, this.b, this.c, target );
  11474. }
  11475. /**
  11476. * Computes a plane the triangle lies within.
  11477. *
  11478. * @param {Plane} target - The target vector that is used to store the method's result.
  11479. * @return {Plane} The plane the triangle lies within.
  11480. */
  11481. getPlane( target ) {
  11482. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11483. }
  11484. /**
  11485. * Computes a barycentric coordinates from the given vector.
  11486. * Returns `null` if the triangle is degenerate.
  11487. *
  11488. * @param {Vector3} point - A point in 3D space.
  11489. * @param {Vector3} target - The target vector that is used to store the method's result.
  11490. * @return {?Vector3} The barycentric coordinates for the given point
  11491. */
  11492. getBarycoord( point, target ) {
  11493. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11494. }
  11495. /**
  11496. * Computes the value barycentrically interpolated for the given point on the
  11497. * triangle. Returns `null` if the triangle is degenerate.
  11498. *
  11499. * @param {Vector3} point - Position of interpolated point.
  11500. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11501. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11502. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11503. * @param {Vector3} target - The target vector that is used to store the method's result.
  11504. * @return {?Vector3} The interpolated value.
  11505. */
  11506. getInterpolation( point, v1, v2, v3, target ) {
  11507. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11508. }
  11509. /**
  11510. * Returns `true` if the given point, when projected onto the plane of the
  11511. * triangle, lies within the triangle.
  11512. *
  11513. * @param {Vector3} point - The point in 3D space to test.
  11514. * @return {boolean} Whether the given point, when projected onto the plane of the
  11515. * triangle, lies within the triangle or not.
  11516. */
  11517. containsPoint( point ) {
  11518. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11519. }
  11520. /**
  11521. * Returns `true` if the triangle is oriented towards the given direction.
  11522. *
  11523. * @param {Vector3} direction - The (normalized) direction vector.
  11524. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11525. */
  11526. isFrontFacing( direction ) {
  11527. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11528. }
  11529. /**
  11530. * Returns `true` if this triangle intersects with the given box.
  11531. *
  11532. * @param {Box3} box - The box to intersect.
  11533. * @return {boolean} Whether this triangle intersects with the given box or not.
  11534. */
  11535. intersectsBox( box ) {
  11536. return box.intersectsTriangle( this );
  11537. }
  11538. /**
  11539. * Returns the closest point on the triangle to the given point.
  11540. *
  11541. * @param {Vector3} p - The point to compute the closest point for.
  11542. * @param {Vector3} target - The target vector that is used to store the method's result.
  11543. * @return {Vector3} The closest point on the triangle.
  11544. */
  11545. closestPointToPoint( p, target ) {
  11546. const a = this.a, b = this.b, c = this.c;
  11547. let v, w;
  11548. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11549. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11550. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11551. // basically, we're distinguishing which of the voronoi regions of the triangle
  11552. // the point lies in with the minimum amount of redundant computation.
  11553. _vab.subVectors( b, a );
  11554. _vac.subVectors( c, a );
  11555. _vap.subVectors( p, a );
  11556. const d1 = _vab.dot( _vap );
  11557. const d2 = _vac.dot( _vap );
  11558. if ( d1 <= 0 && d2 <= 0 ) {
  11559. // vertex region of A; barycentric coords (1, 0, 0)
  11560. return target.copy( a );
  11561. }
  11562. _vbp.subVectors( p, b );
  11563. const d3 = _vab.dot( _vbp );
  11564. const d4 = _vac.dot( _vbp );
  11565. if ( d3 >= 0 && d4 <= d3 ) {
  11566. // vertex region of B; barycentric coords (0, 1, 0)
  11567. return target.copy( b );
  11568. }
  11569. const vc = d1 * d4 - d3 * d2;
  11570. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11571. v = d1 / ( d1 - d3 );
  11572. // edge region of AB; barycentric coords (1-v, v, 0)
  11573. return target.copy( a ).addScaledVector( _vab, v );
  11574. }
  11575. _vcp.subVectors( p, c );
  11576. const d5 = _vab.dot( _vcp );
  11577. const d6 = _vac.dot( _vcp );
  11578. if ( d6 >= 0 && d5 <= d6 ) {
  11579. // vertex region of C; barycentric coords (0, 0, 1)
  11580. return target.copy( c );
  11581. }
  11582. const vb = d5 * d2 - d1 * d6;
  11583. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11584. w = d2 / ( d2 - d6 );
  11585. // edge region of AC; barycentric coords (1-w, 0, w)
  11586. return target.copy( a ).addScaledVector( _vac, w );
  11587. }
  11588. const va = d3 * d6 - d5 * d4;
  11589. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11590. _vbc.subVectors( c, b );
  11591. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11592. // edge region of BC; barycentric coords (0, 1-w, w)
  11593. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11594. }
  11595. // face region
  11596. const denom = 1 / ( va + vb + vc );
  11597. // u = va * denom
  11598. v = vb * denom;
  11599. w = vc * denom;
  11600. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11601. }
  11602. /**
  11603. * Returns `true` if this triangle is equal with the given one.
  11604. *
  11605. * @param {Triangle} triangle - The triangle to test for equality.
  11606. * @return {boolean} Whether this triangle is equal with the given one.
  11607. */
  11608. equals( triangle ) {
  11609. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11610. }
  11611. }
  11612. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11613. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11614. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11615. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11616. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11617. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11618. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11619. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11620. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11621. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11622. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11623. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11624. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11625. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11626. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11627. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11628. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11629. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11630. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11631. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11632. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11633. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11634. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11635. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11636. const _hslA = { h: 0, s: 0, l: 0 };
  11637. const _hslB = { h: 0, s: 0, l: 0 };
  11638. function hue2rgb( p, q, t ) {
  11639. if ( t < 0 ) t += 1;
  11640. if ( t > 1 ) t -= 1;
  11641. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11642. if ( t < 1 / 2 ) return q;
  11643. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11644. return p;
  11645. }
  11646. /**
  11647. * A Color instance is represented by RGB components in the linear <i>working
  11648. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11649. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11650. * strings) are converted to the working color space automatically.
  11651. *
  11652. * ```js
  11653. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11654. * const color = new THREE.Color().setHex( 0x112233 );
  11655. * ```
  11656. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11657. * ```js
  11658. * // assumed already LinearSRGBColorSpace; no conversion
  11659. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11660. *
  11661. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11662. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11663. * ```
  11664. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11665. * see <i>Color management</i>. Iterating through a Color instance will yield
  11666. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11667. * in any of the following ways:
  11668. * ```js
  11669. * //empty constructor - will default white
  11670. * const color1 = new THREE.Color();
  11671. *
  11672. * //Hexadecimal color (recommended)
  11673. * const color2 = new THREE.Color( 0xff0000 );
  11674. *
  11675. * //RGB string
  11676. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11677. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11678. *
  11679. * //X11 color name - all 140 color names are supported.
  11680. * //Note the lack of CamelCase in the name
  11681. * const color5 = new THREE.Color( 'skyblue' );
  11682. * //HSL string
  11683. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11684. *
  11685. * //Separate RGB values between 0 and 1
  11686. * const color7 = new THREE.Color( 1, 0, 0 );
  11687. * ```
  11688. */
  11689. class Color {
  11690. /**
  11691. * Constructs a new color.
  11692. *
  11693. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11694. * and that method is used throughout the rest of the documentation.
  11695. *
  11696. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11697. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11698. * @param {number} [g] - The green component.
  11699. * @param {number} [b] - The blue component.
  11700. */
  11701. constructor( r, g, b ) {
  11702. /**
  11703. * This flag can be used for type testing.
  11704. *
  11705. * @type {boolean}
  11706. * @readonly
  11707. * @default true
  11708. */
  11709. this.isColor = true;
  11710. /**
  11711. * The red component.
  11712. *
  11713. * @type {number}
  11714. * @default 1
  11715. */
  11716. this.r = 1;
  11717. /**
  11718. * The green component.
  11719. *
  11720. * @type {number}
  11721. * @default 1
  11722. */
  11723. this.g = 1;
  11724. /**
  11725. * The blue component.
  11726. *
  11727. * @type {number}
  11728. * @default 1
  11729. */
  11730. this.b = 1;
  11731. return this.set( r, g, b );
  11732. }
  11733. /**
  11734. * Sets the colors's components from the given values.
  11735. *
  11736. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11737. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11738. * @param {number} [g] - The green component.
  11739. * @param {number} [b] - The blue component.
  11740. * @return {Color} A reference to this color.
  11741. */
  11742. set( r, g, b ) {
  11743. if ( g === undefined && b === undefined ) {
  11744. // r is THREE.Color, hex or string
  11745. const value = r;
  11746. if ( value && value.isColor ) {
  11747. this.copy( value );
  11748. } else if ( typeof value === 'number' ) {
  11749. this.setHex( value );
  11750. } else if ( typeof value === 'string' ) {
  11751. this.setStyle( value );
  11752. }
  11753. } else {
  11754. this.setRGB( r, g, b );
  11755. }
  11756. return this;
  11757. }
  11758. /**
  11759. * Sets the colors's components to the given scalar value.
  11760. *
  11761. * @param {number} scalar - The scalar value.
  11762. * @return {Color} A reference to this color.
  11763. */
  11764. setScalar( scalar ) {
  11765. this.r = scalar;
  11766. this.g = scalar;
  11767. this.b = scalar;
  11768. return this;
  11769. }
  11770. /**
  11771. * Sets this color from a hexadecimal value.
  11772. *
  11773. * @param {number} hex - The hexadecimal value.
  11774. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11775. * @return {Color} A reference to this color.
  11776. */
  11777. setHex( hex, colorSpace = SRGBColorSpace ) {
  11778. hex = Math.floor( hex );
  11779. this.r = ( hex >> 16 & 255 ) / 255;
  11780. this.g = ( hex >> 8 & 255 ) / 255;
  11781. this.b = ( hex & 255 ) / 255;
  11782. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11783. return this;
  11784. }
  11785. /**
  11786. * Sets this color from RGB values.
  11787. *
  11788. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11789. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11790. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11791. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11792. * @return {Color} A reference to this color.
  11793. */
  11794. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11795. this.r = r;
  11796. this.g = g;
  11797. this.b = b;
  11798. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11799. return this;
  11800. }
  11801. /**
  11802. * Sets this color from RGB values.
  11803. *
  11804. * @param {number} h - Hue value between `0.0` and `1.0`.
  11805. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11806. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11807. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11808. * @return {Color} A reference to this color.
  11809. */
  11810. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11811. // h,s,l ranges are in 0.0 - 1.0
  11812. h = euclideanModulo( h, 1 );
  11813. s = clamp( s, 0, 1 );
  11814. l = clamp( l, 0, 1 );
  11815. if ( s === 0 ) {
  11816. this.r = this.g = this.b = l;
  11817. } else {
  11818. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11819. const q = ( 2 * l ) - p;
  11820. this.r = hue2rgb( q, p, h + 1 / 3 );
  11821. this.g = hue2rgb( q, p, h );
  11822. this.b = hue2rgb( q, p, h - 1 / 3 );
  11823. }
  11824. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11825. return this;
  11826. }
  11827. /**
  11828. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11829. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11830. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  11831. * all 140 color names are supported).
  11832. *
  11833. * @param {string} style - Color as a CSS-style string.
  11834. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11835. * @return {Color} A reference to this color.
  11836. */
  11837. setStyle( style, colorSpace = SRGBColorSpace ) {
  11838. function handleAlpha( string ) {
  11839. if ( string === undefined ) return;
  11840. if ( parseFloat( string ) < 1 ) {
  11841. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  11842. }
  11843. }
  11844. let m;
  11845. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11846. // rgb / hsl
  11847. let color;
  11848. const name = m[ 1 ];
  11849. const components = m[ 2 ];
  11850. switch ( name ) {
  11851. case 'rgb':
  11852. case 'rgba':
  11853. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11854. // rgb(255,0,0) rgba(255,0,0,0.5)
  11855. handleAlpha( color[ 4 ] );
  11856. return this.setRGB(
  11857. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11858. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11859. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11860. colorSpace
  11861. );
  11862. }
  11863. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11864. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11865. handleAlpha( color[ 4 ] );
  11866. return this.setRGB(
  11867. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11868. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11869. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11870. colorSpace
  11871. );
  11872. }
  11873. break;
  11874. case 'hsl':
  11875. case 'hsla':
  11876. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11877. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11878. handleAlpha( color[ 4 ] );
  11879. return this.setHSL(
  11880. parseFloat( color[ 1 ] ) / 360,
  11881. parseFloat( color[ 2 ] ) / 100,
  11882. parseFloat( color[ 3 ] ) / 100,
  11883. colorSpace
  11884. );
  11885. }
  11886. break;
  11887. default:
  11888. warn( 'Color: Unknown color model ' + style );
  11889. }
  11890. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11891. // hex color
  11892. const hex = m[ 1 ];
  11893. const size = hex.length;
  11894. if ( size === 3 ) {
  11895. // #ff0
  11896. return this.setRGB(
  11897. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11898. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11899. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11900. colorSpace
  11901. );
  11902. } else if ( size === 6 ) {
  11903. // #ff0000
  11904. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11905. } else {
  11906. warn( 'Color: Invalid hex color ' + style );
  11907. }
  11908. } else if ( style && style.length > 0 ) {
  11909. return this.setColorName( style, colorSpace );
  11910. }
  11911. return this;
  11912. }
  11913. /**
  11914. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11915. * you don't need the other CSS-style formats.
  11916. *
  11917. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11918. * ```js
  11919. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11920. * ```
  11921. *
  11922. * @param {string} style - The color name.
  11923. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11924. * @return {Color} A reference to this color.
  11925. */
  11926. setColorName( style, colorSpace = SRGBColorSpace ) {
  11927. // color keywords
  11928. const hex = _colorKeywords[ style.toLowerCase() ];
  11929. if ( hex !== undefined ) {
  11930. // red
  11931. this.setHex( hex, colorSpace );
  11932. } else {
  11933. // unknown color
  11934. warn( 'Color: Unknown color ' + style );
  11935. }
  11936. return this;
  11937. }
  11938. /**
  11939. * Returns a new color with copied values from this instance.
  11940. *
  11941. * @return {Color} A clone of this instance.
  11942. */
  11943. clone() {
  11944. return new this.constructor( this.r, this.g, this.b );
  11945. }
  11946. /**
  11947. * Copies the values of the given color to this instance.
  11948. *
  11949. * @param {Color} color - The color to copy.
  11950. * @return {Color} A reference to this color.
  11951. */
  11952. copy( color ) {
  11953. this.r = color.r;
  11954. this.g = color.g;
  11955. this.b = color.b;
  11956. return this;
  11957. }
  11958. /**
  11959. * Copies the given color into this color, and then converts this color from
  11960. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11961. *
  11962. * @param {Color} color - The color to copy/convert.
  11963. * @return {Color} A reference to this color.
  11964. */
  11965. copySRGBToLinear( color ) {
  11966. this.r = SRGBToLinear( color.r );
  11967. this.g = SRGBToLinear( color.g );
  11968. this.b = SRGBToLinear( color.b );
  11969. return this;
  11970. }
  11971. /**
  11972. * Copies the given color into this color, and then converts this color from
  11973. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11974. *
  11975. * @param {Color} color - The color to copy/convert.
  11976. * @return {Color} A reference to this color.
  11977. */
  11978. copyLinearToSRGB( color ) {
  11979. this.r = LinearToSRGB( color.r );
  11980. this.g = LinearToSRGB( color.g );
  11981. this.b = LinearToSRGB( color.b );
  11982. return this;
  11983. }
  11984. /**
  11985. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11986. *
  11987. * @return {Color} A reference to this color.
  11988. */
  11989. convertSRGBToLinear() {
  11990. this.copySRGBToLinear( this );
  11991. return this;
  11992. }
  11993. /**
  11994. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11995. *
  11996. * @return {Color} A reference to this color.
  11997. */
  11998. convertLinearToSRGB() {
  11999. this.copyLinearToSRGB( this );
  12000. return this;
  12001. }
  12002. /**
  12003. * Returns the hexadecimal value of this color.
  12004. *
  12005. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12006. * @return {number} The hexadecimal value.
  12007. */
  12008. getHex( colorSpace = SRGBColorSpace ) {
  12009. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12010. return Math.round( clamp( _color.r * 255, 0, 255 ) ) * 65536 + Math.round( clamp( _color.g * 255, 0, 255 ) ) * 256 + Math.round( clamp( _color.b * 255, 0, 255 ) );
  12011. }
  12012. /**
  12013. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12014. *
  12015. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12016. * @return {string} The hexadecimal value as a string.
  12017. */
  12018. getHexString( colorSpace = SRGBColorSpace ) {
  12019. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12020. }
  12021. /**
  12022. * Converts the colors RGB values into the HSL format and stores them into the
  12023. * given target object.
  12024. *
  12025. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12026. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12027. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12028. */
  12029. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12030. // h,s,l ranges are in 0.0 - 1.0
  12031. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12032. const r = _color.r, g = _color.g, b = _color.b;
  12033. const max = Math.max( r, g, b );
  12034. const min = Math.min( r, g, b );
  12035. let hue, saturation;
  12036. const lightness = ( min + max ) / 2.0;
  12037. if ( min === max ) {
  12038. hue = 0;
  12039. saturation = 0;
  12040. } else {
  12041. const delta = max - min;
  12042. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12043. switch ( max ) {
  12044. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12045. case g: hue = ( b - r ) / delta + 2; break;
  12046. case b: hue = ( r - g ) / delta + 4; break;
  12047. }
  12048. hue /= 6;
  12049. }
  12050. target.h = hue;
  12051. target.s = saturation;
  12052. target.l = lightness;
  12053. return target;
  12054. }
  12055. /**
  12056. * Returns the RGB values of this color and stores them into the given target object.
  12057. *
  12058. * @param {Color} target - The target color that is used to store the method's result.
  12059. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12060. * @return {Color} The RGB representation of this color.
  12061. */
  12062. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12063. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12064. target.r = _color.r;
  12065. target.g = _color.g;
  12066. target.b = _color.b;
  12067. return target;
  12068. }
  12069. /**
  12070. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12071. *
  12072. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12073. * @return {string} The CSS representation of this color.
  12074. */
  12075. getStyle( colorSpace = SRGBColorSpace ) {
  12076. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12077. const r = _color.r, g = _color.g, b = _color.b;
  12078. if ( colorSpace !== SRGBColorSpace ) {
  12079. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12080. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12081. }
  12082. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12083. }
  12084. /**
  12085. * Adds the given HSL values to this color's values.
  12086. * Internally, this converts the color's RGB values to HSL, adds HSL
  12087. * and then converts the color back to RGB.
  12088. *
  12089. * @param {number} h - Hue value between `0.0` and `1.0`.
  12090. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12091. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12092. * @return {Color} A reference to this color.
  12093. */
  12094. offsetHSL( h, s, l ) {
  12095. this.getHSL( _hslA );
  12096. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12097. }
  12098. /**
  12099. * Adds the RGB values of the given color to the RGB values of this color.
  12100. *
  12101. * @param {Color} color - The color to add.
  12102. * @return {Color} A reference to this color.
  12103. */
  12104. add( color ) {
  12105. this.r += color.r;
  12106. this.g += color.g;
  12107. this.b += color.b;
  12108. return this;
  12109. }
  12110. /**
  12111. * Adds the RGB values of the given colors and stores the result in this instance.
  12112. *
  12113. * @param {Color} color1 - The first color.
  12114. * @param {Color} color2 - The second color.
  12115. * @return {Color} A reference to this color.
  12116. */
  12117. addColors( color1, color2 ) {
  12118. this.r = color1.r + color2.r;
  12119. this.g = color1.g + color2.g;
  12120. this.b = color1.b + color2.b;
  12121. return this;
  12122. }
  12123. /**
  12124. * Adds the given scalar value to the RGB values of this color.
  12125. *
  12126. * @param {number} s - The scalar to add.
  12127. * @return {Color} A reference to this color.
  12128. */
  12129. addScalar( s ) {
  12130. this.r += s;
  12131. this.g += s;
  12132. this.b += s;
  12133. return this;
  12134. }
  12135. /**
  12136. * Subtracts the RGB values of the given color from the RGB values of this color.
  12137. *
  12138. * @param {Color} color - The color to subtract.
  12139. * @return {Color} A reference to this color.
  12140. */
  12141. sub( color ) {
  12142. this.r = Math.max( 0, this.r - color.r );
  12143. this.g = Math.max( 0, this.g - color.g );
  12144. this.b = Math.max( 0, this.b - color.b );
  12145. return this;
  12146. }
  12147. /**
  12148. * Multiplies the RGB values of the given color with the RGB values of this color.
  12149. *
  12150. * @param {Color} color - The color to multiply.
  12151. * @return {Color} A reference to this color.
  12152. */
  12153. multiply( color ) {
  12154. this.r *= color.r;
  12155. this.g *= color.g;
  12156. this.b *= color.b;
  12157. return this;
  12158. }
  12159. /**
  12160. * Multiplies the given scalar value with the RGB values of this color.
  12161. *
  12162. * @param {number} s - The scalar to multiply.
  12163. * @return {Color} A reference to this color.
  12164. */
  12165. multiplyScalar( s ) {
  12166. this.r *= s;
  12167. this.g *= s;
  12168. this.b *= s;
  12169. return this;
  12170. }
  12171. /**
  12172. * Linearly interpolates this color's RGB values toward the RGB values of the
  12173. * given color. The alpha argument can be thought of as the ratio between
  12174. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12175. *
  12176. * @param {Color} color - The color to converge on.
  12177. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12178. * @return {Color} A reference to this color.
  12179. */
  12180. lerp( color, alpha ) {
  12181. this.r += ( color.r - this.r ) * alpha;
  12182. this.g += ( color.g - this.g ) * alpha;
  12183. this.b += ( color.b - this.b ) * alpha;
  12184. return this;
  12185. }
  12186. /**
  12187. * Linearly interpolates between the given colors and stores the result in this instance.
  12188. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12189. * is the first and `1.0` is the second color.
  12190. *
  12191. * @param {Color} color1 - The first color.
  12192. * @param {Color} color2 - The second color.
  12193. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12194. * @return {Color} A reference to this color.
  12195. */
  12196. lerpColors( color1, color2, alpha ) {
  12197. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12198. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12199. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12200. return this;
  12201. }
  12202. /**
  12203. * Linearly interpolates this color's HSL values toward the HSL values of the
  12204. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12205. * from one color to the other, but instead going through all the hues in between
  12206. * those two colors. The alpha argument can be thought of as the ratio between
  12207. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12208. *
  12209. * @param {Color} color - The color to converge on.
  12210. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12211. * @return {Color} A reference to this color.
  12212. */
  12213. lerpHSL( color, alpha ) {
  12214. this.getHSL( _hslA );
  12215. color.getHSL( _hslB );
  12216. const h = lerp( _hslA.h, _hslB.h, alpha );
  12217. const s = lerp( _hslA.s, _hslB.s, alpha );
  12218. const l = lerp( _hslA.l, _hslB.l, alpha );
  12219. this.setHSL( h, s, l );
  12220. return this;
  12221. }
  12222. /**
  12223. * Sets the color's RGB components from the given 3D vector.
  12224. *
  12225. * @param {Vector3} v - The vector to set.
  12226. * @return {Color} A reference to this color.
  12227. */
  12228. setFromVector3( v ) {
  12229. this.r = v.x;
  12230. this.g = v.y;
  12231. this.b = v.z;
  12232. return this;
  12233. }
  12234. /**
  12235. * Transforms this color with the given 3x3 matrix.
  12236. *
  12237. * @param {Matrix3} m - The matrix.
  12238. * @return {Color} A reference to this color.
  12239. */
  12240. applyMatrix3( m ) {
  12241. const r = this.r, g = this.g, b = this.b;
  12242. const e = m.elements;
  12243. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12244. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12245. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12246. return this;
  12247. }
  12248. /**
  12249. * Returns `true` if this color is equal with the given one.
  12250. *
  12251. * @param {Color} c - The color to test for equality.
  12252. * @return {boolean} Whether this bounding color is equal with the given one.
  12253. */
  12254. equals( c ) {
  12255. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12256. }
  12257. /**
  12258. * Sets this color's RGB components from the given array.
  12259. *
  12260. * @param {Array<number>} array - An array holding the RGB values.
  12261. * @param {number} [offset=0] - The offset into the array.
  12262. * @return {Color} A reference to this color.
  12263. */
  12264. fromArray( array, offset = 0 ) {
  12265. this.r = array[ offset ];
  12266. this.g = array[ offset + 1 ];
  12267. this.b = array[ offset + 2 ];
  12268. return this;
  12269. }
  12270. /**
  12271. * Writes the RGB components of this color to the given array. If no array is provided,
  12272. * the method returns a new instance.
  12273. *
  12274. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12275. * @param {number} [offset=0] - Index of the first element in the array.
  12276. * @return {Array<number>} The color components.
  12277. */
  12278. toArray( array = [], offset = 0 ) {
  12279. array[ offset ] = this.r;
  12280. array[ offset + 1 ] = this.g;
  12281. array[ offset + 2 ] = this.b;
  12282. return array;
  12283. }
  12284. /**
  12285. * Sets the components of this color from the given buffer attribute.
  12286. *
  12287. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12288. * @param {number} index - The index into the attribute.
  12289. * @return {Color} A reference to this color.
  12290. */
  12291. fromBufferAttribute( attribute, index ) {
  12292. this.r = attribute.getX( index );
  12293. this.g = attribute.getY( index );
  12294. this.b = attribute.getZ( index );
  12295. return this;
  12296. }
  12297. /**
  12298. * This methods defines the serialization result of this class. Returns the color
  12299. * as a hexadecimal value.
  12300. *
  12301. * @return {number} The hexadecimal value.
  12302. */
  12303. toJSON() {
  12304. return this.getHex();
  12305. }
  12306. *[ Symbol.iterator ]() {
  12307. yield this.r;
  12308. yield this.g;
  12309. yield this.b;
  12310. }
  12311. }
  12312. const _color = /*@__PURE__*/ new Color();
  12313. /**
  12314. * A dictionary with X11 color names.
  12315. *
  12316. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12317. *
  12318. * @static
  12319. * @type {Object}
  12320. */
  12321. Color.NAMES = _colorKeywords;
  12322. let _materialId = 0;
  12323. /**
  12324. * Abstract base class for materials.
  12325. *
  12326. * Materials define the appearance of renderable 3D objects.
  12327. *
  12328. * @abstract
  12329. * @augments EventDispatcher
  12330. */
  12331. class Material extends EventDispatcher {
  12332. /**
  12333. * Constructs a new material.
  12334. */
  12335. constructor() {
  12336. super();
  12337. /**
  12338. * This flag can be used for type testing.
  12339. *
  12340. * @type {boolean}
  12341. * @readonly
  12342. * @default true
  12343. */
  12344. this.isMaterial = true;
  12345. /**
  12346. * The ID of the material.
  12347. *
  12348. * @name Material#id
  12349. * @type {number}
  12350. * @readonly
  12351. */
  12352. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12353. /**
  12354. * The UUID of the material.
  12355. *
  12356. * @type {string}
  12357. * @readonly
  12358. */
  12359. this.uuid = generateUUID();
  12360. /**
  12361. * The name of the material.
  12362. *
  12363. * @type {string}
  12364. */
  12365. this.name = '';
  12366. /**
  12367. * The type property is used for detecting the object type
  12368. * in context of serialization/deserialization.
  12369. *
  12370. * @type {string}
  12371. * @readonly
  12372. */
  12373. this.type = 'Material';
  12374. /**
  12375. * Defines the blending type of the material.
  12376. *
  12377. * It must be set to `CustomBlending` if custom blending properties like
  12378. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12379. * should have any effect.
  12380. *
  12381. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12382. * @default NormalBlending
  12383. */
  12384. this.blending = NormalBlending;
  12385. /**
  12386. * Defines which side of faces will be rendered - front, back or both.
  12387. *
  12388. * @type {(FrontSide|BackSide|DoubleSide)}
  12389. * @default FrontSide
  12390. */
  12391. this.side = FrontSide;
  12392. /**
  12393. * If set to `true`, vertex colors should be used.
  12394. *
  12395. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12396. * four (RGBA) component color buffer attribute is used.
  12397. *
  12398. * @type {boolean}
  12399. * @default false
  12400. */
  12401. this.vertexColors = false;
  12402. /**
  12403. * Defines how transparent the material is.
  12404. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12405. *
  12406. * If the {@link Material#transparent} is not set to `true`,
  12407. * the material will remain fully opaque and this value will only affect its color.
  12408. *
  12409. * @type {number}
  12410. * @default 1
  12411. */
  12412. this.opacity = 1;
  12413. /**
  12414. * Defines whether this material is transparent. This has an effect on
  12415. * rendering as transparent objects need special treatment and are rendered
  12416. * after non-transparent objects.
  12417. *
  12418. * When set to true, the extent to which the material is transparent is
  12419. * controlled by {@link Material#opacity}.
  12420. *
  12421. * @type {boolean}
  12422. * @default false
  12423. */
  12424. this.transparent = false;
  12425. /**
  12426. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12427. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12428. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12429. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12430. *
  12431. * @type {boolean}
  12432. * @default false
  12433. */
  12434. this.alphaHash = false;
  12435. /**
  12436. * Defines the blending source factor.
  12437. *
  12438. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12439. * @default SrcAlphaFactor
  12440. */
  12441. this.blendSrc = SrcAlphaFactor;
  12442. /**
  12443. * Defines the blending destination factor.
  12444. *
  12445. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12446. * @default OneMinusSrcAlphaFactor
  12447. */
  12448. this.blendDst = OneMinusSrcAlphaFactor;
  12449. /**
  12450. * Defines the blending equation.
  12451. *
  12452. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12453. * @default AddEquation
  12454. */
  12455. this.blendEquation = AddEquation;
  12456. /**
  12457. * Defines the blending source alpha factor.
  12458. *
  12459. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12460. * @default null
  12461. */
  12462. this.blendSrcAlpha = null;
  12463. /**
  12464. * Defines the blending destination alpha factor.
  12465. *
  12466. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12467. * @default null
  12468. */
  12469. this.blendDstAlpha = null;
  12470. /**
  12471. * Defines the blending equation of the alpha channel.
  12472. *
  12473. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12474. * @default null
  12475. */
  12476. this.blendEquationAlpha = null;
  12477. /**
  12478. * Represents the RGB values of the constant blend color.
  12479. *
  12480. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12481. *
  12482. * @type {Color}
  12483. * @default (0,0,0)
  12484. */
  12485. this.blendColor = new Color( 0, 0, 0 );
  12486. /**
  12487. * Represents the alpha value of the constant blend color.
  12488. *
  12489. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12490. *
  12491. * @type {number}
  12492. * @default 0
  12493. */
  12494. this.blendAlpha = 0;
  12495. /**
  12496. * Defines the depth function.
  12497. *
  12498. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12499. * @default LessEqualDepth
  12500. */
  12501. this.depthFunc = LessEqualDepth;
  12502. /**
  12503. * Whether to have depth test enabled when rendering this material.
  12504. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12505. *
  12506. * @type {boolean}
  12507. * @default true
  12508. */
  12509. this.depthTest = true;
  12510. /**
  12511. * Whether rendering this material has any effect on the depth buffer.
  12512. *
  12513. * When drawing 2D overlays it can be useful to disable the depth writing in
  12514. * order to layer several things together without creating z-index artifacts.
  12515. *
  12516. * @type {boolean}
  12517. * @default true
  12518. */
  12519. this.depthWrite = true;
  12520. /**
  12521. * The bit mask to use when writing to the stencil buffer.
  12522. *
  12523. * @type {number}
  12524. * @default 0xff
  12525. */
  12526. this.stencilWriteMask = 0xff;
  12527. /**
  12528. * The stencil comparison function to use.
  12529. *
  12530. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12531. * @default AlwaysStencilFunc
  12532. */
  12533. this.stencilFunc = AlwaysStencilFunc;
  12534. /**
  12535. * The value to use when performing stencil comparisons or stencil operations.
  12536. *
  12537. * @type {number}
  12538. * @default 0
  12539. */
  12540. this.stencilRef = 0;
  12541. /**
  12542. * The bit mask to use when comparing against the stencil buffer.
  12543. *
  12544. * @type {number}
  12545. * @default 0xff
  12546. */
  12547. this.stencilFuncMask = 0xff;
  12548. /**
  12549. * Which stencil operation to perform when the comparison function returns `false`.
  12550. *
  12551. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12552. * @default KeepStencilOp
  12553. */
  12554. this.stencilFail = KeepStencilOp;
  12555. /**
  12556. * Which stencil operation to perform when the comparison function returns
  12557. * `true` but the depth test fails.
  12558. *
  12559. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12560. * @default KeepStencilOp
  12561. */
  12562. this.stencilZFail = KeepStencilOp;
  12563. /**
  12564. * Which stencil operation to perform when the comparison function returns
  12565. * `true` and the depth test passes.
  12566. *
  12567. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12568. * @default KeepStencilOp
  12569. */
  12570. this.stencilZPass = KeepStencilOp;
  12571. /**
  12572. * Whether stencil operations are performed against the stencil buffer. In
  12573. * order to perform writes or comparisons against the stencil buffer this
  12574. * value must be `true`.
  12575. *
  12576. * @type {boolean}
  12577. * @default false
  12578. */
  12579. this.stencilWrite = false;
  12580. /**
  12581. * User-defined clipping planes specified as THREE.Plane objects in world
  12582. * space. These planes apply to the objects this material is attached to.
  12583. * Points in space whose signed distance to the plane is negative are clipped
  12584. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12585. * be `true`.
  12586. *
  12587. * @type {?Array<Plane>}
  12588. * @default null
  12589. */
  12590. this.clippingPlanes = null;
  12591. /**
  12592. * Changes the behavior of clipping planes so that only their intersection is
  12593. * clipped, rather than their union.
  12594. *
  12595. * @type {boolean}
  12596. * @default false
  12597. */
  12598. this.clipIntersection = false;
  12599. /**
  12600. * Defines whether to clip shadows according to the clipping planes specified
  12601. * on this material.
  12602. *
  12603. * @type {boolean}
  12604. * @default false
  12605. */
  12606. this.clipShadows = false;
  12607. /**
  12608. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12609. * is determined as follows:
  12610. *
  12611. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12612. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12613. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12614. *
  12615. * @type {?(FrontSide|BackSide|DoubleSide)}
  12616. * @default null
  12617. */
  12618. this.shadowSide = null;
  12619. /**
  12620. * Whether to render the material's color.
  12621. *
  12622. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12623. * objects that occlude other objects.
  12624. *
  12625. * @type {boolean}
  12626. * @default true
  12627. */
  12628. this.colorWrite = true;
  12629. /**
  12630. * Override the renderer's default precision for this material.
  12631. *
  12632. * @type {?('highp'|'mediump'|'lowp')}
  12633. * @default null
  12634. */
  12635. this.precision = null;
  12636. /**
  12637. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12638. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12639. * The offset is added before the depth test is performed and before the value is written
  12640. * into the depth buffer.
  12641. *
  12642. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12643. * rendering solids with highlighted edges.
  12644. *
  12645. * @type {boolean}
  12646. * @default false
  12647. */
  12648. this.polygonOffset = false;
  12649. /**
  12650. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12651. *
  12652. * @type {number}
  12653. * @default 0
  12654. */
  12655. this.polygonOffsetFactor = 0;
  12656. /**
  12657. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12658. *
  12659. * @type {number}
  12660. * @default 0
  12661. */
  12662. this.polygonOffsetUnits = 0;
  12663. /**
  12664. * Whether to apply dithering to the color to remove the appearance of banding.
  12665. *
  12666. * @type {boolean}
  12667. * @default false
  12668. */
  12669. this.dithering = false;
  12670. /**
  12671. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12672. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12673. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12674. *
  12675. * @type {boolean}
  12676. * @default false
  12677. */
  12678. this.alphaToCoverage = false;
  12679. /**
  12680. * Whether to premultiply the alpha (transparency) value.
  12681. *
  12682. * @type {boolean}
  12683. * @default false
  12684. */
  12685. this.premultipliedAlpha = false;
  12686. /**
  12687. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12688. *
  12689. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12690. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12691. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12692. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12693. * disable the two pass rendering to avoid performance issues.
  12694. *
  12695. * @type {boolean}
  12696. * @default false
  12697. */
  12698. this.forceSinglePass = false;
  12699. /**
  12700. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12701. *
  12702. * @type {boolean}
  12703. * @default true
  12704. */
  12705. this.allowOverride = true;
  12706. /**
  12707. * Defines whether 3D objects using this material are visible.
  12708. *
  12709. * @type {boolean}
  12710. * @default true
  12711. */
  12712. this.visible = true;
  12713. /**
  12714. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12715. *
  12716. * It is ignored when rendering to a render target or using post processing or when using
  12717. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12718. *
  12719. * @type {boolean}
  12720. * @default true
  12721. */
  12722. this.toneMapped = true;
  12723. /**
  12724. * An object that can be used to store custom data about the Material. It
  12725. * should not hold references to functions as these will not be cloned.
  12726. *
  12727. * @type {Object}
  12728. */
  12729. this.userData = {};
  12730. /**
  12731. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12732. *
  12733. * @type {number}
  12734. * @readonly
  12735. * @default 0
  12736. */
  12737. this.version = 0;
  12738. this._alphaTest = 0;
  12739. }
  12740. /**
  12741. * Sets the alpha value to be used when running an alpha test. The material
  12742. * will not be rendered if the opacity is lower than this value.
  12743. *
  12744. * @type {number}
  12745. * @readonly
  12746. * @default 0
  12747. */
  12748. get alphaTest() {
  12749. return this._alphaTest;
  12750. }
  12751. set alphaTest( value ) {
  12752. if ( this._alphaTest > 0 !== value > 0 ) {
  12753. this.version ++;
  12754. }
  12755. this._alphaTest = value;
  12756. }
  12757. /**
  12758. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12759. *
  12760. * This method can only be used when rendering with {@link WebGLRenderer}.
  12761. *
  12762. * @param {WebGLRenderer} renderer - The renderer.
  12763. * @param {Scene} scene - The scene.
  12764. * @param {Camera} camera - The camera that is used to render the scene.
  12765. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12766. * @param {Object3D} object - The 3D object.
  12767. * @param {Object} group - The geometry group data.
  12768. */
  12769. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12770. /**
  12771. * An optional callback that is executed immediately before the shader
  12772. * program is compiled. This function is called with the shader source code
  12773. * as a parameter. Useful for the modification of built-in materials.
  12774. *
  12775. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12776. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12777. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12778. *
  12779. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12780. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12781. */
  12782. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12783. /**
  12784. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12785. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12786. * shader or recompile the shader for this material as needed.
  12787. *
  12788. * This method can only be used when rendering with {@link WebGLRenderer}.
  12789. *
  12790. * @return {string} The custom program cache key.
  12791. */
  12792. customProgramCacheKey() {
  12793. return this.onBeforeCompile.toString();
  12794. }
  12795. /**
  12796. * This method can be used to set default values from parameter objects.
  12797. * It is a generic implementation so it can be used with different types
  12798. * of materials.
  12799. *
  12800. * @param {Object} [values] - The material values to set.
  12801. */
  12802. setValues( values ) {
  12803. if ( values === undefined ) return;
  12804. for ( const key in values ) {
  12805. const newValue = values[ key ];
  12806. if ( newValue === undefined ) {
  12807. warn( `Material: parameter '${ key }' has value of undefined.` );
  12808. continue;
  12809. }
  12810. const currentValue = this[ key ];
  12811. if ( currentValue === undefined ) {
  12812. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12813. continue;
  12814. }
  12815. if ( currentValue && currentValue.isColor ) {
  12816. currentValue.set( newValue );
  12817. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12818. currentValue.copy( newValue );
  12819. } else {
  12820. this[ key ] = newValue;
  12821. }
  12822. }
  12823. }
  12824. /**
  12825. * Serializes the material into JSON.
  12826. *
  12827. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12828. * @return {Object} A JSON object representing the serialized material.
  12829. * @see {@link ObjectLoader#parse}
  12830. */
  12831. toJSON( meta ) {
  12832. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12833. if ( isRootObject ) {
  12834. meta = {
  12835. textures: {},
  12836. images: {}
  12837. };
  12838. }
  12839. const data = {
  12840. metadata: {
  12841. version: 4.7,
  12842. type: 'Material',
  12843. generator: 'Material.toJSON'
  12844. }
  12845. };
  12846. // standard Material serialization
  12847. data.uuid = this.uuid;
  12848. data.type = this.type;
  12849. if ( this.name !== '' ) data.name = this.name;
  12850. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12851. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12852. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12853. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12854. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12855. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12856. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12857. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12858. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12859. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12860. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12861. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12862. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12863. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12864. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12865. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12866. }
  12867. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12868. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12869. }
  12870. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12871. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12872. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12873. }
  12874. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12875. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12876. }
  12877. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12878. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12879. }
  12880. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12881. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12882. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12883. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12884. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12885. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12886. }
  12887. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12888. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12889. }
  12890. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12891. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12892. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12893. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12894. }
  12895. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12896. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12897. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12898. if ( this.lightMap && this.lightMap.isTexture ) {
  12899. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12900. data.lightMapIntensity = this.lightMapIntensity;
  12901. }
  12902. if ( this.aoMap && this.aoMap.isTexture ) {
  12903. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12904. data.aoMapIntensity = this.aoMapIntensity;
  12905. }
  12906. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12907. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12908. data.bumpScale = this.bumpScale;
  12909. }
  12910. if ( this.normalMap && this.normalMap.isTexture ) {
  12911. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12912. data.normalMapType = this.normalMapType;
  12913. data.normalScale = this.normalScale.toArray();
  12914. }
  12915. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12916. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12917. data.displacementScale = this.displacementScale;
  12918. data.displacementBias = this.displacementBias;
  12919. }
  12920. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12921. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12922. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12923. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12924. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12925. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12926. if ( this.envMap && this.envMap.isTexture ) {
  12927. data.envMap = this.envMap.toJSON( meta ).uuid;
  12928. if ( this.combine !== undefined ) data.combine = this.combine;
  12929. }
  12930. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12931. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12932. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12933. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12934. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12935. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12936. }
  12937. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12938. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12939. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12940. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12941. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12942. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12943. if ( this.size !== undefined ) data.size = this.size;
  12944. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12945. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12946. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12947. if ( this.side !== FrontSide ) data.side = this.side;
  12948. if ( this.vertexColors === true ) data.vertexColors = true;
  12949. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12950. if ( this.transparent === true ) data.transparent = true;
  12951. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12952. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12953. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12954. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12955. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12956. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12957. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12958. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12959. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12960. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12961. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12962. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12963. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12964. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12965. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12966. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12967. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12968. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12969. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12970. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12971. // rotation (SpriteMaterial)
  12972. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12973. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12974. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12975. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12976. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12977. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12978. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12979. if ( this.scale !== undefined ) data.scale = this.scale;
  12980. if ( this.dithering === true ) data.dithering = true;
  12981. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12982. if ( this.alphaHash === true ) data.alphaHash = true;
  12983. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12984. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12985. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12986. if ( this.allowOverride === false ) data.allowOverride = false;
  12987. if ( this.wireframe === true ) data.wireframe = true;
  12988. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12989. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  12990. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  12991. if ( this.flatShading === true ) data.flatShading = true;
  12992. if ( this.visible === false ) data.visible = false;
  12993. if ( this.toneMapped === false ) data.toneMapped = false;
  12994. if ( this.fog === false ) data.fog = false;
  12995. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  12996. // TODO: Copied from Object3D.toJSON
  12997. function extractFromCache( cache ) {
  12998. const values = [];
  12999. for ( const key in cache ) {
  13000. const data = cache[ key ];
  13001. delete data.metadata;
  13002. values.push( data );
  13003. }
  13004. return values;
  13005. }
  13006. if ( isRootObject ) {
  13007. const textures = extractFromCache( meta.textures );
  13008. const images = extractFromCache( meta.images );
  13009. if ( textures.length > 0 ) data.textures = textures;
  13010. if ( images.length > 0 ) data.images = images;
  13011. }
  13012. return data;
  13013. }
  13014. /**
  13015. * Returns a new material with copied values from this instance.
  13016. *
  13017. * @return {Material} A clone of this instance.
  13018. */
  13019. clone() {
  13020. return new this.constructor().copy( this );
  13021. }
  13022. /**
  13023. * Copies the values of the given material to this instance.
  13024. *
  13025. * @param {Material} source - The material to copy.
  13026. * @return {Material} A reference to this instance.
  13027. */
  13028. copy( source ) {
  13029. this.name = source.name;
  13030. this.blending = source.blending;
  13031. this.side = source.side;
  13032. this.vertexColors = source.vertexColors;
  13033. this.opacity = source.opacity;
  13034. this.transparent = source.transparent;
  13035. this.blendSrc = source.blendSrc;
  13036. this.blendDst = source.blendDst;
  13037. this.blendEquation = source.blendEquation;
  13038. this.blendSrcAlpha = source.blendSrcAlpha;
  13039. this.blendDstAlpha = source.blendDstAlpha;
  13040. this.blendEquationAlpha = source.blendEquationAlpha;
  13041. this.blendColor.copy( source.blendColor );
  13042. this.blendAlpha = source.blendAlpha;
  13043. this.depthFunc = source.depthFunc;
  13044. this.depthTest = source.depthTest;
  13045. this.depthWrite = source.depthWrite;
  13046. this.stencilWriteMask = source.stencilWriteMask;
  13047. this.stencilFunc = source.stencilFunc;
  13048. this.stencilRef = source.stencilRef;
  13049. this.stencilFuncMask = source.stencilFuncMask;
  13050. this.stencilFail = source.stencilFail;
  13051. this.stencilZFail = source.stencilZFail;
  13052. this.stencilZPass = source.stencilZPass;
  13053. this.stencilWrite = source.stencilWrite;
  13054. const srcPlanes = source.clippingPlanes;
  13055. let dstPlanes = null;
  13056. if ( srcPlanes !== null ) {
  13057. const n = srcPlanes.length;
  13058. dstPlanes = new Array( n );
  13059. for ( let i = 0; i !== n; ++ i ) {
  13060. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13061. }
  13062. }
  13063. this.clippingPlanes = dstPlanes;
  13064. this.clipIntersection = source.clipIntersection;
  13065. this.clipShadows = source.clipShadows;
  13066. this.shadowSide = source.shadowSide;
  13067. this.colorWrite = source.colorWrite;
  13068. this.precision = source.precision;
  13069. this.polygonOffset = source.polygonOffset;
  13070. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13071. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13072. this.dithering = source.dithering;
  13073. this.alphaTest = source.alphaTest;
  13074. this.alphaHash = source.alphaHash;
  13075. this.alphaToCoverage = source.alphaToCoverage;
  13076. this.premultipliedAlpha = source.premultipliedAlpha;
  13077. this.forceSinglePass = source.forceSinglePass;
  13078. this.allowOverride = source.allowOverride;
  13079. this.visible = source.visible;
  13080. this.toneMapped = source.toneMapped;
  13081. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13082. return this;
  13083. }
  13084. /**
  13085. * Frees the GPU-related resources allocated by this instance. Call this
  13086. * method whenever this instance is no longer used in your app.
  13087. *
  13088. * @fires Material#dispose
  13089. */
  13090. dispose() {
  13091. /**
  13092. * Fires when the material has been disposed of.
  13093. *
  13094. * @event Material#dispose
  13095. * @type {Object}
  13096. */
  13097. this.dispatchEvent( { type: 'dispose' } );
  13098. }
  13099. /**
  13100. * Setting this property to `true` indicates the engine the material
  13101. * needs to be recompiled.
  13102. *
  13103. * @type {boolean}
  13104. * @default false
  13105. * @param {boolean} value
  13106. */
  13107. set needsUpdate( value ) {
  13108. if ( value === true ) this.version ++;
  13109. }
  13110. }
  13111. /**
  13112. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13113. *
  13114. * This material is not affected by lights.
  13115. *
  13116. * @augments Material
  13117. * @demo scenes/material-browser.html#MeshBasicMaterial
  13118. */
  13119. class MeshBasicMaterial extends Material {
  13120. /**
  13121. * Constructs a new mesh basic material.
  13122. *
  13123. * @param {Object} [parameters] - An object with one or more properties
  13124. * defining the material's appearance. Any property of the material
  13125. * (including any property from inherited materials) can be passed
  13126. * in here. Color values can be passed any type of value accepted
  13127. * by {@link Color#set}.
  13128. */
  13129. constructor( parameters ) {
  13130. super();
  13131. /**
  13132. * This flag can be used for type testing.
  13133. *
  13134. * @type {boolean}
  13135. * @readonly
  13136. * @default true
  13137. */
  13138. this.isMeshBasicMaterial = true;
  13139. this.type = 'MeshBasicMaterial';
  13140. /**
  13141. * Color of the material.
  13142. *
  13143. * @type {Color}
  13144. * @default (1,1,1)
  13145. */
  13146. this.color = new Color( 0xffffff ); // diffuse
  13147. /**
  13148. * The color map. May optionally include an alpha channel, typically combined
  13149. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13150. * color is modulated by the diffuse `color`.
  13151. *
  13152. * @type {?Texture}
  13153. * @default null
  13154. */
  13155. this.map = null;
  13156. /**
  13157. * The light map. Requires a second set of UVs.
  13158. *
  13159. * @type {?Texture}
  13160. * @default null
  13161. */
  13162. this.lightMap = null;
  13163. /**
  13164. * Intensity of the baked light.
  13165. *
  13166. * @type {number}
  13167. * @default 1
  13168. */
  13169. this.lightMapIntensity = 1.0;
  13170. /**
  13171. * The red channel of this texture is used as the ambient occlusion map.
  13172. * Requires a second set of UVs.
  13173. *
  13174. * @type {?Texture}
  13175. * @default null
  13176. */
  13177. this.aoMap = null;
  13178. /**
  13179. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13180. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13181. * red channel is also `1`, ambient light is fully occluded on a surface.
  13182. *
  13183. * @type {number}
  13184. * @default 1
  13185. */
  13186. this.aoMapIntensity = 1.0;
  13187. /**
  13188. * Specular map used by the material.
  13189. *
  13190. * @type {?Texture}
  13191. * @default null
  13192. */
  13193. this.specularMap = null;
  13194. /**
  13195. * The alpha map is a grayscale texture that controls the opacity across the
  13196. * surface (black: fully transparent; white: fully opaque).
  13197. *
  13198. * Only the color of the texture is used, ignoring the alpha channel if one
  13199. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13200. * when sampling this texture due to the extra bit of precision provided for
  13201. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13202. * luminance/alpha textures will also still work as expected.
  13203. *
  13204. * @type {?Texture}
  13205. * @default null
  13206. */
  13207. this.alphaMap = null;
  13208. /**
  13209. * The environment map.
  13210. *
  13211. * @type {?Texture}
  13212. * @default null
  13213. */
  13214. this.envMap = null;
  13215. /**
  13216. * The rotation of the environment map in radians.
  13217. *
  13218. * @type {Euler}
  13219. * @default (0,0,0)
  13220. */
  13221. this.envMapRotation = new Euler();
  13222. /**
  13223. * How to combine the result of the surface's color with the environment map, if any.
  13224. *
  13225. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13226. * blend between the two colors.
  13227. *
  13228. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13229. * @default MultiplyOperation
  13230. */
  13231. this.combine = MultiplyOperation;
  13232. /**
  13233. * How much the environment map affects the surface.
  13234. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13235. *
  13236. * @type {number}
  13237. * @default 1
  13238. */
  13239. this.reflectivity = 1;
  13240. /**
  13241. * The index of refraction (IOR) of air (approximately 1) divided by the
  13242. * index of refraction of the material. It is used with environment mapping
  13243. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13244. * The refraction ratio should not exceed `1`.
  13245. *
  13246. * @type {number}
  13247. * @default 0.98
  13248. */
  13249. this.refractionRatio = 0.98;
  13250. /**
  13251. * Renders the geometry as a wireframe.
  13252. *
  13253. * @type {boolean}
  13254. * @default false
  13255. */
  13256. this.wireframe = false;
  13257. /**
  13258. * Controls the thickness of the wireframe.
  13259. *
  13260. * Can only be used with {@link SVGRenderer}.
  13261. *
  13262. * @type {number}
  13263. * @default 1
  13264. */
  13265. this.wireframeLinewidth = 1;
  13266. /**
  13267. * Defines appearance of wireframe ends.
  13268. *
  13269. * Can only be used with {@link SVGRenderer}.
  13270. *
  13271. * @type {('round'|'bevel'|'miter')}
  13272. * @default 'round'
  13273. */
  13274. this.wireframeLinecap = 'round';
  13275. /**
  13276. * Defines appearance of wireframe joints.
  13277. *
  13278. * Can only be used with {@link SVGRenderer}.
  13279. *
  13280. * @type {('round'|'bevel'|'miter')}
  13281. * @default 'round'
  13282. */
  13283. this.wireframeLinejoin = 'round';
  13284. /**
  13285. * Whether the material is affected by fog or not.
  13286. *
  13287. * @type {boolean}
  13288. * @default true
  13289. */
  13290. this.fog = true;
  13291. this.setValues( parameters );
  13292. }
  13293. copy( source ) {
  13294. super.copy( source );
  13295. this.color.copy( source.color );
  13296. this.map = source.map;
  13297. this.lightMap = source.lightMap;
  13298. this.lightMapIntensity = source.lightMapIntensity;
  13299. this.aoMap = source.aoMap;
  13300. this.aoMapIntensity = source.aoMapIntensity;
  13301. this.specularMap = source.specularMap;
  13302. this.alphaMap = source.alphaMap;
  13303. this.envMap = source.envMap;
  13304. this.envMapRotation.copy( source.envMapRotation );
  13305. this.combine = source.combine;
  13306. this.reflectivity = source.reflectivity;
  13307. this.refractionRatio = source.refractionRatio;
  13308. this.wireframe = source.wireframe;
  13309. this.wireframeLinewidth = source.wireframeLinewidth;
  13310. this.wireframeLinecap = source.wireframeLinecap;
  13311. this.wireframeLinejoin = source.wireframeLinejoin;
  13312. this.fog = source.fog;
  13313. return this;
  13314. }
  13315. }
  13316. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13317. const _tables = /*@__PURE__*/ _generateTables();
  13318. function _generateTables() {
  13319. // float32 to float16 helpers
  13320. const buffer = new ArrayBuffer( 4 );
  13321. const floatView = new Float32Array( buffer );
  13322. const uint32View = new Uint32Array( buffer );
  13323. const baseTable = new Uint32Array( 512 );
  13324. const shiftTable = new Uint32Array( 512 );
  13325. for ( let i = 0; i < 256; ++ i ) {
  13326. const e = i - 127;
  13327. // very small number (0, -0)
  13328. if ( e < -27 ) {
  13329. baseTable[ i ] = 0x0000;
  13330. baseTable[ i | 0x100 ] = 0x8000;
  13331. shiftTable[ i ] = 24;
  13332. shiftTable[ i | 0x100 ] = 24;
  13333. // small number (denorm)
  13334. } else if ( e < -14 ) {
  13335. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13336. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13337. shiftTable[ i ] = - e - 1;
  13338. shiftTable[ i | 0x100 ] = - e - 1;
  13339. // normal number
  13340. } else if ( e <= 15 ) {
  13341. baseTable[ i ] = ( e + 15 ) << 10;
  13342. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13343. shiftTable[ i ] = 13;
  13344. shiftTable[ i | 0x100 ] = 13;
  13345. // large number (Infinity, -Infinity)
  13346. } else if ( e < 128 ) {
  13347. baseTable[ i ] = 0x7c00;
  13348. baseTable[ i | 0x100 ] = 0xfc00;
  13349. shiftTable[ i ] = 24;
  13350. shiftTable[ i | 0x100 ] = 24;
  13351. // stay (NaN, Infinity, -Infinity)
  13352. } else {
  13353. baseTable[ i ] = 0x7c00;
  13354. baseTable[ i | 0x100 ] = 0xfc00;
  13355. shiftTable[ i ] = 13;
  13356. shiftTable[ i | 0x100 ] = 13;
  13357. }
  13358. }
  13359. // float16 to float32 helpers
  13360. const mantissaTable = new Uint32Array( 2048 );
  13361. const exponentTable = new Uint32Array( 64 );
  13362. const offsetTable = new Uint32Array( 64 );
  13363. for ( let i = 1; i < 1024; ++ i ) {
  13364. let m = i << 13; // zero pad mantissa bits
  13365. let e = 0; // zero exponent
  13366. // normalized
  13367. while ( ( m & 0x00800000 ) === 0 ) {
  13368. m <<= 1;
  13369. e -= 0x00800000; // decrement exponent
  13370. }
  13371. m &= -8388609; // clear leading 1 bit
  13372. e += 0x38800000; // adjust bias
  13373. mantissaTable[ i ] = m | e;
  13374. }
  13375. for ( let i = 1024; i < 2048; ++ i ) {
  13376. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13377. }
  13378. for ( let i = 1; i < 31; ++ i ) {
  13379. exponentTable[ i ] = i << 23;
  13380. }
  13381. exponentTable[ 31 ] = 0x47800000;
  13382. exponentTable[ 32 ] = 0x80000000;
  13383. for ( let i = 33; i < 63; ++ i ) {
  13384. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13385. }
  13386. exponentTable[ 63 ] = 0xc7800000;
  13387. for ( let i = 1; i < 64; ++ i ) {
  13388. if ( i !== 32 ) {
  13389. offsetTable[ i ] = 1024;
  13390. }
  13391. }
  13392. return {
  13393. floatView: floatView,
  13394. uint32View: uint32View,
  13395. baseTable: baseTable,
  13396. shiftTable: shiftTable,
  13397. mantissaTable: mantissaTable,
  13398. exponentTable: exponentTable,
  13399. offsetTable: offsetTable
  13400. };
  13401. }
  13402. /**
  13403. * Returns a half precision floating point value (FP16) from the given single
  13404. * precision floating point value (FP32).
  13405. *
  13406. * @param {number} val - A single precision floating point value.
  13407. * @return {number} The FP16 value.
  13408. */
  13409. function toHalfFloat( val ) {
  13410. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13411. val = clamp( val, -65504, 65504 );
  13412. _tables.floatView[ 0 ] = val;
  13413. const f = _tables.uint32View[ 0 ];
  13414. const e = ( f >> 23 ) & 0x1ff;
  13415. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13416. }
  13417. /**
  13418. * Returns a single precision floating point value (FP32) from the given half
  13419. * precision floating point value (FP16).
  13420. *
  13421. * @param {number} val - A half precision floating point value.
  13422. * @return {number} The FP32 value.
  13423. */
  13424. function fromHalfFloat( val ) {
  13425. const m = val >> 10;
  13426. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13427. return _tables.floatView[ 0 ];
  13428. }
  13429. /**
  13430. * A class containing utility functions for data.
  13431. *
  13432. * @hideconstructor
  13433. */
  13434. class DataUtils {
  13435. /**
  13436. * Returns a half precision floating point value (FP16) from the given single
  13437. * precision floating point value (FP32).
  13438. *
  13439. * @param {number} val - A single precision floating point value.
  13440. * @return {number} The FP16 value.
  13441. */
  13442. static toHalfFloat( val ) {
  13443. return toHalfFloat( val );
  13444. }
  13445. /**
  13446. * Returns a single precision floating point value (FP32) from the given half
  13447. * precision floating point value (FP16).
  13448. *
  13449. * @param {number} val - A half precision floating point value.
  13450. * @return {number} The FP32 value.
  13451. */
  13452. static fromHalfFloat( val ) {
  13453. return fromHalfFloat( val );
  13454. }
  13455. }
  13456. const _vector$9 = /*@__PURE__*/ new Vector3();
  13457. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13458. let _id$3 = 0;
  13459. /**
  13460. * This class stores data for an attribute (such as vertex positions, face
  13461. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13462. * a geometry, which allows for more efficient passing of data to the GPU.
  13463. *
  13464. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13465. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13466. */
  13467. class BufferAttribute {
  13468. /**
  13469. * Constructs a new buffer attribute.
  13470. *
  13471. * @param {TypedArray} array - The array holding the attribute data.
  13472. * @param {number} itemSize - The item size.
  13473. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13474. */
  13475. constructor( array, itemSize, normalized = false ) {
  13476. if ( Array.isArray( array ) ) {
  13477. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13478. }
  13479. /**
  13480. * This flag can be used for type testing.
  13481. *
  13482. * @type {boolean}
  13483. * @readonly
  13484. * @default true
  13485. */
  13486. this.isBufferAttribute = true;
  13487. /**
  13488. * The ID of the buffer attribute.
  13489. *
  13490. * @name BufferAttribute#id
  13491. * @type {number}
  13492. * @readonly
  13493. */
  13494. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13495. /**
  13496. * The name of the buffer attribute.
  13497. *
  13498. * @type {string}
  13499. */
  13500. this.name = '';
  13501. /**
  13502. * The array holding the attribute data. It should have `itemSize * numVertices`
  13503. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13504. *
  13505. * @type {TypedArray}
  13506. */
  13507. this.array = array;
  13508. /**
  13509. * The number of values of the array that should be associated with a particular vertex.
  13510. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13511. * normal, or color), then the value should be `3`.
  13512. *
  13513. * @type {number}
  13514. */
  13515. this.itemSize = itemSize;
  13516. /**
  13517. * Represents the number of items this buffer attribute stores. It is internally computed
  13518. * by dividing the `array` length by the `itemSize`.
  13519. *
  13520. * @type {number}
  13521. * @readonly
  13522. */
  13523. this.count = array !== undefined ? array.length / itemSize : 0;
  13524. /**
  13525. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13526. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13527. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13528. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13529. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13530. *
  13531. * @type {boolean}
  13532. */
  13533. this.normalized = normalized;
  13534. /**
  13535. * Defines the intended usage pattern of the data store for optimization purposes.
  13536. *
  13537. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13538. * instantiate a new one and set the desired usage before the next render.
  13539. *
  13540. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13541. * @default StaticDrawUsage
  13542. */
  13543. this.usage = StaticDrawUsage;
  13544. /**
  13545. * This can be used to only update some components of stored vectors (for example, just the
  13546. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13547. *
  13548. * @type {Array<Object>}
  13549. */
  13550. this.updateRanges = [];
  13551. /**
  13552. * Configures the bound GPU type for use in shaders.
  13553. *
  13554. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13555. * For lower precision float types, use `Float16BufferAttribute`.
  13556. *
  13557. * @type {(FloatType|IntType)}
  13558. * @default FloatType
  13559. */
  13560. this.gpuType = FloatType;
  13561. /**
  13562. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13563. *
  13564. * @type {number}
  13565. */
  13566. this.version = 0;
  13567. }
  13568. /**
  13569. * A callback function that is executed after the renderer has transferred the attribute
  13570. * array data to the GPU.
  13571. */
  13572. onUploadCallback() {}
  13573. /**
  13574. * Flag to indicate that this attribute has changed and should be re-sent to
  13575. * the GPU. Set this to `true` when you modify the value of the array.
  13576. *
  13577. * @type {number}
  13578. * @default false
  13579. * @param {boolean} value
  13580. */
  13581. set needsUpdate( value ) {
  13582. if ( value === true ) this.version ++;
  13583. }
  13584. /**
  13585. * Sets the usage of this buffer attribute.
  13586. *
  13587. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13588. * @return {BufferAttribute} A reference to this buffer attribute.
  13589. */
  13590. setUsage( value ) {
  13591. this.usage = value;
  13592. return this;
  13593. }
  13594. /**
  13595. * Adds a range of data in the data array to be updated on the GPU.
  13596. *
  13597. * @param {number} start - Position at which to start update.
  13598. * @param {number} count - The number of components to update.
  13599. */
  13600. addUpdateRange( start, count ) {
  13601. this.updateRanges.push( { start, count } );
  13602. }
  13603. /**
  13604. * Clears the update ranges.
  13605. */
  13606. clearUpdateRanges() {
  13607. this.updateRanges.length = 0;
  13608. }
  13609. /**
  13610. * Copies the values of the given buffer attribute to this instance.
  13611. *
  13612. * @param {BufferAttribute} source - The buffer attribute to copy.
  13613. * @return {BufferAttribute} A reference to this instance.
  13614. */
  13615. copy( source ) {
  13616. this.name = source.name;
  13617. this.array = new source.array.constructor( source.array );
  13618. this.itemSize = source.itemSize;
  13619. this.count = source.count;
  13620. this.normalized = source.normalized;
  13621. this.usage = source.usage;
  13622. this.gpuType = source.gpuType;
  13623. return this;
  13624. }
  13625. /**
  13626. * Copies a vector from the given buffer attribute to this one. The start
  13627. * and destination position in the attribute buffers are represented by the
  13628. * given indices.
  13629. *
  13630. * @param {number} index1 - The destination index into this buffer attribute.
  13631. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13632. * @param {number} index2 - The source index into the given buffer attribute.
  13633. * @return {BufferAttribute} A reference to this instance.
  13634. */
  13635. copyAt( index1, attribute, index2 ) {
  13636. index1 *= this.itemSize;
  13637. index2 *= attribute.itemSize;
  13638. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13639. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13640. }
  13641. return this;
  13642. }
  13643. /**
  13644. * Copies the given array data into this buffer attribute.
  13645. *
  13646. * @param {(TypedArray|Array)} array - The array to copy.
  13647. * @return {BufferAttribute} A reference to this instance.
  13648. */
  13649. copyArray( array ) {
  13650. this.array.set( array );
  13651. return this;
  13652. }
  13653. /**
  13654. * Applies the given 3x3 matrix to the given attribute. Works with
  13655. * item size `2` and `3`.
  13656. *
  13657. * @param {Matrix3} m - The matrix to apply.
  13658. * @return {BufferAttribute} A reference to this instance.
  13659. */
  13660. applyMatrix3( m ) {
  13661. if ( this.itemSize === 2 ) {
  13662. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13663. _vector2$1.fromBufferAttribute( this, i );
  13664. _vector2$1.applyMatrix3( m );
  13665. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13666. }
  13667. } else if ( this.itemSize === 3 ) {
  13668. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13669. _vector$9.fromBufferAttribute( this, i );
  13670. _vector$9.applyMatrix3( m );
  13671. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13672. }
  13673. }
  13674. return this;
  13675. }
  13676. /**
  13677. * Applies the given 4x4 matrix to the given attribute. Only works with
  13678. * item size `3`.
  13679. *
  13680. * @param {Matrix4} m - The matrix to apply.
  13681. * @return {BufferAttribute} A reference to this instance.
  13682. */
  13683. applyMatrix4( m ) {
  13684. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13685. _vector$9.fromBufferAttribute( this, i );
  13686. _vector$9.applyMatrix4( m );
  13687. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13688. }
  13689. return this;
  13690. }
  13691. /**
  13692. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13693. * item size `3`.
  13694. *
  13695. * @param {Matrix3} m - The normal matrix to apply.
  13696. * @return {BufferAttribute} A reference to this instance.
  13697. */
  13698. applyNormalMatrix( m ) {
  13699. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13700. _vector$9.fromBufferAttribute( this, i );
  13701. _vector$9.applyNormalMatrix( m );
  13702. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13703. }
  13704. return this;
  13705. }
  13706. /**
  13707. * Applies the given 4x4 matrix to the given attribute. Only works with
  13708. * item size `3` and with direction vectors.
  13709. *
  13710. * @param {Matrix4} m - The matrix to apply.
  13711. * @return {BufferAttribute} A reference to this instance.
  13712. */
  13713. transformDirection( m ) {
  13714. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13715. _vector$9.fromBufferAttribute( this, i );
  13716. _vector$9.transformDirection( m );
  13717. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13718. }
  13719. return this;
  13720. }
  13721. /**
  13722. * Sets the given array data in the buffer attribute.
  13723. *
  13724. * @param {(TypedArray|Array)} value - The array data to set.
  13725. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13726. * @return {BufferAttribute} A reference to this instance.
  13727. */
  13728. set( value, offset = 0 ) {
  13729. // Matching BufferAttribute constructor, do not normalize the array.
  13730. this.array.set( value, offset );
  13731. return this;
  13732. }
  13733. /**
  13734. * Returns the given component of the vector at the given index.
  13735. *
  13736. * @param {number} index - The index into the buffer attribute.
  13737. * @param {number} component - The component index.
  13738. * @return {number} The returned value.
  13739. */
  13740. getComponent( index, component ) {
  13741. let value = this.array[ index * this.itemSize + component ];
  13742. if ( this.normalized ) value = denormalize( value, this.array );
  13743. return value;
  13744. }
  13745. /**
  13746. * Sets the given value to the given component of the vector at the given index.
  13747. *
  13748. * @param {number} index - The index into the buffer attribute.
  13749. * @param {number} component - The component index.
  13750. * @param {number} value - The value to set.
  13751. * @return {BufferAttribute} A reference to this instance.
  13752. */
  13753. setComponent( index, component, value ) {
  13754. if ( this.normalized ) value = normalize( value, this.array );
  13755. this.array[ index * this.itemSize + component ] = value;
  13756. return this;
  13757. }
  13758. /**
  13759. * Returns the x component of the vector at the given index.
  13760. *
  13761. * @param {number} index - The index into the buffer attribute.
  13762. * @return {number} The x component.
  13763. */
  13764. getX( index ) {
  13765. let x = this.array[ index * this.itemSize ];
  13766. if ( this.normalized ) x = denormalize( x, this.array );
  13767. return x;
  13768. }
  13769. /**
  13770. * Sets the x component of the vector at the given index.
  13771. *
  13772. * @param {number} index - The index into the buffer attribute.
  13773. * @param {number} x - The value to set.
  13774. * @return {BufferAttribute} A reference to this instance.
  13775. */
  13776. setX( index, x ) {
  13777. if ( this.normalized ) x = normalize( x, this.array );
  13778. this.array[ index * this.itemSize ] = x;
  13779. return this;
  13780. }
  13781. /**
  13782. * Returns the y component of the vector at the given index.
  13783. *
  13784. * @param {number} index - The index into the buffer attribute.
  13785. * @return {number} The y component.
  13786. */
  13787. getY( index ) {
  13788. let y = this.array[ index * this.itemSize + 1 ];
  13789. if ( this.normalized ) y = denormalize( y, this.array );
  13790. return y;
  13791. }
  13792. /**
  13793. * Sets the y component of the vector at the given index.
  13794. *
  13795. * @param {number} index - The index into the buffer attribute.
  13796. * @param {number} y - The value to set.
  13797. * @return {BufferAttribute} A reference to this instance.
  13798. */
  13799. setY( index, y ) {
  13800. if ( this.normalized ) y = normalize( y, this.array );
  13801. this.array[ index * this.itemSize + 1 ] = y;
  13802. return this;
  13803. }
  13804. /**
  13805. * Returns the z component of the vector at the given index.
  13806. *
  13807. * @param {number} index - The index into the buffer attribute.
  13808. * @return {number} The z component.
  13809. */
  13810. getZ( index ) {
  13811. let z = this.array[ index * this.itemSize + 2 ];
  13812. if ( this.normalized ) z = denormalize( z, this.array );
  13813. return z;
  13814. }
  13815. /**
  13816. * Sets the z component of the vector at the given index.
  13817. *
  13818. * @param {number} index - The index into the buffer attribute.
  13819. * @param {number} z - The value to set.
  13820. * @return {BufferAttribute} A reference to this instance.
  13821. */
  13822. setZ( index, z ) {
  13823. if ( this.normalized ) z = normalize( z, this.array );
  13824. this.array[ index * this.itemSize + 2 ] = z;
  13825. return this;
  13826. }
  13827. /**
  13828. * Returns the w component of the vector at the given index.
  13829. *
  13830. * @param {number} index - The index into the buffer attribute.
  13831. * @return {number} The w component.
  13832. */
  13833. getW( index ) {
  13834. let w = this.array[ index * this.itemSize + 3 ];
  13835. if ( this.normalized ) w = denormalize( w, this.array );
  13836. return w;
  13837. }
  13838. /**
  13839. * Sets the w component of the vector at the given index.
  13840. *
  13841. * @param {number} index - The index into the buffer attribute.
  13842. * @param {number} w - The value to set.
  13843. * @return {BufferAttribute} A reference to this instance.
  13844. */
  13845. setW( index, w ) {
  13846. if ( this.normalized ) w = normalize( w, this.array );
  13847. this.array[ index * this.itemSize + 3 ] = w;
  13848. return this;
  13849. }
  13850. /**
  13851. * Sets the x and y component of the vector at the given index.
  13852. *
  13853. * @param {number} index - The index into the buffer attribute.
  13854. * @param {number} x - The value for the x component to set.
  13855. * @param {number} y - The value for the y component to set.
  13856. * @return {BufferAttribute} A reference to this instance.
  13857. */
  13858. setXY( index, x, y ) {
  13859. index *= this.itemSize;
  13860. if ( this.normalized ) {
  13861. x = normalize( x, this.array );
  13862. y = normalize( y, this.array );
  13863. }
  13864. this.array[ index + 0 ] = x;
  13865. this.array[ index + 1 ] = y;
  13866. return this;
  13867. }
  13868. /**
  13869. * Sets the x, y and z component of the vector at the given index.
  13870. *
  13871. * @param {number} index - The index into the buffer attribute.
  13872. * @param {number} x - The value for the x component to set.
  13873. * @param {number} y - The value for the y component to set.
  13874. * @param {number} z - The value for the z component to set.
  13875. * @return {BufferAttribute} A reference to this instance.
  13876. */
  13877. setXYZ( index, x, y, z ) {
  13878. index *= this.itemSize;
  13879. if ( this.normalized ) {
  13880. x = normalize( x, this.array );
  13881. y = normalize( y, this.array );
  13882. z = normalize( z, this.array );
  13883. }
  13884. this.array[ index + 0 ] = x;
  13885. this.array[ index + 1 ] = y;
  13886. this.array[ index + 2 ] = z;
  13887. return this;
  13888. }
  13889. /**
  13890. * Sets the x, y, z and w component of the vector at the given index.
  13891. *
  13892. * @param {number} index - The index into the buffer attribute.
  13893. * @param {number} x - The value for the x component to set.
  13894. * @param {number} y - The value for the y component to set.
  13895. * @param {number} z - The value for the z component to set.
  13896. * @param {number} w - The value for the w component to set.
  13897. * @return {BufferAttribute} A reference to this instance.
  13898. */
  13899. setXYZW( index, x, y, z, w ) {
  13900. index *= this.itemSize;
  13901. if ( this.normalized ) {
  13902. x = normalize( x, this.array );
  13903. y = normalize( y, this.array );
  13904. z = normalize( z, this.array );
  13905. w = normalize( w, this.array );
  13906. }
  13907. this.array[ index + 0 ] = x;
  13908. this.array[ index + 1 ] = y;
  13909. this.array[ index + 2 ] = z;
  13910. this.array[ index + 3 ] = w;
  13911. return this;
  13912. }
  13913. /**
  13914. * Sets the given callback function that is executed after the Renderer has transferred
  13915. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13916. * the upload when attribute data are not needed anymore on the CPU side.
  13917. *
  13918. * @param {Function} callback - The `onUpload()` callback.
  13919. * @return {BufferAttribute} A reference to this instance.
  13920. */
  13921. onUpload( callback ) {
  13922. this.onUploadCallback = callback;
  13923. return this;
  13924. }
  13925. /**
  13926. * Returns a new buffer attribute with copied values from this instance.
  13927. *
  13928. * @return {BufferAttribute} A clone of this instance.
  13929. */
  13930. clone() {
  13931. return new this.constructor( this.array, this.itemSize ).copy( this );
  13932. }
  13933. /**
  13934. * Serializes the buffer attribute into JSON.
  13935. *
  13936. * @return {Object} A JSON object representing the serialized buffer attribute.
  13937. */
  13938. toJSON() {
  13939. const data = {
  13940. itemSize: this.itemSize,
  13941. type: this.array.constructor.name,
  13942. array: Array.from( this.array ),
  13943. normalized: this.normalized
  13944. };
  13945. if ( this.name !== '' ) data.name = this.name;
  13946. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13947. return data;
  13948. }
  13949. }
  13950. /**
  13951. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13952. * a plain `Array` instance.
  13953. *
  13954. * @augments BufferAttribute
  13955. */
  13956. class Int8BufferAttribute extends BufferAttribute {
  13957. /**
  13958. * Constructs a new buffer attribute.
  13959. *
  13960. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13961. * @param {number} itemSize - The item size.
  13962. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13963. */
  13964. constructor( array, itemSize, normalized ) {
  13965. super( new Int8Array( array ), itemSize, normalized );
  13966. }
  13967. }
  13968. /**
  13969. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13970. * a plain `Array` instance.
  13971. *
  13972. * @augments BufferAttribute
  13973. */
  13974. class Uint8BufferAttribute extends BufferAttribute {
  13975. /**
  13976. * Constructs a new buffer attribute.
  13977. *
  13978. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13979. * @param {number} itemSize - The item size.
  13980. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13981. */
  13982. constructor( array, itemSize, normalized ) {
  13983. super( new Uint8Array( array ), itemSize, normalized );
  13984. }
  13985. }
  13986. /**
  13987. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13988. * a plain `Array` instance.
  13989. *
  13990. * @augments BufferAttribute
  13991. */
  13992. class Uint8ClampedBufferAttribute extends BufferAttribute {
  13993. /**
  13994. * Constructs a new buffer attribute.
  13995. *
  13996. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  13997. * @param {number} itemSize - The item size.
  13998. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13999. */
  14000. constructor( array, itemSize, normalized ) {
  14001. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14002. }
  14003. }
  14004. /**
  14005. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14006. * a plain `Array` instance.
  14007. *
  14008. * @augments BufferAttribute
  14009. */
  14010. class Int16BufferAttribute extends BufferAttribute {
  14011. /**
  14012. * Constructs a new buffer attribute.
  14013. *
  14014. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14015. * @param {number} itemSize - The item size.
  14016. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14017. */
  14018. constructor( array, itemSize, normalized ) {
  14019. super( new Int16Array( array ), itemSize, normalized );
  14020. }
  14021. }
  14022. /**
  14023. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14024. * a plain `Array` instance.
  14025. *
  14026. * @augments BufferAttribute
  14027. */
  14028. class Uint16BufferAttribute extends BufferAttribute {
  14029. /**
  14030. * Constructs a new buffer attribute.
  14031. *
  14032. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14033. * @param {number} itemSize - The item size.
  14034. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14035. */
  14036. constructor( array, itemSize, normalized ) {
  14037. super( new Uint16Array( array ), itemSize, normalized );
  14038. }
  14039. }
  14040. /**
  14041. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14042. * a plain `Array` instance.
  14043. *
  14044. * @augments BufferAttribute
  14045. */
  14046. class Int32BufferAttribute extends BufferAttribute {
  14047. /**
  14048. * Constructs a new buffer attribute.
  14049. *
  14050. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14051. * @param {number} itemSize - The item size.
  14052. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14053. */
  14054. constructor( array, itemSize, normalized ) {
  14055. super( new Int32Array( array ), itemSize, normalized );
  14056. }
  14057. }
  14058. /**
  14059. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14060. * a plain `Array` instance.
  14061. *
  14062. * @augments BufferAttribute
  14063. */
  14064. class Uint32BufferAttribute extends BufferAttribute {
  14065. /**
  14066. * Constructs a new buffer attribute.
  14067. *
  14068. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14069. * @param {number} itemSize - The item size.
  14070. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14071. */
  14072. constructor( array, itemSize, normalized ) {
  14073. super( new Uint32Array( array ), itemSize, normalized );
  14074. }
  14075. }
  14076. /**
  14077. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14078. * a plain `Array` instance.
  14079. *
  14080. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14081. * browser support is still problematic.
  14082. *
  14083. * @augments BufferAttribute
  14084. */
  14085. class Float16BufferAttribute extends BufferAttribute {
  14086. /**
  14087. * Constructs a new buffer attribute.
  14088. *
  14089. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14090. * @param {number} itemSize - The item size.
  14091. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14092. */
  14093. constructor( array, itemSize, normalized ) {
  14094. super( new Uint16Array( array ), itemSize, normalized );
  14095. this.isFloat16BufferAttribute = true;
  14096. }
  14097. getX( index ) {
  14098. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14099. if ( this.normalized ) x = denormalize( x, this.array );
  14100. return x;
  14101. }
  14102. setX( index, x ) {
  14103. if ( this.normalized ) x = normalize( x, this.array );
  14104. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14105. return this;
  14106. }
  14107. getY( index ) {
  14108. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14109. if ( this.normalized ) y = denormalize( y, this.array );
  14110. return y;
  14111. }
  14112. setY( index, y ) {
  14113. if ( this.normalized ) y = normalize( y, this.array );
  14114. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14115. return this;
  14116. }
  14117. getZ( index ) {
  14118. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14119. if ( this.normalized ) z = denormalize( z, this.array );
  14120. return z;
  14121. }
  14122. setZ( index, z ) {
  14123. if ( this.normalized ) z = normalize( z, this.array );
  14124. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14125. return this;
  14126. }
  14127. getW( index ) {
  14128. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14129. if ( this.normalized ) w = denormalize( w, this.array );
  14130. return w;
  14131. }
  14132. setW( index, w ) {
  14133. if ( this.normalized ) w = normalize( w, this.array );
  14134. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14135. return this;
  14136. }
  14137. setXY( index, x, y ) {
  14138. index *= this.itemSize;
  14139. if ( this.normalized ) {
  14140. x = normalize( x, this.array );
  14141. y = normalize( y, this.array );
  14142. }
  14143. this.array[ index + 0 ] = toHalfFloat( x );
  14144. this.array[ index + 1 ] = toHalfFloat( y );
  14145. return this;
  14146. }
  14147. setXYZ( index, x, y, z ) {
  14148. index *= this.itemSize;
  14149. if ( this.normalized ) {
  14150. x = normalize( x, this.array );
  14151. y = normalize( y, this.array );
  14152. z = normalize( z, this.array );
  14153. }
  14154. this.array[ index + 0 ] = toHalfFloat( x );
  14155. this.array[ index + 1 ] = toHalfFloat( y );
  14156. this.array[ index + 2 ] = toHalfFloat( z );
  14157. return this;
  14158. }
  14159. setXYZW( index, x, y, z, w ) {
  14160. index *= this.itemSize;
  14161. if ( this.normalized ) {
  14162. x = normalize( x, this.array );
  14163. y = normalize( y, this.array );
  14164. z = normalize( z, this.array );
  14165. w = normalize( w, this.array );
  14166. }
  14167. this.array[ index + 0 ] = toHalfFloat( x );
  14168. this.array[ index + 1 ] = toHalfFloat( y );
  14169. this.array[ index + 2 ] = toHalfFloat( z );
  14170. this.array[ index + 3 ] = toHalfFloat( w );
  14171. return this;
  14172. }
  14173. }
  14174. /**
  14175. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14176. * a plain `Array` instance.
  14177. *
  14178. * @augments BufferAttribute
  14179. */
  14180. class Float32BufferAttribute extends BufferAttribute {
  14181. /**
  14182. * Constructs a new buffer attribute.
  14183. *
  14184. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14185. * @param {number} itemSize - The item size.
  14186. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14187. */
  14188. constructor( array, itemSize, normalized ) {
  14189. super( new Float32Array( array ), itemSize, normalized );
  14190. }
  14191. }
  14192. let _id$2 = 0;
  14193. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14194. const _obj = /*@__PURE__*/ new Object3D();
  14195. const _offset = /*@__PURE__*/ new Vector3();
  14196. const _box$2 = /*@__PURE__*/ new Box3();
  14197. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14198. const _vector$8 = /*@__PURE__*/ new Vector3();
  14199. /**
  14200. * A representation of mesh, line, or point geometry. Includes vertex
  14201. * positions, face indices, normals, colors, UVs, and custom attributes
  14202. * within buffers, reducing the cost of passing all this data to the GPU.
  14203. *
  14204. * ```js
  14205. * const geometry = new THREE.BufferGeometry();
  14206. * // create a simple square shape. We duplicate the top left and bottom right
  14207. * // vertices because each vertex needs to appear once per triangle.
  14208. * const vertices = new Float32Array( [
  14209. * -1.0, -1.0, 1.0, // v0
  14210. * 1.0, -1.0, 1.0, // v1
  14211. * 1.0, 1.0, 1.0, // v2
  14212. *
  14213. * 1.0, 1.0, 1.0, // v3
  14214. * -1.0, 1.0, 1.0, // v4
  14215. * -1.0, -1.0, 1.0 // v5
  14216. * ] );
  14217. * // itemSize = 3 because there are 3 values (components) per vertex
  14218. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14219. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14220. * const mesh = new THREE.Mesh( geometry, material );
  14221. * ```
  14222. *
  14223. * @augments EventDispatcher
  14224. */
  14225. class BufferGeometry extends EventDispatcher {
  14226. /**
  14227. * Constructs a new geometry.
  14228. */
  14229. constructor() {
  14230. super();
  14231. /**
  14232. * This flag can be used for type testing.
  14233. *
  14234. * @type {boolean}
  14235. * @readonly
  14236. * @default true
  14237. */
  14238. this.isBufferGeometry = true;
  14239. /**
  14240. * The ID of the geometry.
  14241. *
  14242. * @name BufferGeometry#id
  14243. * @type {number}
  14244. * @readonly
  14245. */
  14246. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14247. /**
  14248. * The UUID of the geometry.
  14249. *
  14250. * @type {string}
  14251. * @readonly
  14252. */
  14253. this.uuid = generateUUID();
  14254. /**
  14255. * The name of the geometry.
  14256. *
  14257. * @type {string}
  14258. */
  14259. this.name = '';
  14260. this.type = 'BufferGeometry';
  14261. /**
  14262. * Allows for vertices to be re-used across multiple triangles; this is
  14263. * called using "indexed triangles". Each triangle is associated with the
  14264. * indices of three vertices. This attribute therefore stores the index of
  14265. * each vertex for each triangular face. If this attribute is not set, the
  14266. * renderer assumes that each three contiguous positions represent a single triangle.
  14267. *
  14268. * @type {?BufferAttribute}
  14269. * @default null
  14270. */
  14271. this.index = null;
  14272. /**
  14273. * A (storage) buffer attribute which was generated with a compute shader and
  14274. * now defines indirect draw calls.
  14275. *
  14276. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14277. *
  14278. * @type {?BufferAttribute}
  14279. * @default null
  14280. */
  14281. this.indirect = null;
  14282. /**
  14283. * The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14284. *
  14285. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14286. *
  14287. * @type {number|Array<number>}
  14288. * @default 0
  14289. */
  14290. this.indirectOffset = 0;
  14291. /**
  14292. * This dictionary has as id the name of the attribute to be set and as value
  14293. * the buffer attribute to set it to. Rather than accessing this property directly,
  14294. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14295. *
  14296. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14297. */
  14298. this.attributes = {};
  14299. /**
  14300. * This dictionary holds the morph targets of the geometry.
  14301. *
  14302. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14303. * be changed. You will have to call `dispose()`, and create a new geometry instance.
  14304. *
  14305. * @type {Object}
  14306. */
  14307. this.morphAttributes = {};
  14308. /**
  14309. * Used to control the morph target behavior; when set to `true`, the morph
  14310. * target data is treated as relative offsets, rather than as absolute
  14311. * positions/normals.
  14312. *
  14313. * @type {boolean}
  14314. * @default false
  14315. */
  14316. this.morphTargetsRelative = false;
  14317. /**
  14318. * Split the geometry into groups, each of which will be rendered in a
  14319. * separate draw call. This allows an array of materials to be used with the geometry.
  14320. *
  14321. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14322. *
  14323. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14324. * indices, and must not leave vertices or indices unused.
  14325. *
  14326. * @type {Array<Object>}
  14327. */
  14328. this.groups = [];
  14329. /**
  14330. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14331. *
  14332. * @type {?Box3}
  14333. * @default null
  14334. */
  14335. this.boundingBox = null;
  14336. /**
  14337. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14338. *
  14339. * @type {?Sphere}
  14340. * @default null
  14341. */
  14342. this.boundingSphere = null;
  14343. /**
  14344. * Determines the part of the geometry to render. This should not be set directly,
  14345. * instead use `setDrawRange()`.
  14346. *
  14347. * @type {{start:number,count:number}}
  14348. */
  14349. this.drawRange = { start: 0, count: Infinity };
  14350. /**
  14351. * An object that can be used to store custom data about the geometry.
  14352. * It should not hold references to functions as these will not be cloned.
  14353. *
  14354. * @type {Object}
  14355. */
  14356. this.userData = {};
  14357. }
  14358. /**
  14359. * Returns the index of this geometry.
  14360. *
  14361. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14362. */
  14363. getIndex() {
  14364. return this.index;
  14365. }
  14366. /**
  14367. * Sets the given index to this geometry.
  14368. *
  14369. * @param {Array<number>|BufferAttribute} index - The index to set.
  14370. * @return {BufferGeometry} A reference to this instance.
  14371. */
  14372. setIndex( index ) {
  14373. if ( Array.isArray( index ) ) {
  14374. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14375. } else {
  14376. this.index = index;
  14377. }
  14378. return this;
  14379. }
  14380. /**
  14381. * Sets the given indirect attribute to this geometry.
  14382. *
  14383. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14384. * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset.
  14385. * @return {BufferGeometry} A reference to this instance.
  14386. */
  14387. setIndirect( indirect, indirectOffset = 0 ) {
  14388. this.indirect = indirect;
  14389. this.indirectOffset = indirectOffset;
  14390. return this;
  14391. }
  14392. /**
  14393. * Returns the indirect attribute of this geometry.
  14394. *
  14395. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14396. */
  14397. getIndirect() {
  14398. return this.indirect;
  14399. }
  14400. /**
  14401. * Returns the buffer attribute for the given name.
  14402. *
  14403. * @param {string} name - The attribute name.
  14404. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14405. * Returns `undefined` if not attribute has been found.
  14406. */
  14407. getAttribute( name ) {
  14408. return this.attributes[ name ];
  14409. }
  14410. /**
  14411. * Sets the given attribute for the given name.
  14412. *
  14413. * @param {string} name - The attribute name.
  14414. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14415. * @return {BufferGeometry} A reference to this instance.
  14416. */
  14417. setAttribute( name, attribute ) {
  14418. this.attributes[ name ] = attribute;
  14419. return this;
  14420. }
  14421. /**
  14422. * Deletes the attribute for the given name.
  14423. *
  14424. * @param {string} name - The attribute name to delete.
  14425. * @return {BufferGeometry} A reference to this instance.
  14426. */
  14427. deleteAttribute( name ) {
  14428. delete this.attributes[ name ];
  14429. return this;
  14430. }
  14431. /**
  14432. * Returns `true` if this geometry has an attribute for the given name.
  14433. *
  14434. * @param {string} name - The attribute name.
  14435. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14436. */
  14437. hasAttribute( name ) {
  14438. return this.attributes[ name ] !== undefined;
  14439. }
  14440. /**
  14441. * Adds a group to this geometry.
  14442. *
  14443. * @param {number} start - The first element in this draw call. That is the first
  14444. * vertex for non-indexed geometry, otherwise the first triangle index.
  14445. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14446. * @param {number} [materialIndex=0] - The material array index to use.
  14447. */
  14448. addGroup( start, count, materialIndex = 0 ) {
  14449. this.groups.push( {
  14450. start: start,
  14451. count: count,
  14452. materialIndex: materialIndex
  14453. } );
  14454. }
  14455. /**
  14456. * Clears all groups.
  14457. */
  14458. clearGroups() {
  14459. this.groups = [];
  14460. }
  14461. /**
  14462. * Sets the draw range for this geometry.
  14463. *
  14464. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14465. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14466. * For indexed BufferGeometry, `count` is the number of indices to render.
  14467. */
  14468. setDrawRange( start, count ) {
  14469. this.drawRange.start = start;
  14470. this.drawRange.count = count;
  14471. }
  14472. /**
  14473. * Applies the given 4x4 transformation matrix to the geometry.
  14474. *
  14475. * @param {Matrix4} matrix - The matrix to apply.
  14476. * @return {BufferGeometry} A reference to this instance.
  14477. */
  14478. applyMatrix4( matrix ) {
  14479. const position = this.attributes.position;
  14480. if ( position !== undefined ) {
  14481. position.applyMatrix4( matrix );
  14482. position.needsUpdate = true;
  14483. }
  14484. const normal = this.attributes.normal;
  14485. if ( normal !== undefined ) {
  14486. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14487. normal.applyNormalMatrix( normalMatrix );
  14488. normal.needsUpdate = true;
  14489. }
  14490. const tangent = this.attributes.tangent;
  14491. if ( tangent !== undefined ) {
  14492. tangent.transformDirection( matrix );
  14493. tangent.needsUpdate = true;
  14494. }
  14495. if ( this.boundingBox !== null ) {
  14496. this.computeBoundingBox();
  14497. }
  14498. if ( this.boundingSphere !== null ) {
  14499. this.computeBoundingSphere();
  14500. }
  14501. return this;
  14502. }
  14503. /**
  14504. * Applies the rotation represented by the Quaternion to the geometry.
  14505. *
  14506. * @param {Quaternion} q - The Quaternion to apply.
  14507. * @return {BufferGeometry} A reference to this instance.
  14508. */
  14509. applyQuaternion( q ) {
  14510. _m1$2.makeRotationFromQuaternion( q );
  14511. this.applyMatrix4( _m1$2 );
  14512. return this;
  14513. }
  14514. /**
  14515. * Rotates the geometry about the X axis. This is typically done as a one time
  14516. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14517. * real-time mesh rotation.
  14518. *
  14519. * @param {number} angle - The angle in radians.
  14520. * @return {BufferGeometry} A reference to this instance.
  14521. */
  14522. rotateX( angle ) {
  14523. // rotate geometry around world x-axis
  14524. _m1$2.makeRotationX( angle );
  14525. this.applyMatrix4( _m1$2 );
  14526. return this;
  14527. }
  14528. /**
  14529. * Rotates the geometry about the Y axis. This is typically done as a one time
  14530. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14531. * real-time mesh rotation.
  14532. *
  14533. * @param {number} angle - The angle in radians.
  14534. * @return {BufferGeometry} A reference to this instance.
  14535. */
  14536. rotateY( angle ) {
  14537. // rotate geometry around world y-axis
  14538. _m1$2.makeRotationY( angle );
  14539. this.applyMatrix4( _m1$2 );
  14540. return this;
  14541. }
  14542. /**
  14543. * Rotates the geometry about the Z axis. This is typically done as a one time
  14544. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14545. * real-time mesh rotation.
  14546. *
  14547. * @param {number} angle - The angle in radians.
  14548. * @return {BufferGeometry} A reference to this instance.
  14549. */
  14550. rotateZ( angle ) {
  14551. // rotate geometry around world z-axis
  14552. _m1$2.makeRotationZ( angle );
  14553. this.applyMatrix4( _m1$2 );
  14554. return this;
  14555. }
  14556. /**
  14557. * Translates the geometry. This is typically done as a one time
  14558. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14559. * real-time mesh rotation.
  14560. *
  14561. * @param {number} x - The x offset.
  14562. * @param {number} y - The y offset.
  14563. * @param {number} z - The z offset.
  14564. * @return {BufferGeometry} A reference to this instance.
  14565. */
  14566. translate( x, y, z ) {
  14567. // translate geometry
  14568. _m1$2.makeTranslation( x, y, z );
  14569. this.applyMatrix4( _m1$2 );
  14570. return this;
  14571. }
  14572. /**
  14573. * Scales the geometry. This is typically done as a one time
  14574. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14575. * real-time mesh rotation.
  14576. *
  14577. * @param {number} x - The x scale.
  14578. * @param {number} y - The y scale.
  14579. * @param {number} z - The z scale.
  14580. * @return {BufferGeometry} A reference to this instance.
  14581. */
  14582. scale( x, y, z ) {
  14583. // scale geometry
  14584. _m1$2.makeScale( x, y, z );
  14585. this.applyMatrix4( _m1$2 );
  14586. return this;
  14587. }
  14588. /**
  14589. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14590. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14591. * real-time mesh rotation.
  14592. *
  14593. * @param {Vector3} vector - The target point.
  14594. * @return {BufferGeometry} A reference to this instance.
  14595. */
  14596. lookAt( vector ) {
  14597. _obj.lookAt( vector );
  14598. _obj.updateMatrix();
  14599. this.applyMatrix4( _obj.matrix );
  14600. return this;
  14601. }
  14602. /**
  14603. * Center the geometry based on its bounding box.
  14604. *
  14605. * @return {BufferGeometry} A reference to this instance.
  14606. */
  14607. center() {
  14608. this.computeBoundingBox();
  14609. this.boundingBox.getCenter( _offset ).negate();
  14610. this.translate( _offset.x, _offset.y, _offset.z );
  14611. return this;
  14612. }
  14613. /**
  14614. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14615. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14616. * set to `0`.
  14617. *
  14618. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14619. * data from the array. The length of the array must match the vertex count.
  14620. *
  14621. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14622. * @return {BufferGeometry} A reference to this instance.
  14623. */
  14624. setFromPoints( points ) {
  14625. const positionAttribute = this.getAttribute( 'position' );
  14626. if ( positionAttribute === undefined ) {
  14627. const position = [];
  14628. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14629. const point = points[ i ];
  14630. position.push( point.x, point.y, point.z || 0 );
  14631. }
  14632. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14633. } else {
  14634. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14635. for ( let i = 0; i < l; i ++ ) {
  14636. const point = points[ i ];
  14637. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14638. }
  14639. if ( points.length > positionAttribute.count ) {
  14640. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14641. }
  14642. positionAttribute.needsUpdate = true;
  14643. }
  14644. return this;
  14645. }
  14646. /**
  14647. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14648. * The bounding box is not computed by the engine; it must be computed by your app.
  14649. * You may need to recompute the bounding box if the geometry vertices are modified.
  14650. */
  14651. computeBoundingBox() {
  14652. if ( this.boundingBox === null ) {
  14653. this.boundingBox = new Box3();
  14654. }
  14655. const position = this.attributes.position;
  14656. const morphAttributesPosition = this.morphAttributes.position;
  14657. if ( position && position.isGLBufferAttribute ) {
  14658. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14659. this.boundingBox.set(
  14660. new Vector3( - Infinity, - Infinity, - Infinity ),
  14661. new Vector3( + Infinity, + Infinity, + Infinity )
  14662. );
  14663. return;
  14664. }
  14665. if ( position !== undefined ) {
  14666. this.boundingBox.setFromBufferAttribute( position );
  14667. // process morph attributes if present
  14668. if ( morphAttributesPosition ) {
  14669. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14670. const morphAttribute = morphAttributesPosition[ i ];
  14671. _box$2.setFromBufferAttribute( morphAttribute );
  14672. if ( this.morphTargetsRelative ) {
  14673. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14674. this.boundingBox.expandByPoint( _vector$8 );
  14675. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14676. this.boundingBox.expandByPoint( _vector$8 );
  14677. } else {
  14678. this.boundingBox.expandByPoint( _box$2.min );
  14679. this.boundingBox.expandByPoint( _box$2.max );
  14680. }
  14681. }
  14682. }
  14683. } else {
  14684. this.boundingBox.makeEmpty();
  14685. }
  14686. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14687. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14688. }
  14689. }
  14690. /**
  14691. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14692. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14693. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14694. */
  14695. computeBoundingSphere() {
  14696. if ( this.boundingSphere === null ) {
  14697. this.boundingSphere = new Sphere();
  14698. }
  14699. const position = this.attributes.position;
  14700. const morphAttributesPosition = this.morphAttributes.position;
  14701. if ( position && position.isGLBufferAttribute ) {
  14702. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14703. this.boundingSphere.set( new Vector3(), Infinity );
  14704. return;
  14705. }
  14706. if ( position ) {
  14707. // first, find the center of the bounding sphere
  14708. const center = this.boundingSphere.center;
  14709. _box$2.setFromBufferAttribute( position );
  14710. // process morph attributes if present
  14711. if ( morphAttributesPosition ) {
  14712. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14713. const morphAttribute = morphAttributesPosition[ i ];
  14714. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14715. if ( this.morphTargetsRelative ) {
  14716. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14717. _box$2.expandByPoint( _vector$8 );
  14718. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14719. _box$2.expandByPoint( _vector$8 );
  14720. } else {
  14721. _box$2.expandByPoint( _boxMorphTargets.min );
  14722. _box$2.expandByPoint( _boxMorphTargets.max );
  14723. }
  14724. }
  14725. }
  14726. _box$2.getCenter( center );
  14727. // second, try to find a boundingSphere with a radius smaller than the
  14728. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14729. let maxRadiusSq = 0;
  14730. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14731. _vector$8.fromBufferAttribute( position, i );
  14732. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14733. }
  14734. // process morph attributes if present
  14735. if ( morphAttributesPosition ) {
  14736. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14737. const morphAttribute = morphAttributesPosition[ i ];
  14738. const morphTargetsRelative = this.morphTargetsRelative;
  14739. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14740. _vector$8.fromBufferAttribute( morphAttribute, j );
  14741. if ( morphTargetsRelative ) {
  14742. _offset.fromBufferAttribute( position, j );
  14743. _vector$8.add( _offset );
  14744. }
  14745. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14746. }
  14747. }
  14748. }
  14749. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14750. if ( isNaN( this.boundingSphere.radius ) ) {
  14751. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14752. }
  14753. }
  14754. }
  14755. /**
  14756. * Calculates and adds a tangent attribute to this geometry.
  14757. *
  14758. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14759. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14760. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14761. */
  14762. computeTangents() {
  14763. const index = this.index;
  14764. const attributes = this.attributes;
  14765. // based on http://www.terathon.com/code/tangent.html
  14766. // (per vertex tangents)
  14767. if ( index === null ||
  14768. attributes.position === undefined ||
  14769. attributes.normal === undefined ||
  14770. attributes.uv === undefined ) {
  14771. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14772. return;
  14773. }
  14774. const positionAttribute = attributes.position;
  14775. const normalAttribute = attributes.normal;
  14776. const uvAttribute = attributes.uv;
  14777. if ( this.hasAttribute( 'tangent' ) === false ) {
  14778. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14779. }
  14780. const tangentAttribute = this.getAttribute( 'tangent' );
  14781. const tan1 = [], tan2 = [];
  14782. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14783. tan1[ i ] = new Vector3();
  14784. tan2[ i ] = new Vector3();
  14785. }
  14786. const vA = new Vector3(),
  14787. vB = new Vector3(),
  14788. vC = new Vector3(),
  14789. uvA = new Vector2(),
  14790. uvB = new Vector2(),
  14791. uvC = new Vector2(),
  14792. sdir = new Vector3(),
  14793. tdir = new Vector3();
  14794. function handleTriangle( a, b, c ) {
  14795. vA.fromBufferAttribute( positionAttribute, a );
  14796. vB.fromBufferAttribute( positionAttribute, b );
  14797. vC.fromBufferAttribute( positionAttribute, c );
  14798. uvA.fromBufferAttribute( uvAttribute, a );
  14799. uvB.fromBufferAttribute( uvAttribute, b );
  14800. uvC.fromBufferAttribute( uvAttribute, c );
  14801. vB.sub( vA );
  14802. vC.sub( vA );
  14803. uvB.sub( uvA );
  14804. uvC.sub( uvA );
  14805. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14806. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14807. if ( ! isFinite( r ) ) return;
  14808. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14809. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14810. tan1[ a ].add( sdir );
  14811. tan1[ b ].add( sdir );
  14812. tan1[ c ].add( sdir );
  14813. tan2[ a ].add( tdir );
  14814. tan2[ b ].add( tdir );
  14815. tan2[ c ].add( tdir );
  14816. }
  14817. let groups = this.groups;
  14818. if ( groups.length === 0 ) {
  14819. groups = [ {
  14820. start: 0,
  14821. count: index.count
  14822. } ];
  14823. }
  14824. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14825. const group = groups[ i ];
  14826. const start = group.start;
  14827. const count = group.count;
  14828. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14829. handleTriangle(
  14830. index.getX( j + 0 ),
  14831. index.getX( j + 1 ),
  14832. index.getX( j + 2 )
  14833. );
  14834. }
  14835. }
  14836. const tmp = new Vector3(), tmp2 = new Vector3();
  14837. const n = new Vector3(), n2 = new Vector3();
  14838. function handleVertex( v ) {
  14839. n.fromBufferAttribute( normalAttribute, v );
  14840. n2.copy( n );
  14841. const t = tan1[ v ];
  14842. // Gram-Schmidt orthogonalize
  14843. tmp.copy( t );
  14844. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14845. // Calculate handedness
  14846. tmp2.crossVectors( n2, t );
  14847. const test = tmp2.dot( tan2[ v ] );
  14848. const w = ( test < 0.0 ) ? -1 : 1.0;
  14849. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14850. }
  14851. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14852. const group = groups[ i ];
  14853. const start = group.start;
  14854. const count = group.count;
  14855. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14856. handleVertex( index.getX( j + 0 ) );
  14857. handleVertex( index.getX( j + 1 ) );
  14858. handleVertex( index.getX( j + 2 ) );
  14859. }
  14860. }
  14861. }
  14862. /**
  14863. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14864. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14865. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14866. * to be the same as the face normal.
  14867. */
  14868. computeVertexNormals() {
  14869. const index = this.index;
  14870. const positionAttribute = this.getAttribute( 'position' );
  14871. if ( positionAttribute !== undefined ) {
  14872. let normalAttribute = this.getAttribute( 'normal' );
  14873. if ( normalAttribute === undefined ) {
  14874. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14875. this.setAttribute( 'normal', normalAttribute );
  14876. } else {
  14877. // reset existing normals to zero
  14878. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14879. normalAttribute.setXYZ( i, 0, 0, 0 );
  14880. }
  14881. }
  14882. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14883. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14884. const cb = new Vector3(), ab = new Vector3();
  14885. // indexed elements
  14886. if ( index ) {
  14887. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14888. const vA = index.getX( i + 0 );
  14889. const vB = index.getX( i + 1 );
  14890. const vC = index.getX( i + 2 );
  14891. pA.fromBufferAttribute( positionAttribute, vA );
  14892. pB.fromBufferAttribute( positionAttribute, vB );
  14893. pC.fromBufferAttribute( positionAttribute, vC );
  14894. cb.subVectors( pC, pB );
  14895. ab.subVectors( pA, pB );
  14896. cb.cross( ab );
  14897. nA.fromBufferAttribute( normalAttribute, vA );
  14898. nB.fromBufferAttribute( normalAttribute, vB );
  14899. nC.fromBufferAttribute( normalAttribute, vC );
  14900. nA.add( cb );
  14901. nB.add( cb );
  14902. nC.add( cb );
  14903. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14904. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14905. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14906. }
  14907. } else {
  14908. // non-indexed elements (unconnected triangle soup)
  14909. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14910. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14911. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14912. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14913. cb.subVectors( pC, pB );
  14914. ab.subVectors( pA, pB );
  14915. cb.cross( ab );
  14916. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14917. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14918. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14919. }
  14920. }
  14921. this.normalizeNormals();
  14922. normalAttribute.needsUpdate = true;
  14923. }
  14924. }
  14925. /**
  14926. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14927. * correct lighting on the geometry surfaces.
  14928. */
  14929. normalizeNormals() {
  14930. const normals = this.attributes.normal;
  14931. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14932. _vector$8.fromBufferAttribute( normals, i );
  14933. _vector$8.normalize();
  14934. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14935. }
  14936. }
  14937. /**
  14938. * Return a new non-index version of this indexed geometry. If the geometry
  14939. * is already non-indexed, the method is a NOOP.
  14940. *
  14941. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14942. */
  14943. toNonIndexed() {
  14944. function convertBufferAttribute( attribute, indices ) {
  14945. const array = attribute.array;
  14946. const itemSize = attribute.itemSize;
  14947. const normalized = attribute.normalized;
  14948. const array2 = new array.constructor( indices.length * itemSize );
  14949. let index = 0, index2 = 0;
  14950. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14951. if ( attribute.isInterleavedBufferAttribute ) {
  14952. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14953. } else {
  14954. index = indices[ i ] * itemSize;
  14955. }
  14956. for ( let j = 0; j < itemSize; j ++ ) {
  14957. array2[ index2 ++ ] = array[ index ++ ];
  14958. }
  14959. }
  14960. return new BufferAttribute( array2, itemSize, normalized );
  14961. }
  14962. //
  14963. if ( this.index === null ) {
  14964. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14965. return this;
  14966. }
  14967. const geometry2 = new BufferGeometry();
  14968. const indices = this.index.array;
  14969. const attributes = this.attributes;
  14970. // attributes
  14971. for ( const name in attributes ) {
  14972. const attribute = attributes[ name ];
  14973. const newAttribute = convertBufferAttribute( attribute, indices );
  14974. geometry2.setAttribute( name, newAttribute );
  14975. }
  14976. // morph attributes
  14977. const morphAttributes = this.morphAttributes;
  14978. for ( const name in morphAttributes ) {
  14979. const morphArray = [];
  14980. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14981. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14982. const attribute = morphAttribute[ i ];
  14983. const newAttribute = convertBufferAttribute( attribute, indices );
  14984. morphArray.push( newAttribute );
  14985. }
  14986. geometry2.morphAttributes[ name ] = morphArray;
  14987. }
  14988. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14989. // groups
  14990. const groups = this.groups;
  14991. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14992. const group = groups[ i ];
  14993. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14994. }
  14995. return geometry2;
  14996. }
  14997. /**
  14998. * Serializes the geometry into JSON.
  14999. *
  15000. * @return {Object} A JSON object representing the serialized geometry.
  15001. */
  15002. toJSON() {
  15003. const data = {
  15004. metadata: {
  15005. version: 4.7,
  15006. type: 'BufferGeometry',
  15007. generator: 'BufferGeometry.toJSON'
  15008. }
  15009. };
  15010. // standard BufferGeometry serialization
  15011. data.uuid = this.uuid;
  15012. data.type = this.type;
  15013. if ( this.name !== '' ) data.name = this.name;
  15014. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15015. if ( this.parameters !== undefined ) {
  15016. const parameters = this.parameters;
  15017. for ( const key in parameters ) {
  15018. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15019. }
  15020. return data;
  15021. }
  15022. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15023. data.data = { attributes: {} };
  15024. const index = this.index;
  15025. if ( index !== null ) {
  15026. data.data.index = {
  15027. type: index.array.constructor.name,
  15028. array: Array.prototype.slice.call( index.array )
  15029. };
  15030. }
  15031. const attributes = this.attributes;
  15032. for ( const key in attributes ) {
  15033. const attribute = attributes[ key ];
  15034. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15035. }
  15036. const morphAttributes = {};
  15037. let hasMorphAttributes = false;
  15038. for ( const key in this.morphAttributes ) {
  15039. const attributeArray = this.morphAttributes[ key ];
  15040. const array = [];
  15041. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15042. const attribute = attributeArray[ i ];
  15043. array.push( attribute.toJSON( data.data ) );
  15044. }
  15045. if ( array.length > 0 ) {
  15046. morphAttributes[ key ] = array;
  15047. hasMorphAttributes = true;
  15048. }
  15049. }
  15050. if ( hasMorphAttributes ) {
  15051. data.data.morphAttributes = morphAttributes;
  15052. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15053. }
  15054. const groups = this.groups;
  15055. if ( groups.length > 0 ) {
  15056. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15057. }
  15058. const boundingSphere = this.boundingSphere;
  15059. if ( boundingSphere !== null ) {
  15060. data.data.boundingSphere = boundingSphere.toJSON();
  15061. }
  15062. return data;
  15063. }
  15064. /**
  15065. * Returns a new geometry with copied values from this instance.
  15066. *
  15067. * @return {BufferGeometry} A clone of this instance.
  15068. */
  15069. clone() {
  15070. return new this.constructor().copy( this );
  15071. }
  15072. /**
  15073. * Copies the values of the given geometry to this instance.
  15074. *
  15075. * @param {BufferGeometry} source - The geometry to copy.
  15076. * @return {BufferGeometry} A reference to this instance.
  15077. */
  15078. copy( source ) {
  15079. // reset
  15080. this.index = null;
  15081. this.attributes = {};
  15082. this.morphAttributes = {};
  15083. this.groups = [];
  15084. this.boundingBox = null;
  15085. this.boundingSphere = null;
  15086. // used for storing cloned, shared data
  15087. const data = {};
  15088. // name
  15089. this.name = source.name;
  15090. // index
  15091. const index = source.index;
  15092. if ( index !== null ) {
  15093. this.setIndex( index.clone() );
  15094. }
  15095. // attributes
  15096. const attributes = source.attributes;
  15097. for ( const name in attributes ) {
  15098. const attribute = attributes[ name ];
  15099. this.setAttribute( name, attribute.clone( data ) );
  15100. }
  15101. // morph attributes
  15102. const morphAttributes = source.morphAttributes;
  15103. for ( const name in morphAttributes ) {
  15104. const array = [];
  15105. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15106. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15107. array.push( morphAttribute[ i ].clone( data ) );
  15108. }
  15109. this.morphAttributes[ name ] = array;
  15110. }
  15111. this.morphTargetsRelative = source.morphTargetsRelative;
  15112. // groups
  15113. const groups = source.groups;
  15114. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15115. const group = groups[ i ];
  15116. this.addGroup( group.start, group.count, group.materialIndex );
  15117. }
  15118. // bounding box
  15119. const boundingBox = source.boundingBox;
  15120. if ( boundingBox !== null ) {
  15121. this.boundingBox = boundingBox.clone();
  15122. }
  15123. // bounding sphere
  15124. const boundingSphere = source.boundingSphere;
  15125. if ( boundingSphere !== null ) {
  15126. this.boundingSphere = boundingSphere.clone();
  15127. }
  15128. // draw range
  15129. this.drawRange.start = source.drawRange.start;
  15130. this.drawRange.count = source.drawRange.count;
  15131. // user data
  15132. this.userData = source.userData;
  15133. return this;
  15134. }
  15135. /**
  15136. * Frees the GPU-related resources allocated by this instance. Call this
  15137. * method whenever this instance is no longer used in your app.
  15138. *
  15139. * @fires BufferGeometry#dispose
  15140. */
  15141. dispose() {
  15142. this.dispatchEvent( { type: 'dispose' } );
  15143. }
  15144. }
  15145. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15146. const _ray$3 = /*@__PURE__*/ new Ray();
  15147. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15148. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15149. const _vA$1 = /*@__PURE__*/ new Vector3();
  15150. const _vB$1 = /*@__PURE__*/ new Vector3();
  15151. const _vC$1 = /*@__PURE__*/ new Vector3();
  15152. const _tempA = /*@__PURE__*/ new Vector3();
  15153. const _morphA = /*@__PURE__*/ new Vector3();
  15154. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15155. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15156. /**
  15157. * Class representing triangular polygon mesh based objects.
  15158. *
  15159. * ```js
  15160. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15161. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15162. * const mesh = new THREE.Mesh( geometry, material );
  15163. * scene.add( mesh );
  15164. * ```
  15165. *
  15166. * @augments Object3D
  15167. */
  15168. class Mesh extends Object3D {
  15169. /**
  15170. * Constructs a new mesh.
  15171. *
  15172. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15173. * @param {Material|Array<Material>} [material] - The mesh material.
  15174. */
  15175. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15176. super();
  15177. /**
  15178. * This flag can be used for type testing.
  15179. *
  15180. * @type {boolean}
  15181. * @readonly
  15182. * @default true
  15183. */
  15184. this.isMesh = true;
  15185. this.type = 'Mesh';
  15186. /**
  15187. * The mesh geometry.
  15188. *
  15189. * @type {BufferGeometry}
  15190. */
  15191. this.geometry = geometry;
  15192. /**
  15193. * The mesh material.
  15194. *
  15195. * @type {Material|Array<Material>}
  15196. * @default MeshBasicMaterial
  15197. */
  15198. this.material = material;
  15199. /**
  15200. * A dictionary representing the morph targets in the geometry. The key is the
  15201. * morph targets name, the value its attribute index. This member is `undefined`
  15202. * by default and only set when morph targets are detected in the geometry.
  15203. *
  15204. * @type {Object<string,number>|undefined}
  15205. * @default undefined
  15206. */
  15207. this.morphTargetDictionary = undefined;
  15208. /**
  15209. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15210. * is applied. This member is `undefined` by default and only set when morph targets are
  15211. * detected in the geometry.
  15212. *
  15213. * @type {Array<number>|undefined}
  15214. * @default undefined
  15215. */
  15216. this.morphTargetInfluences = undefined;
  15217. /**
  15218. * The number of instances of this mesh.
  15219. * Can only be used with {@link WebGPURenderer}.
  15220. *
  15221. * @type {number}
  15222. * @default 1
  15223. */
  15224. this.count = 1;
  15225. this.updateMorphTargets();
  15226. }
  15227. copy( source, recursive ) {
  15228. super.copy( source, recursive );
  15229. if ( source.morphTargetInfluences !== undefined ) {
  15230. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15231. }
  15232. if ( source.morphTargetDictionary !== undefined ) {
  15233. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15234. }
  15235. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15236. this.geometry = source.geometry;
  15237. return this;
  15238. }
  15239. /**
  15240. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15241. * to make sure existing morph targets can influence this 3D object.
  15242. */
  15243. updateMorphTargets() {
  15244. const geometry = this.geometry;
  15245. const morphAttributes = geometry.morphAttributes;
  15246. const keys = Object.keys( morphAttributes );
  15247. if ( keys.length > 0 ) {
  15248. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15249. if ( morphAttribute !== undefined ) {
  15250. this.morphTargetInfluences = [];
  15251. this.morphTargetDictionary = {};
  15252. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15253. const name = morphAttribute[ m ].name || String( m );
  15254. this.morphTargetInfluences.push( 0 );
  15255. this.morphTargetDictionary[ name ] = m;
  15256. }
  15257. }
  15258. }
  15259. }
  15260. /**
  15261. * Returns the local-space position of the vertex at the given index, taking into
  15262. * account the current animation state of both morph targets and skinning.
  15263. *
  15264. * @param {number} index - The vertex index.
  15265. * @param {Vector3} target - The target object that is used to store the method's result.
  15266. * @return {Vector3} The vertex position in local space.
  15267. */
  15268. getVertexPosition( index, target ) {
  15269. const geometry = this.geometry;
  15270. const position = geometry.attributes.position;
  15271. const morphPosition = geometry.morphAttributes.position;
  15272. const morphTargetsRelative = geometry.morphTargetsRelative;
  15273. target.fromBufferAttribute( position, index );
  15274. const morphInfluences = this.morphTargetInfluences;
  15275. if ( morphPosition && morphInfluences ) {
  15276. _morphA.set( 0, 0, 0 );
  15277. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15278. const influence = morphInfluences[ i ];
  15279. const morphAttribute = morphPosition[ i ];
  15280. if ( influence === 0 ) continue;
  15281. _tempA.fromBufferAttribute( morphAttribute, index );
  15282. if ( morphTargetsRelative ) {
  15283. _morphA.addScaledVector( _tempA, influence );
  15284. } else {
  15285. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15286. }
  15287. }
  15288. target.add( _morphA );
  15289. }
  15290. return target;
  15291. }
  15292. /**
  15293. * Computes intersection points between a casted ray and this line.
  15294. *
  15295. * @param {Raycaster} raycaster - The raycaster.
  15296. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15297. */
  15298. raycast( raycaster, intersects ) {
  15299. const geometry = this.geometry;
  15300. const material = this.material;
  15301. const matrixWorld = this.matrixWorld;
  15302. if ( material === undefined ) return;
  15303. // test with bounding sphere in world space
  15304. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15305. _sphere$6.copy( geometry.boundingSphere );
  15306. _sphere$6.applyMatrix4( matrixWorld );
  15307. // check distance from ray origin to bounding sphere
  15308. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15309. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15310. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15311. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15312. }
  15313. // convert ray to local space of mesh
  15314. _inverseMatrix$3.copy( matrixWorld ).invert();
  15315. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15316. // test with bounding box in local space
  15317. if ( geometry.boundingBox !== null ) {
  15318. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15319. }
  15320. // test for intersections with geometry
  15321. this._computeIntersections( raycaster, intersects, _ray$3 );
  15322. }
  15323. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15324. let intersection;
  15325. const geometry = this.geometry;
  15326. const material = this.material;
  15327. const index = geometry.index;
  15328. const position = geometry.attributes.position;
  15329. const uv = geometry.attributes.uv;
  15330. const uv1 = geometry.attributes.uv1;
  15331. const normal = geometry.attributes.normal;
  15332. const groups = geometry.groups;
  15333. const drawRange = geometry.drawRange;
  15334. if ( index !== null ) {
  15335. // indexed buffer geometry
  15336. if ( Array.isArray( material ) ) {
  15337. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15338. const group = groups[ i ];
  15339. const groupMaterial = material[ group.materialIndex ];
  15340. const start = Math.max( group.start, drawRange.start );
  15341. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15342. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15343. const a = index.getX( j );
  15344. const b = index.getX( j + 1 );
  15345. const c = index.getX( j + 2 );
  15346. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15347. if ( intersection ) {
  15348. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15349. intersection.face.materialIndex = group.materialIndex;
  15350. intersects.push( intersection );
  15351. }
  15352. }
  15353. }
  15354. } else {
  15355. const start = Math.max( 0, drawRange.start );
  15356. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15357. for ( let i = start, il = end; i < il; i += 3 ) {
  15358. const a = index.getX( i );
  15359. const b = index.getX( i + 1 );
  15360. const c = index.getX( i + 2 );
  15361. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15362. if ( intersection ) {
  15363. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15364. intersects.push( intersection );
  15365. }
  15366. }
  15367. }
  15368. } else if ( position !== undefined ) {
  15369. // non-indexed buffer geometry
  15370. if ( Array.isArray( material ) ) {
  15371. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15372. const group = groups[ i ];
  15373. const groupMaterial = material[ group.materialIndex ];
  15374. const start = Math.max( group.start, drawRange.start );
  15375. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15376. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15377. const a = j;
  15378. const b = j + 1;
  15379. const c = j + 2;
  15380. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15381. if ( intersection ) {
  15382. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15383. intersection.face.materialIndex = group.materialIndex;
  15384. intersects.push( intersection );
  15385. }
  15386. }
  15387. }
  15388. } else {
  15389. const start = Math.max( 0, drawRange.start );
  15390. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15391. for ( let i = start, il = end; i < il; i += 3 ) {
  15392. const a = i;
  15393. const b = i + 1;
  15394. const c = i + 2;
  15395. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15396. if ( intersection ) {
  15397. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15398. intersects.push( intersection );
  15399. }
  15400. }
  15401. }
  15402. }
  15403. }
  15404. }
  15405. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15406. let intersect;
  15407. if ( material.side === BackSide ) {
  15408. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15409. } else {
  15410. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15411. }
  15412. if ( intersect === null ) return null;
  15413. _intersectionPointWorld.copy( point );
  15414. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15415. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15416. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15417. return {
  15418. distance: distance,
  15419. point: _intersectionPointWorld.clone(),
  15420. object: object
  15421. };
  15422. }
  15423. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15424. object.getVertexPosition( a, _vA$1 );
  15425. object.getVertexPosition( b, _vB$1 );
  15426. object.getVertexPosition( c, _vC$1 );
  15427. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15428. if ( intersection ) {
  15429. const barycoord = new Vector3();
  15430. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15431. if ( uv ) {
  15432. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15433. }
  15434. if ( uv1 ) {
  15435. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15436. }
  15437. if ( normal ) {
  15438. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15439. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15440. intersection.normal.multiplyScalar( -1 );
  15441. }
  15442. }
  15443. const face = {
  15444. a: a,
  15445. b: b,
  15446. c: c,
  15447. normal: new Vector3(),
  15448. materialIndex: 0
  15449. };
  15450. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15451. intersection.face = face;
  15452. intersection.barycoord = barycoord;
  15453. }
  15454. return intersection;
  15455. }
  15456. /**
  15457. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15458. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15459. * of the axes.
  15460. *
  15461. * ```js
  15462. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15463. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15464. * const cube = new THREE.Mesh( geometry, material );
  15465. * scene.add( cube );
  15466. * ```
  15467. *
  15468. * @augments BufferGeometry
  15469. * @demo scenes/geometry-browser.html#BoxGeometry
  15470. */
  15471. class BoxGeometry extends BufferGeometry {
  15472. /**
  15473. * Constructs a new box geometry.
  15474. *
  15475. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15476. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15477. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15478. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15479. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15480. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15481. */
  15482. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15483. super();
  15484. this.type = 'BoxGeometry';
  15485. /**
  15486. * Holds the constructor parameters that have been
  15487. * used to generate the geometry. Any modification
  15488. * after instantiation does not change the geometry.
  15489. *
  15490. * @type {Object}
  15491. */
  15492. this.parameters = {
  15493. width: width,
  15494. height: height,
  15495. depth: depth,
  15496. widthSegments: widthSegments,
  15497. heightSegments: heightSegments,
  15498. depthSegments: depthSegments
  15499. };
  15500. const scope = this;
  15501. // segments
  15502. widthSegments = Math.floor( widthSegments );
  15503. heightSegments = Math.floor( heightSegments );
  15504. depthSegments = Math.floor( depthSegments );
  15505. // buffers
  15506. const indices = [];
  15507. const vertices = [];
  15508. const normals = [];
  15509. const uvs = [];
  15510. // helper variables
  15511. let numberOfVertices = 0;
  15512. let groupStart = 0;
  15513. // build each side of the box geometry
  15514. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15515. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15516. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15517. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15518. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15519. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15520. // build geometry
  15521. this.setIndex( indices );
  15522. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15523. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15524. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15525. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15526. const segmentWidth = width / gridX;
  15527. const segmentHeight = height / gridY;
  15528. const widthHalf = width / 2;
  15529. const heightHalf = height / 2;
  15530. const depthHalf = depth / 2;
  15531. const gridX1 = gridX + 1;
  15532. const gridY1 = gridY + 1;
  15533. let vertexCounter = 0;
  15534. let groupCount = 0;
  15535. const vector = new Vector3();
  15536. // generate vertices, normals and uvs
  15537. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15538. const y = iy * segmentHeight - heightHalf;
  15539. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15540. const x = ix * segmentWidth - widthHalf;
  15541. // set values to correct vector component
  15542. vector[ u ] = x * udir;
  15543. vector[ v ] = y * vdir;
  15544. vector[ w ] = depthHalf;
  15545. // now apply vector to vertex buffer
  15546. vertices.push( vector.x, vector.y, vector.z );
  15547. // set values to correct vector component
  15548. vector[ u ] = 0;
  15549. vector[ v ] = 0;
  15550. vector[ w ] = depth > 0 ? 1 : -1;
  15551. // now apply vector to normal buffer
  15552. normals.push( vector.x, vector.y, vector.z );
  15553. // uvs
  15554. uvs.push( ix / gridX );
  15555. uvs.push( 1 - ( iy / gridY ) );
  15556. // counters
  15557. vertexCounter += 1;
  15558. }
  15559. }
  15560. // indices
  15561. // 1. you need three indices to draw a single face
  15562. // 2. a single segment consists of two faces
  15563. // 3. so we need to generate six (2*3) indices per segment
  15564. for ( let iy = 0; iy < gridY; iy ++ ) {
  15565. for ( let ix = 0; ix < gridX; ix ++ ) {
  15566. const a = numberOfVertices + ix + gridX1 * iy;
  15567. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15568. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15569. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15570. // faces
  15571. indices.push( a, b, d );
  15572. indices.push( b, c, d );
  15573. // increase counter
  15574. groupCount += 6;
  15575. }
  15576. }
  15577. // add a group to the geometry. this will ensure multi material support
  15578. scope.addGroup( groupStart, groupCount, materialIndex );
  15579. // calculate new start value for groups
  15580. groupStart += groupCount;
  15581. // update total number of vertices
  15582. numberOfVertices += vertexCounter;
  15583. }
  15584. }
  15585. copy( source ) {
  15586. super.copy( source );
  15587. this.parameters = Object.assign( {}, source.parameters );
  15588. return this;
  15589. }
  15590. /**
  15591. * Factory method for creating an instance of this class from the given
  15592. * JSON object.
  15593. *
  15594. * @param {Object} data - A JSON object representing the serialized geometry.
  15595. * @return {BoxGeometry} A new instance.
  15596. */
  15597. static fromJSON( data ) {
  15598. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15599. }
  15600. }
  15601. /**
  15602. * Provides utility functions for managing uniforms.
  15603. *
  15604. * @module UniformsUtils
  15605. */
  15606. /**
  15607. * Clones the given uniform definitions by performing a deep-copy. That means
  15608. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15609. * the cloned uniform will refer to a new object reference.
  15610. *
  15611. * @param {Object} src - An object representing uniform definitions.
  15612. * @return {Object} The cloned uniforms.
  15613. */
  15614. function cloneUniforms( src ) {
  15615. const dst = {};
  15616. for ( const u in src ) {
  15617. dst[ u ] = {};
  15618. for ( const p in src[ u ] ) {
  15619. const property = src[ u ][ p ];
  15620. if ( property && ( property.isColor ||
  15621. property.isMatrix3 || property.isMatrix4 ||
  15622. property.isVector2 || property.isVector3 || property.isVector4 ||
  15623. property.isTexture || property.isQuaternion ) ) {
  15624. if ( property.isRenderTargetTexture ) {
  15625. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15626. dst[ u ][ p ] = null;
  15627. } else {
  15628. dst[ u ][ p ] = property.clone();
  15629. }
  15630. } else if ( Array.isArray( property ) ) {
  15631. dst[ u ][ p ] = property.slice();
  15632. } else {
  15633. dst[ u ][ p ] = property;
  15634. }
  15635. }
  15636. }
  15637. return dst;
  15638. }
  15639. /**
  15640. * Merges the given uniform definitions into a single object. Since the
  15641. * method internally uses cloneUniforms(), it performs a deep-copy when
  15642. * producing the merged uniform definitions.
  15643. *
  15644. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15645. * @return {Object} The merged uniforms.
  15646. */
  15647. function mergeUniforms( uniforms ) {
  15648. const merged = {};
  15649. for ( let u = 0; u < uniforms.length; u ++ ) {
  15650. const tmp = cloneUniforms( uniforms[ u ] );
  15651. for ( const p in tmp ) {
  15652. merged[ p ] = tmp[ p ];
  15653. }
  15654. }
  15655. return merged;
  15656. }
  15657. function cloneUniformsGroups( src ) {
  15658. const dst = [];
  15659. for ( let u = 0; u < src.length; u ++ ) {
  15660. dst.push( src[ u ].clone() );
  15661. }
  15662. return dst;
  15663. }
  15664. function getUnlitUniformColorSpace( renderer ) {
  15665. const currentRenderTarget = renderer.getRenderTarget();
  15666. if ( currentRenderTarget === null ) {
  15667. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15668. return renderer.outputColorSpace;
  15669. }
  15670. // https://github.com/mrdoob/three.js/issues/27868
  15671. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15672. return currentRenderTarget.texture.colorSpace;
  15673. }
  15674. return ColorManagement.workingColorSpace;
  15675. }
  15676. // Legacy
  15677. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15678. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15679. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15680. /**
  15681. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15682. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15683. * effect not included with any of the built-in materials.
  15684. *
  15685. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15686. *
  15687. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15688. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15689. * you don't want that, use {@link RawShaderMaterial} instead.
  15690. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15691. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15692. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15693. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15694. * - The loop variable has to be *i*.
  15695. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15696. * value of *i* for the given iteration and can be used in preprocessor
  15697. * statements.
  15698. *
  15699. * ```js
  15700. * const material = new THREE.ShaderMaterial( {
  15701. * uniforms: {
  15702. * time: { value: 1.0 },
  15703. * resolution: { value: new THREE.Vector2() }
  15704. * },
  15705. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15706. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15707. * } );
  15708. * ```
  15709. *
  15710. * @augments Material
  15711. */
  15712. class ShaderMaterial extends Material {
  15713. /**
  15714. * Constructs a new shader material.
  15715. *
  15716. * @param {Object} [parameters] - An object with one or more properties
  15717. * defining the material's appearance. Any property of the material
  15718. * (including any property from inherited materials) can be passed
  15719. * in here. Color values can be passed any type of value accepted
  15720. * by {@link Color#set}.
  15721. */
  15722. constructor( parameters ) {
  15723. super();
  15724. /**
  15725. * This flag can be used for type testing.
  15726. *
  15727. * @type {boolean}
  15728. * @readonly
  15729. * @default true
  15730. */
  15731. this.isShaderMaterial = true;
  15732. this.type = 'ShaderMaterial';
  15733. /**
  15734. * Defines custom constants using `#define` directives within the GLSL code
  15735. * for both the vertex shader and the fragment shader; each key/value pair
  15736. * yields another directive.
  15737. * ```js
  15738. * defines: {
  15739. * FOO: 15,
  15740. * BAR: true
  15741. * }
  15742. * ```
  15743. * Yields the lines:
  15744. * ```
  15745. * #define FOO 15
  15746. * #define BAR true
  15747. * ```
  15748. *
  15749. * @type {Object}
  15750. */
  15751. this.defines = {};
  15752. /**
  15753. * An object of the form:
  15754. * ```js
  15755. * {
  15756. * "uniform1": { value: 1.0 },
  15757. * "uniform2": { value: 2 }
  15758. * }
  15759. * ```
  15760. * specifying the uniforms to be passed to the shader code; keys are uniform
  15761. * names, values are definitions of the form
  15762. * ```
  15763. * {
  15764. * value: 1.0
  15765. * }
  15766. * ```
  15767. * where `value` is the value of the uniform. Names must match the name of
  15768. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15769. * on every frame, so updating the value of the uniform will immediately
  15770. * update the value available to the GLSL code.
  15771. *
  15772. * @type {Object}
  15773. */
  15774. this.uniforms = {};
  15775. /**
  15776. * An array holding uniforms groups for configuring UBOs.
  15777. *
  15778. * @type {Array<UniformsGroup>}
  15779. */
  15780. this.uniformsGroups = [];
  15781. /**
  15782. * Vertex shader GLSL code. This is the actual code for the shader.
  15783. *
  15784. * @type {string}
  15785. */
  15786. this.vertexShader = default_vertex;
  15787. /**
  15788. * Fragment shader GLSL code. This is the actual code for the shader.
  15789. *
  15790. * @type {string}
  15791. */
  15792. this.fragmentShader = default_fragment;
  15793. /**
  15794. * Controls line thickness or lines.
  15795. *
  15796. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15797. * width of one pixel.
  15798. *
  15799. * @type {number}
  15800. * @default 1
  15801. */
  15802. this.linewidth = 1;
  15803. /**
  15804. * Renders the geometry as a wireframe.
  15805. *
  15806. * @type {boolean}
  15807. * @default false
  15808. */
  15809. this.wireframe = false;
  15810. /**
  15811. * Controls the thickness of the wireframe.
  15812. *
  15813. * WebGL and WebGPU ignore this property and always render
  15814. * 1 pixel wide lines.
  15815. *
  15816. * @type {number}
  15817. * @default 1
  15818. */
  15819. this.wireframeLinewidth = 1;
  15820. /**
  15821. * Defines whether the material color is affected by global fog settings; `true`
  15822. * to pass fog uniforms to the shader.
  15823. *
  15824. * Setting this property to `true` requires the definition of fog uniforms. It is
  15825. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  15826. * with predefined fog uniforms.
  15827. *
  15828. * ```js
  15829. * const material = new ShaderMaterial( {
  15830. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  15831. * vertexShader: vertexShader,
  15832. * fragmentShader: fragmentShader,
  15833. * fog: true
  15834. * } );
  15835. * ```
  15836. *
  15837. * @type {boolean}
  15838. * @default false
  15839. */
  15840. this.fog = false;
  15841. /**
  15842. * Defines whether this material uses lighting; `true` to pass uniform data
  15843. * related to lighting to this shader.
  15844. *
  15845. * @type {boolean}
  15846. * @default false
  15847. */
  15848. this.lights = false;
  15849. /**
  15850. * Defines whether this material supports clipping; `true` to let the renderer
  15851. * pass the clippingPlanes uniform.
  15852. *
  15853. * @type {boolean}
  15854. * @default false
  15855. */
  15856. this.clipping = false;
  15857. /**
  15858. * Overwritten and set to `true` by default.
  15859. *
  15860. * @type {boolean}
  15861. * @default true
  15862. */
  15863. this.forceSinglePass = true;
  15864. /**
  15865. * This object allows to enable certain WebGL 2 extensions.
  15866. *
  15867. * - clipCullDistance: set to `true` to use vertex shader clipping
  15868. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15869. *
  15870. * @type {{clipCullDistance:false,multiDraw:false}}
  15871. */
  15872. this.extensions = {
  15873. clipCullDistance: false, // set to use vertex shader clipping
  15874. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15875. };
  15876. /**
  15877. * When the rendered geometry doesn't include these attributes but the
  15878. * material does, these default values will be passed to the shaders. This
  15879. * avoids errors when buffer data is missing.
  15880. *
  15881. * - color: [ 1, 1, 1 ]
  15882. * - uv: [ 0, 0 ]
  15883. * - uv1: [ 0, 0 ]
  15884. *
  15885. * @type {Object}
  15886. */
  15887. this.defaultAttributeValues = {
  15888. 'color': [ 1, 1, 1 ],
  15889. 'uv': [ 0, 0 ],
  15890. 'uv1': [ 0, 0 ]
  15891. };
  15892. /**
  15893. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  15894. * to bind a generic vertex index to an attribute variable.
  15895. *
  15896. * @type {string|undefined}
  15897. * @default undefined
  15898. */
  15899. this.index0AttributeName = undefined;
  15900. /**
  15901. * Can be used to force a uniform update while changing uniforms in
  15902. * {@link Object3D#onBeforeRender}.
  15903. *
  15904. * @type {boolean}
  15905. * @default false
  15906. */
  15907. this.uniformsNeedUpdate = false;
  15908. /**
  15909. * Defines the GLSL version of custom shader code.
  15910. *
  15911. * @type {?(GLSL1|GLSL3)}
  15912. * @default null
  15913. */
  15914. this.glslVersion = null;
  15915. if ( parameters !== undefined ) {
  15916. this.setValues( parameters );
  15917. }
  15918. }
  15919. copy( source ) {
  15920. super.copy( source );
  15921. this.fragmentShader = source.fragmentShader;
  15922. this.vertexShader = source.vertexShader;
  15923. this.uniforms = cloneUniforms( source.uniforms );
  15924. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15925. this.defines = Object.assign( {}, source.defines );
  15926. this.wireframe = source.wireframe;
  15927. this.wireframeLinewidth = source.wireframeLinewidth;
  15928. this.fog = source.fog;
  15929. this.lights = source.lights;
  15930. this.clipping = source.clipping;
  15931. this.extensions = Object.assign( {}, source.extensions );
  15932. this.glslVersion = source.glslVersion;
  15933. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  15934. this.index0AttributeName = source.index0AttributeName;
  15935. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  15936. return this;
  15937. }
  15938. toJSON( meta ) {
  15939. const data = super.toJSON( meta );
  15940. data.glslVersion = this.glslVersion;
  15941. data.uniforms = {};
  15942. for ( const name in this.uniforms ) {
  15943. const uniform = this.uniforms[ name ];
  15944. const value = uniform.value;
  15945. if ( value && value.isTexture ) {
  15946. data.uniforms[ name ] = {
  15947. type: 't',
  15948. value: value.toJSON( meta ).uuid
  15949. };
  15950. } else if ( value && value.isColor ) {
  15951. data.uniforms[ name ] = {
  15952. type: 'c',
  15953. value: value.getHex()
  15954. };
  15955. } else if ( value && value.isVector2 ) {
  15956. data.uniforms[ name ] = {
  15957. type: 'v2',
  15958. value: value.toArray()
  15959. };
  15960. } else if ( value && value.isVector3 ) {
  15961. data.uniforms[ name ] = {
  15962. type: 'v3',
  15963. value: value.toArray()
  15964. };
  15965. } else if ( value && value.isVector4 ) {
  15966. data.uniforms[ name ] = {
  15967. type: 'v4',
  15968. value: value.toArray()
  15969. };
  15970. } else if ( value && value.isMatrix3 ) {
  15971. data.uniforms[ name ] = {
  15972. type: 'm3',
  15973. value: value.toArray()
  15974. };
  15975. } else if ( value && value.isMatrix4 ) {
  15976. data.uniforms[ name ] = {
  15977. type: 'm4',
  15978. value: value.toArray()
  15979. };
  15980. } else {
  15981. data.uniforms[ name ] = {
  15982. value: value
  15983. };
  15984. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15985. }
  15986. }
  15987. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15988. data.vertexShader = this.vertexShader;
  15989. data.fragmentShader = this.fragmentShader;
  15990. data.lights = this.lights;
  15991. data.clipping = this.clipping;
  15992. const extensions = {};
  15993. for ( const key in this.extensions ) {
  15994. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15995. }
  15996. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15997. return data;
  15998. }
  15999. }
  16000. /**
  16001. * Abstract base class for cameras. This class should always be inherited
  16002. * when you build a new camera.
  16003. *
  16004. * @abstract
  16005. * @augments Object3D
  16006. */
  16007. class Camera extends Object3D {
  16008. /**
  16009. * Constructs a new camera.
  16010. */
  16011. constructor() {
  16012. super();
  16013. /**
  16014. * This flag can be used for type testing.
  16015. *
  16016. * @type {boolean}
  16017. * @readonly
  16018. * @default true
  16019. */
  16020. this.isCamera = true;
  16021. this.type = 'Camera';
  16022. /**
  16023. * The inverse of the camera's world matrix.
  16024. *
  16025. * @type {Matrix4}
  16026. */
  16027. this.matrixWorldInverse = new Matrix4();
  16028. /**
  16029. * The camera's projection matrix.
  16030. *
  16031. * @type {Matrix4}
  16032. */
  16033. this.projectionMatrix = new Matrix4();
  16034. /**
  16035. * The inverse of the camera's projection matrix.
  16036. *
  16037. * @type {Matrix4}
  16038. */
  16039. this.projectionMatrixInverse = new Matrix4();
  16040. /**
  16041. * The coordinate system in which the camera is used.
  16042. *
  16043. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16044. */
  16045. this.coordinateSystem = WebGLCoordinateSystem;
  16046. this._reversedDepth = false;
  16047. }
  16048. /**
  16049. * The flag that indicates whether the camera uses a reversed depth buffer.
  16050. *
  16051. * @type {boolean}
  16052. * @default false
  16053. */
  16054. get reversedDepth() {
  16055. return this._reversedDepth;
  16056. }
  16057. copy( source, recursive ) {
  16058. super.copy( source, recursive );
  16059. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16060. this.projectionMatrix.copy( source.projectionMatrix );
  16061. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16062. this.coordinateSystem = source.coordinateSystem;
  16063. return this;
  16064. }
  16065. /**
  16066. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16067. *
  16068. * This method is overwritten since cameras have a different forward vector compared to other
  16069. * 3D objects. A camera looks down its local, negative z-axis by default.
  16070. *
  16071. * @param {Vector3} target - The target vector the result is stored to.
  16072. * @return {Vector3} The 3D object's direction in world space.
  16073. */
  16074. getWorldDirection( target ) {
  16075. return super.getWorldDirection( target ).negate();
  16076. }
  16077. updateMatrixWorld( force ) {
  16078. super.updateMatrixWorld( force );
  16079. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16080. }
  16081. updateWorldMatrix( updateParents, updateChildren ) {
  16082. super.updateWorldMatrix( updateParents, updateChildren );
  16083. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16084. }
  16085. clone() {
  16086. return new this.constructor().copy( this );
  16087. }
  16088. }
  16089. const _v3$1 = /*@__PURE__*/ new Vector3();
  16090. const _minTarget = /*@__PURE__*/ new Vector2();
  16091. const _maxTarget = /*@__PURE__*/ new Vector2();
  16092. /**
  16093. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16094. *
  16095. * This projection mode is designed to mimic the way the human eye sees. It
  16096. * is the most common projection mode used for rendering a 3D scene.
  16097. *
  16098. * ```js
  16099. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16100. * scene.add( camera );
  16101. * ```
  16102. *
  16103. * @augments Camera
  16104. */
  16105. class PerspectiveCamera extends Camera {
  16106. /**
  16107. * Constructs a new perspective camera.
  16108. *
  16109. * @param {number} [fov=50] - The vertical field of view.
  16110. * @param {number} [aspect=1] - The aspect ratio.
  16111. * @param {number} [near=0.1] - The camera's near plane.
  16112. * @param {number} [far=2000] - The camera's far plane.
  16113. */
  16114. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16115. super();
  16116. /**
  16117. * This flag can be used for type testing.
  16118. *
  16119. * @type {boolean}
  16120. * @readonly
  16121. * @default true
  16122. */
  16123. this.isPerspectiveCamera = true;
  16124. this.type = 'PerspectiveCamera';
  16125. /**
  16126. * The vertical field of view, from bottom to top of view,
  16127. * in degrees.
  16128. *
  16129. * @type {number}
  16130. * @default 50
  16131. */
  16132. this.fov = fov;
  16133. /**
  16134. * The zoom factor of the camera.
  16135. *
  16136. * @type {number}
  16137. * @default 1
  16138. */
  16139. this.zoom = 1;
  16140. /**
  16141. * The camera's near plane. The valid range is greater than `0`
  16142. * and less than the current value of {@link PerspectiveCamera#far}.
  16143. *
  16144. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16145. * valid value for a perspective camera's near plane.
  16146. *
  16147. * @type {number}
  16148. * @default 0.1
  16149. */
  16150. this.near = near;
  16151. /**
  16152. * The camera's far plane. Must be greater than the
  16153. * current value of {@link PerspectiveCamera#near}.
  16154. *
  16155. * @type {number}
  16156. * @default 2000
  16157. */
  16158. this.far = far;
  16159. /**
  16160. * Object distance used for stereoscopy and depth-of-field effects. This
  16161. * parameter does not influence the projection matrix unless a
  16162. * {@link StereoCamera} is being used.
  16163. *
  16164. * @type {number}
  16165. * @default 10
  16166. */
  16167. this.focus = 10;
  16168. /**
  16169. * The aspect ratio, usually the canvas width / canvas height.
  16170. *
  16171. * @type {number}
  16172. * @default 1
  16173. */
  16174. this.aspect = aspect;
  16175. /**
  16176. * Represents the frustum window specification. This property should not be edited
  16177. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16178. *
  16179. * @type {?Object}
  16180. * @default null
  16181. */
  16182. this.view = null;
  16183. /**
  16184. * Film size used for the larger axis. Default is `35` (millimeters). This
  16185. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16186. * is set to a nonzero value.
  16187. *
  16188. * @type {number}
  16189. * @default 35
  16190. */
  16191. this.filmGauge = 35;
  16192. /**
  16193. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16194. *
  16195. * @type {number}
  16196. * @default 0
  16197. */
  16198. this.filmOffset = 0;
  16199. this.updateProjectionMatrix();
  16200. }
  16201. copy( source, recursive ) {
  16202. super.copy( source, recursive );
  16203. this.fov = source.fov;
  16204. this.zoom = source.zoom;
  16205. this.near = source.near;
  16206. this.far = source.far;
  16207. this.focus = source.focus;
  16208. this.aspect = source.aspect;
  16209. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16210. this.filmGauge = source.filmGauge;
  16211. this.filmOffset = source.filmOffset;
  16212. return this;
  16213. }
  16214. /**
  16215. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16216. *
  16217. * The default film gauge is 35, so that the focal length can be specified for
  16218. * a 35mm (full frame) camera.
  16219. *
  16220. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16221. */
  16222. setFocalLength( focalLength ) {
  16223. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16224. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16225. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16226. this.updateProjectionMatrix();
  16227. }
  16228. /**
  16229. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16230. * {@link PerspectiveCamera#filmGauge}.
  16231. *
  16232. * @return {number} The computed focal length.
  16233. */
  16234. getFocalLength() {
  16235. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16236. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16237. }
  16238. /**
  16239. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16240. *
  16241. * @return {number} The effective FOV.
  16242. */
  16243. getEffectiveFOV() {
  16244. return RAD2DEG * 2 * Math.atan(
  16245. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16246. }
  16247. /**
  16248. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16249. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16250. *
  16251. * @return {number} The film width.
  16252. */
  16253. getFilmWidth() {
  16254. // film not completely covered in portrait format (aspect < 1)
  16255. return this.filmGauge * Math.min( this.aspect, 1 );
  16256. }
  16257. /**
  16258. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16259. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16260. *
  16261. * @return {number} The film width.
  16262. */
  16263. getFilmHeight() {
  16264. // film not completely covered in landscape format (aspect > 1)
  16265. return this.filmGauge / Math.max( this.aspect, 1 );
  16266. }
  16267. /**
  16268. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16269. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16270. *
  16271. * @param {number} distance - The viewing distance.
  16272. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16273. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16274. */
  16275. getViewBounds( distance, minTarget, maxTarget ) {
  16276. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16277. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16278. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16279. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16280. }
  16281. /**
  16282. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16283. *
  16284. * @param {number} distance - The viewing distance.
  16285. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16286. * @returns {Vector2} The view size.
  16287. */
  16288. getViewSize( distance, target ) {
  16289. this.getViewBounds( distance, _minTarget, _maxTarget );
  16290. return target.subVectors( _maxTarget, _minTarget );
  16291. }
  16292. /**
  16293. * Sets an offset in a larger frustum. This is useful for multi-window or
  16294. * multi-monitor/multi-machine setups.
  16295. *
  16296. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16297. * the monitors are in grid like this
  16298. *```
  16299. * +---+---+---+
  16300. * | A | B | C |
  16301. * +---+---+---+
  16302. * | D | E | F |
  16303. * +---+---+---+
  16304. *```
  16305. * then for each monitor you would call it like this:
  16306. *```js
  16307. * const w = 1920;
  16308. * const h = 1080;
  16309. * const fullWidth = w * 3;
  16310. * const fullHeight = h * 2;
  16311. *
  16312. * // --A--
  16313. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16314. * // --B--
  16315. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16316. * // --C--
  16317. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16318. * // --D--
  16319. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16320. * // --E--
  16321. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16322. * // --F--
  16323. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16324. * ```
  16325. *
  16326. * Note there is no reason monitors have to be the same size or in a grid.
  16327. *
  16328. * @param {number} fullWidth - The full width of multiview setup.
  16329. * @param {number} fullHeight - The full height of multiview setup.
  16330. * @param {number} x - The horizontal offset of the subcamera.
  16331. * @param {number} y - The vertical offset of the subcamera.
  16332. * @param {number} width - The width of subcamera.
  16333. * @param {number} height - The height of subcamera.
  16334. */
  16335. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16336. this.aspect = fullWidth / fullHeight;
  16337. if ( this.view === null ) {
  16338. this.view = {
  16339. enabled: true,
  16340. fullWidth: 1,
  16341. fullHeight: 1,
  16342. offsetX: 0,
  16343. offsetY: 0,
  16344. width: 1,
  16345. height: 1
  16346. };
  16347. }
  16348. this.view.enabled = true;
  16349. this.view.fullWidth = fullWidth;
  16350. this.view.fullHeight = fullHeight;
  16351. this.view.offsetX = x;
  16352. this.view.offsetY = y;
  16353. this.view.width = width;
  16354. this.view.height = height;
  16355. this.updateProjectionMatrix();
  16356. }
  16357. /**
  16358. * Removes the view offset from the projection matrix.
  16359. */
  16360. clearViewOffset() {
  16361. if ( this.view !== null ) {
  16362. this.view.enabled = false;
  16363. }
  16364. this.updateProjectionMatrix();
  16365. }
  16366. /**
  16367. * Updates the camera's projection matrix. Must be called after any change of
  16368. * camera properties.
  16369. */
  16370. updateProjectionMatrix() {
  16371. const near = this.near;
  16372. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16373. let height = 2 * top;
  16374. let width = this.aspect * height;
  16375. let left = -0.5 * width;
  16376. const view = this.view;
  16377. if ( this.view !== null && this.view.enabled ) {
  16378. const fullWidth = view.fullWidth,
  16379. fullHeight = view.fullHeight;
  16380. left += view.offsetX * width / fullWidth;
  16381. top -= view.offsetY * height / fullHeight;
  16382. width *= view.width / fullWidth;
  16383. height *= view.height / fullHeight;
  16384. }
  16385. const skew = this.filmOffset;
  16386. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16387. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16388. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16389. }
  16390. toJSON( meta ) {
  16391. const data = super.toJSON( meta );
  16392. data.object.fov = this.fov;
  16393. data.object.zoom = this.zoom;
  16394. data.object.near = this.near;
  16395. data.object.far = this.far;
  16396. data.object.focus = this.focus;
  16397. data.object.aspect = this.aspect;
  16398. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16399. data.object.filmGauge = this.filmGauge;
  16400. data.object.filmOffset = this.filmOffset;
  16401. return data;
  16402. }
  16403. }
  16404. const fov = -90; // negative fov is not an error
  16405. const aspect = 1;
  16406. /**
  16407. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16408. * cube render target. The render target can then be used as an environment map for rendering
  16409. * realtime reflections in your scene.
  16410. *
  16411. * ```js
  16412. * // Create cube render target
  16413. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16414. *
  16415. * // Create cube camera
  16416. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16417. * scene.add( cubeCamera );
  16418. *
  16419. * // Create car
  16420. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16421. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16422. * scene.add( car );
  16423. *
  16424. * // Update the render target cube
  16425. * car.visible = false;
  16426. * cubeCamera.position.copy( car.position );
  16427. * cubeCamera.update( renderer, scene );
  16428. *
  16429. * // Render the scene
  16430. * car.visible = true;
  16431. * renderer.render( scene, camera );
  16432. * ```
  16433. *
  16434. * @augments Object3D
  16435. */
  16436. class CubeCamera extends Object3D {
  16437. /**
  16438. * Constructs a new cube camera.
  16439. *
  16440. * @param {number} near - The camera's near plane.
  16441. * @param {number} far - The camera's far plane.
  16442. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16443. */
  16444. constructor( near, far, renderTarget ) {
  16445. super();
  16446. this.type = 'CubeCamera';
  16447. /**
  16448. * A reference to the cube render target.
  16449. *
  16450. * @type {WebGLCubeRenderTarget}
  16451. */
  16452. this.renderTarget = renderTarget;
  16453. /**
  16454. * The current active coordinate system.
  16455. *
  16456. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16457. * @default null
  16458. */
  16459. this.coordinateSystem = null;
  16460. /**
  16461. * The current active mipmap level
  16462. *
  16463. * @type {number}
  16464. * @default 0
  16465. */
  16466. this.activeMipmapLevel = 0;
  16467. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16468. cameraPX.layers = this.layers;
  16469. this.add( cameraPX );
  16470. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16471. cameraNX.layers = this.layers;
  16472. this.add( cameraNX );
  16473. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16474. cameraPY.layers = this.layers;
  16475. this.add( cameraPY );
  16476. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16477. cameraNY.layers = this.layers;
  16478. this.add( cameraNY );
  16479. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16480. cameraPZ.layers = this.layers;
  16481. this.add( cameraPZ );
  16482. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16483. cameraNZ.layers = this.layers;
  16484. this.add( cameraNZ );
  16485. }
  16486. /**
  16487. * Must be called when the coordinate system of the cube camera is changed.
  16488. */
  16489. updateCoordinateSystem() {
  16490. const coordinateSystem = this.coordinateSystem;
  16491. const cameras = this.children.concat();
  16492. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16493. for ( const camera of cameras ) this.remove( camera );
  16494. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16495. cameraPX.up.set( 0, 1, 0 );
  16496. cameraPX.lookAt( 1, 0, 0 );
  16497. cameraNX.up.set( 0, 1, 0 );
  16498. cameraNX.lookAt( -1, 0, 0 );
  16499. cameraPY.up.set( 0, 0, -1 );
  16500. cameraPY.lookAt( 0, 1, 0 );
  16501. cameraNY.up.set( 0, 0, 1 );
  16502. cameraNY.lookAt( 0, -1, 0 );
  16503. cameraPZ.up.set( 0, 1, 0 );
  16504. cameraPZ.lookAt( 0, 0, 1 );
  16505. cameraNZ.up.set( 0, 1, 0 );
  16506. cameraNZ.lookAt( 0, 0, -1 );
  16507. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16508. cameraPX.up.set( 0, -1, 0 );
  16509. cameraPX.lookAt( -1, 0, 0 );
  16510. cameraNX.up.set( 0, -1, 0 );
  16511. cameraNX.lookAt( 1, 0, 0 );
  16512. cameraPY.up.set( 0, 0, 1 );
  16513. cameraPY.lookAt( 0, 1, 0 );
  16514. cameraNY.up.set( 0, 0, -1 );
  16515. cameraNY.lookAt( 0, -1, 0 );
  16516. cameraPZ.up.set( 0, -1, 0 );
  16517. cameraPZ.lookAt( 0, 0, 1 );
  16518. cameraNZ.up.set( 0, -1, 0 );
  16519. cameraNZ.lookAt( 0, 0, -1 );
  16520. } else {
  16521. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16522. }
  16523. for ( const camera of cameras ) {
  16524. this.add( camera );
  16525. camera.updateMatrixWorld();
  16526. }
  16527. }
  16528. /**
  16529. * Calling this method will render the given scene with the given renderer
  16530. * into the cube render target of the camera.
  16531. *
  16532. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16533. * @param {Scene} scene - The scene to render.
  16534. */
  16535. update( renderer, scene ) {
  16536. if ( this.parent === null ) this.updateMatrixWorld();
  16537. const { renderTarget, activeMipmapLevel } = this;
  16538. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16539. this.coordinateSystem = renderer.coordinateSystem;
  16540. this.updateCoordinateSystem();
  16541. }
  16542. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16543. const currentRenderTarget = renderer.getRenderTarget();
  16544. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16545. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16546. const currentXrEnabled = renderer.xr.enabled;
  16547. renderer.xr.enabled = false;
  16548. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16549. renderTarget.texture.generateMipmaps = false;
  16550. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16551. renderer.render( scene, cameraPX );
  16552. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16553. renderer.render( scene, cameraNX );
  16554. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16555. renderer.render( scene, cameraPY );
  16556. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16557. renderer.render( scene, cameraNY );
  16558. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16559. renderer.render( scene, cameraPZ );
  16560. // mipmaps are generated during the last call of render()
  16561. // at this point, all sides of the cube render target are defined
  16562. renderTarget.texture.generateMipmaps = generateMipmaps;
  16563. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16564. renderer.render( scene, cameraNZ );
  16565. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16566. renderer.xr.enabled = currentXrEnabled;
  16567. renderTarget.texture.needsPMREMUpdate = true;
  16568. }
  16569. }
  16570. /**
  16571. * Creates a cube texture made up of six images.
  16572. *
  16573. * ```js
  16574. * const loader = new THREE.CubeTextureLoader();
  16575. * loader.setPath( 'textures/cube/pisa/' );
  16576. *
  16577. * const textureCube = loader.load( [
  16578. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16579. * ] );
  16580. *
  16581. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16582. * ```
  16583. *
  16584. * @augments Texture
  16585. */
  16586. class CubeTexture extends Texture {
  16587. /**
  16588. * Constructs a new cube texture.
  16589. *
  16590. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16591. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16592. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16593. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16594. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16595. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16596. * @param {number} [format=RGBAFormat] - The texture format.
  16597. * @param {number} [type=UnsignedByteType] - The texture type.
  16598. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16599. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16600. */
  16601. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16602. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16603. /**
  16604. * This flag can be used for type testing.
  16605. *
  16606. * @type {boolean}
  16607. * @readonly
  16608. * @default true
  16609. */
  16610. this.isCubeTexture = true;
  16611. /**
  16612. * If set to `true`, the texture is flipped along the vertical axis when
  16613. * uploaded to the GPU.
  16614. *
  16615. * Overwritten and set to `false` by default.
  16616. *
  16617. * @type {boolean}
  16618. * @default false
  16619. */
  16620. this.flipY = false;
  16621. }
  16622. /**
  16623. * Alias for {@link CubeTexture#image}.
  16624. *
  16625. * @type {Array<Image>}
  16626. */
  16627. get images() {
  16628. return this.image;
  16629. }
  16630. set images( value ) {
  16631. this.image = value;
  16632. }
  16633. }
  16634. /**
  16635. * A cube render target used in context of {@link WebGLRenderer}.
  16636. *
  16637. * @augments WebGLRenderTarget
  16638. */
  16639. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16640. /**
  16641. * Constructs a new cube render target.
  16642. *
  16643. * @param {number} [size=1] - The size of the render target.
  16644. * @param {RenderTarget~Options} [options] - The configuration object.
  16645. */
  16646. constructor( size = 1, options = {} ) {
  16647. super( size, size, options );
  16648. /**
  16649. * This flag can be used for type testing.
  16650. *
  16651. * @type {boolean}
  16652. * @readonly
  16653. * @default true
  16654. */
  16655. this.isWebGLCubeRenderTarget = true;
  16656. const image = { width: size, height: size, depth: 1 };
  16657. const images = [ image, image, image, image, image, image ];
  16658. /**
  16659. * Overwritten with a different texture type.
  16660. *
  16661. * @type {DataArrayTexture}
  16662. */
  16663. this.texture = new CubeTexture( images );
  16664. this._setTextureOptions( options );
  16665. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16666. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16667. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16668. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16669. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16670. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16671. this.texture.isRenderTargetTexture = true;
  16672. }
  16673. /**
  16674. * Converts the given equirectangular texture to a cube map.
  16675. *
  16676. * @param {WebGLRenderer} renderer - The renderer.
  16677. * @param {Texture} texture - The equirectangular texture.
  16678. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16679. */
  16680. fromEquirectangularTexture( renderer, texture ) {
  16681. this.texture.type = texture.type;
  16682. this.texture.colorSpace = texture.colorSpace;
  16683. this.texture.generateMipmaps = texture.generateMipmaps;
  16684. this.texture.minFilter = texture.minFilter;
  16685. this.texture.magFilter = texture.magFilter;
  16686. const shader = {
  16687. uniforms: {
  16688. tEquirect: { value: null },
  16689. },
  16690. vertexShader: /* glsl */`
  16691. varying vec3 vWorldDirection;
  16692. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16693. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16694. }
  16695. void main() {
  16696. vWorldDirection = transformDirection( position, modelMatrix );
  16697. #include <begin_vertex>
  16698. #include <project_vertex>
  16699. }
  16700. `,
  16701. fragmentShader: /* glsl */`
  16702. uniform sampler2D tEquirect;
  16703. varying vec3 vWorldDirection;
  16704. #include <common>
  16705. void main() {
  16706. vec3 direction = normalize( vWorldDirection );
  16707. vec2 sampleUV = equirectUv( direction );
  16708. gl_FragColor = texture2D( tEquirect, sampleUV );
  16709. }
  16710. `
  16711. };
  16712. const geometry = new BoxGeometry( 5, 5, 5 );
  16713. const material = new ShaderMaterial( {
  16714. name: 'CubemapFromEquirect',
  16715. uniforms: cloneUniforms( shader.uniforms ),
  16716. vertexShader: shader.vertexShader,
  16717. fragmentShader: shader.fragmentShader,
  16718. side: BackSide,
  16719. blending: NoBlending
  16720. } );
  16721. material.uniforms.tEquirect.value = texture;
  16722. const mesh = new Mesh( geometry, material );
  16723. const currentMinFilter = texture.minFilter;
  16724. // Avoid blurred poles
  16725. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16726. const camera = new CubeCamera( 1, 10, this );
  16727. camera.update( renderer, mesh );
  16728. texture.minFilter = currentMinFilter;
  16729. mesh.geometry.dispose();
  16730. mesh.material.dispose();
  16731. return this;
  16732. }
  16733. /**
  16734. * Clears this cube render target.
  16735. *
  16736. * @param {WebGLRenderer} renderer - The renderer.
  16737. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16738. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16739. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16740. */
  16741. clear( renderer, color = true, depth = true, stencil = true ) {
  16742. const currentRenderTarget = renderer.getRenderTarget();
  16743. for ( let i = 0; i < 6; i ++ ) {
  16744. renderer.setRenderTarget( this, i );
  16745. renderer.clear( color, depth, stencil );
  16746. }
  16747. renderer.setRenderTarget( currentRenderTarget );
  16748. }
  16749. }
  16750. /**
  16751. * This is almost identical to an {@link Object3D}. Its purpose is to
  16752. * make working with groups of objects syntactically clearer.
  16753. *
  16754. * ```js
  16755. * // Create a group and add the two cubes.
  16756. * // These cubes can now be rotated / scaled etc as a group.
  16757. * const group = new THREE.Group();
  16758. *
  16759. * group.add( meshA );
  16760. * group.add( meshB );
  16761. *
  16762. * scene.add( group );
  16763. * ```
  16764. *
  16765. * @augments Object3D
  16766. */
  16767. class Group extends Object3D {
  16768. constructor() {
  16769. super();
  16770. /**
  16771. * This flag can be used for type testing.
  16772. *
  16773. * @type {boolean}
  16774. * @readonly
  16775. * @default true
  16776. */
  16777. this.isGroup = true;
  16778. this.type = 'Group';
  16779. }
  16780. }
  16781. const _moveEvent = { type: 'move' };
  16782. /**
  16783. * Class for representing a XR controller with its
  16784. * different coordinate systems.
  16785. *
  16786. * @private
  16787. */
  16788. class WebXRController {
  16789. /**
  16790. * Constructs a new XR controller.
  16791. */
  16792. constructor() {
  16793. /**
  16794. * A group representing the target ray space
  16795. * of the XR controller.
  16796. *
  16797. * @private
  16798. * @type {?Group}
  16799. * @default null
  16800. */
  16801. this._targetRay = null;
  16802. /**
  16803. * A group representing the grip space
  16804. * of the XR controller.
  16805. *
  16806. * @private
  16807. * @type {?Group}
  16808. * @default null
  16809. */
  16810. this._grip = null;
  16811. /**
  16812. * A group representing the hand space
  16813. * of the XR controller.
  16814. *
  16815. * @private
  16816. * @type {?Group}
  16817. * @default null
  16818. */
  16819. this._hand = null;
  16820. }
  16821. /**
  16822. * Returns a group representing the hand space of the XR controller.
  16823. *
  16824. * @return {Group} A group representing the hand space of the XR controller.
  16825. */
  16826. getHandSpace() {
  16827. if ( this._hand === null ) {
  16828. this._hand = new Group();
  16829. this._hand.matrixAutoUpdate = false;
  16830. this._hand.visible = false;
  16831. this._hand.joints = {};
  16832. this._hand.inputState = { pinching: false };
  16833. }
  16834. return this._hand;
  16835. }
  16836. /**
  16837. * Returns a group representing the target ray space of the XR controller.
  16838. *
  16839. * @return {Group} A group representing the target ray space of the XR controller.
  16840. */
  16841. getTargetRaySpace() {
  16842. if ( this._targetRay === null ) {
  16843. this._targetRay = new Group();
  16844. this._targetRay.matrixAutoUpdate = false;
  16845. this._targetRay.visible = false;
  16846. this._targetRay.hasLinearVelocity = false;
  16847. this._targetRay.linearVelocity = new Vector3();
  16848. this._targetRay.hasAngularVelocity = false;
  16849. this._targetRay.angularVelocity = new Vector3();
  16850. }
  16851. return this._targetRay;
  16852. }
  16853. /**
  16854. * Returns a group representing the grip space of the XR controller.
  16855. *
  16856. * @return {Group} A group representing the grip space of the XR controller.
  16857. */
  16858. getGripSpace() {
  16859. if ( this._grip === null ) {
  16860. this._grip = new Group();
  16861. this._grip.matrixAutoUpdate = false;
  16862. this._grip.visible = false;
  16863. this._grip.hasLinearVelocity = false;
  16864. this._grip.linearVelocity = new Vector3();
  16865. this._grip.hasAngularVelocity = false;
  16866. this._grip.angularVelocity = new Vector3();
  16867. }
  16868. return this._grip;
  16869. }
  16870. /**
  16871. * Dispatches the given event to the groups representing
  16872. * the different coordinate spaces of the XR controller.
  16873. *
  16874. * @param {Object} event - The event to dispatch.
  16875. * @return {WebXRController} A reference to this instance.
  16876. */
  16877. dispatchEvent( event ) {
  16878. if ( this._targetRay !== null ) {
  16879. this._targetRay.dispatchEvent( event );
  16880. }
  16881. if ( this._grip !== null ) {
  16882. this._grip.dispatchEvent( event );
  16883. }
  16884. if ( this._hand !== null ) {
  16885. this._hand.dispatchEvent( event );
  16886. }
  16887. return this;
  16888. }
  16889. /**
  16890. * Connects the controller with the given XR input source.
  16891. *
  16892. * @param {XRInputSource} inputSource - The input source.
  16893. * @return {WebXRController} A reference to this instance.
  16894. */
  16895. connect( inputSource ) {
  16896. if ( inputSource && inputSource.hand ) {
  16897. const hand = this._hand;
  16898. if ( hand ) {
  16899. for ( const inputjoint of inputSource.hand.values() ) {
  16900. // Initialize hand with joints when connected
  16901. this._getHandJoint( hand, inputjoint );
  16902. }
  16903. }
  16904. }
  16905. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16906. return this;
  16907. }
  16908. /**
  16909. * Disconnects the controller from the given XR input source.
  16910. *
  16911. * @param {XRInputSource} inputSource - The input source.
  16912. * @return {WebXRController} A reference to this instance.
  16913. */
  16914. disconnect( inputSource ) {
  16915. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16916. if ( this._targetRay !== null ) {
  16917. this._targetRay.visible = false;
  16918. }
  16919. if ( this._grip !== null ) {
  16920. this._grip.visible = false;
  16921. }
  16922. if ( this._hand !== null ) {
  16923. this._hand.visible = false;
  16924. }
  16925. return this;
  16926. }
  16927. /**
  16928. * Updates the controller with the given input source, XR frame and reference space.
  16929. * This updates the transformations of the groups that represent the different
  16930. * coordinate systems of the controller.
  16931. *
  16932. * @param {XRInputSource} inputSource - The input source.
  16933. * @param {XRFrame} frame - The XR frame.
  16934. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16935. * @return {WebXRController} A reference to this instance.
  16936. */
  16937. update( inputSource, frame, referenceSpace ) {
  16938. let inputPose = null;
  16939. let gripPose = null;
  16940. let handPose = null;
  16941. const targetRay = this._targetRay;
  16942. const grip = this._grip;
  16943. const hand = this._hand;
  16944. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16945. if ( hand && inputSource.hand ) {
  16946. handPose = true;
  16947. for ( const inputjoint of inputSource.hand.values() ) {
  16948. // Update the joints groups with the XRJoint poses
  16949. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16950. // The transform of this joint will be updated with the joint pose on each frame
  16951. const joint = this._getHandJoint( hand, inputjoint );
  16952. if ( jointPose !== null ) {
  16953. joint.matrix.fromArray( jointPose.transform.matrix );
  16954. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16955. joint.matrixWorldNeedsUpdate = true;
  16956. joint.jointRadius = jointPose.radius;
  16957. }
  16958. joint.visible = jointPose !== null;
  16959. }
  16960. // Custom events
  16961. // Check pinchz
  16962. const indexTip = hand.joints[ 'index-finger-tip' ];
  16963. const thumbTip = hand.joints[ 'thumb-tip' ];
  16964. const distance = indexTip.position.distanceTo( thumbTip.position );
  16965. const distanceToPinch = 0.02;
  16966. const threshold = 0.005;
  16967. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16968. hand.inputState.pinching = false;
  16969. this.dispatchEvent( {
  16970. type: 'pinchend',
  16971. handedness: inputSource.handedness,
  16972. target: this
  16973. } );
  16974. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16975. hand.inputState.pinching = true;
  16976. this.dispatchEvent( {
  16977. type: 'pinchstart',
  16978. handedness: inputSource.handedness,
  16979. target: this
  16980. } );
  16981. }
  16982. } else {
  16983. if ( grip !== null && inputSource.gripSpace ) {
  16984. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16985. if ( gripPose !== null ) {
  16986. grip.matrix.fromArray( gripPose.transform.matrix );
  16987. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16988. grip.matrixWorldNeedsUpdate = true;
  16989. if ( gripPose.linearVelocity ) {
  16990. grip.hasLinearVelocity = true;
  16991. grip.linearVelocity.copy( gripPose.linearVelocity );
  16992. } else {
  16993. grip.hasLinearVelocity = false;
  16994. }
  16995. if ( gripPose.angularVelocity ) {
  16996. grip.hasAngularVelocity = true;
  16997. grip.angularVelocity.copy( gripPose.angularVelocity );
  16998. } else {
  16999. grip.hasAngularVelocity = false;
  17000. }
  17001. }
  17002. }
  17003. }
  17004. if ( targetRay !== null ) {
  17005. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17006. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17007. if ( inputPose === null && gripPose !== null ) {
  17008. inputPose = gripPose;
  17009. }
  17010. if ( inputPose !== null ) {
  17011. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17012. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17013. targetRay.matrixWorldNeedsUpdate = true;
  17014. if ( inputPose.linearVelocity ) {
  17015. targetRay.hasLinearVelocity = true;
  17016. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17017. } else {
  17018. targetRay.hasLinearVelocity = false;
  17019. }
  17020. if ( inputPose.angularVelocity ) {
  17021. targetRay.hasAngularVelocity = true;
  17022. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17023. } else {
  17024. targetRay.hasAngularVelocity = false;
  17025. }
  17026. this.dispatchEvent( _moveEvent );
  17027. }
  17028. }
  17029. }
  17030. if ( targetRay !== null ) {
  17031. targetRay.visible = ( inputPose !== null );
  17032. }
  17033. if ( grip !== null ) {
  17034. grip.visible = ( gripPose !== null );
  17035. }
  17036. if ( hand !== null ) {
  17037. hand.visible = ( handPose !== null );
  17038. }
  17039. return this;
  17040. }
  17041. /**
  17042. * Returns a group representing the hand joint for the given input joint.
  17043. *
  17044. * @private
  17045. * @param {Group} hand - The group representing the hand space.
  17046. * @param {XRJointSpace} inputjoint - The hand joint data.
  17047. * @return {Group} A group representing the hand joint for the given input joint.
  17048. */
  17049. _getHandJoint( hand, inputjoint ) {
  17050. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17051. const joint = new Group();
  17052. joint.matrixAutoUpdate = false;
  17053. joint.visible = false;
  17054. hand.joints[ inputjoint.jointName ] = joint;
  17055. hand.add( joint );
  17056. }
  17057. return hand.joints[ inputjoint.jointName ];
  17058. }
  17059. }
  17060. /**
  17061. * This class can be used to define an exponential squared fog,
  17062. * which gives a clear view near the camera and a faster than exponentially
  17063. * densening fog farther from the camera.
  17064. *
  17065. * ```js
  17066. * const scene = new THREE.Scene();
  17067. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17068. * ```
  17069. */
  17070. class FogExp2 {
  17071. /**
  17072. * Constructs a new fog.
  17073. *
  17074. * @param {number|Color} color - The fog's color.
  17075. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17076. */
  17077. constructor( color, density = 0.00025 ) {
  17078. /**
  17079. * This flag can be used for type testing.
  17080. *
  17081. * @type {boolean}
  17082. * @readonly
  17083. * @default true
  17084. */
  17085. this.isFogExp2 = true;
  17086. /**
  17087. * The name of the fog.
  17088. *
  17089. * @type {string}
  17090. */
  17091. this.name = '';
  17092. /**
  17093. * The fog's color.
  17094. *
  17095. * @type {Color}
  17096. */
  17097. this.color = new Color( color );
  17098. /**
  17099. * Defines how fast the fog will grow dense.
  17100. *
  17101. * @type {number}
  17102. * @default 0.00025
  17103. */
  17104. this.density = density;
  17105. }
  17106. /**
  17107. * Returns a new fog with copied values from this instance.
  17108. *
  17109. * @return {FogExp2} A clone of this instance.
  17110. */
  17111. clone() {
  17112. return new FogExp2( this.color, this.density );
  17113. }
  17114. /**
  17115. * Serializes the fog into JSON.
  17116. *
  17117. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17118. * @return {Object} A JSON object representing the serialized fog
  17119. */
  17120. toJSON( /* meta */ ) {
  17121. return {
  17122. type: 'FogExp2',
  17123. name: this.name,
  17124. color: this.color.getHex(),
  17125. density: this.density
  17126. };
  17127. }
  17128. }
  17129. /**
  17130. * This class can be used to define a linear fog that grows linearly denser
  17131. * with the distance.
  17132. *
  17133. * ```js
  17134. * const scene = new THREE.Scene();
  17135. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17136. * ```
  17137. */
  17138. class Fog {
  17139. /**
  17140. * Constructs a new fog.
  17141. *
  17142. * @param {number|Color} color - The fog's color.
  17143. * @param {number} [near=1] - The minimum distance to start applying fog.
  17144. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17145. */
  17146. constructor( color, near = 1, far = 1000 ) {
  17147. /**
  17148. * This flag can be used for type testing.
  17149. *
  17150. * @type {boolean}
  17151. * @readonly
  17152. * @default true
  17153. */
  17154. this.isFog = true;
  17155. /**
  17156. * The name of the fog.
  17157. *
  17158. * @type {string}
  17159. */
  17160. this.name = '';
  17161. /**
  17162. * The fog's color.
  17163. *
  17164. * @type {Color}
  17165. */
  17166. this.color = new Color( color );
  17167. /**
  17168. * The minimum distance to start applying fog. Objects that are less than
  17169. * `near` units from the active camera won't be affected by fog.
  17170. *
  17171. * @type {number}
  17172. * @default 1
  17173. */
  17174. this.near = near;
  17175. /**
  17176. * The maximum distance at which fog stops being calculated and applied.
  17177. * Objects that are more than `far` units away from the active camera won't
  17178. * be affected by fog.
  17179. *
  17180. * @type {number}
  17181. * @default 1000
  17182. */
  17183. this.far = far;
  17184. }
  17185. /**
  17186. * Returns a new fog with copied values from this instance.
  17187. *
  17188. * @return {Fog} A clone of this instance.
  17189. */
  17190. clone() {
  17191. return new Fog( this.color, this.near, this.far );
  17192. }
  17193. /**
  17194. * Serializes the fog into JSON.
  17195. *
  17196. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17197. * @return {Object} A JSON object representing the serialized fog
  17198. */
  17199. toJSON( /* meta */ ) {
  17200. return {
  17201. type: 'Fog',
  17202. name: this.name,
  17203. color: this.color.getHex(),
  17204. near: this.near,
  17205. far: this.far
  17206. };
  17207. }
  17208. }
  17209. /**
  17210. * Scenes allow you to set up what is to be rendered and where by three.js.
  17211. * This is where you place 3D objects like meshes, lines or lights.
  17212. *
  17213. * @augments Object3D
  17214. */
  17215. class Scene extends Object3D {
  17216. /**
  17217. * Constructs a new scene.
  17218. */
  17219. constructor() {
  17220. super();
  17221. /**
  17222. * This flag can be used for type testing.
  17223. *
  17224. * @type {boolean}
  17225. * @readonly
  17226. * @default true
  17227. */
  17228. this.isScene = true;
  17229. this.type = 'Scene';
  17230. /**
  17231. * Defines the background of the scene. Valid inputs are:
  17232. *
  17233. * - A color for defining a uniform colored background.
  17234. * - A texture for defining a (flat) textured background.
  17235. * - Cube textures or equirectangular textures for defining a skybox.
  17236. *
  17237. * @type {?(Color|Texture)}
  17238. * @default null
  17239. */
  17240. this.background = null;
  17241. /**
  17242. * Sets the environment map for all physical materials in the scene. However,
  17243. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17244. * material property.
  17245. *
  17246. * @type {?Texture}
  17247. * @default null
  17248. */
  17249. this.environment = null;
  17250. /**
  17251. * A fog instance defining the type of fog that affects everything
  17252. * rendered in the scene.
  17253. *
  17254. * @type {?(Fog|FogExp2)}
  17255. * @default null
  17256. */
  17257. this.fog = null;
  17258. /**
  17259. * Sets the blurriness of the background. Only influences environment maps
  17260. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17261. * and `1`.
  17262. *
  17263. * @type {number}
  17264. * @default 0
  17265. */
  17266. this.backgroundBlurriness = 0;
  17267. /**
  17268. * Attenuates the color of the background. Only applies to background textures.
  17269. *
  17270. * @type {number}
  17271. * @default 1
  17272. */
  17273. this.backgroundIntensity = 1;
  17274. /**
  17275. * The rotation of the background in radians. Only influences environment maps
  17276. * assigned to {@link Scene#background}.
  17277. *
  17278. * @type {Euler}
  17279. * @default (0,0,0)
  17280. */
  17281. this.backgroundRotation = new Euler();
  17282. /**
  17283. * Attenuates the color of the environment. Only influences environment maps
  17284. * assigned to {@link Scene#environment}.
  17285. *
  17286. * @type {number}
  17287. * @default 1
  17288. */
  17289. this.environmentIntensity = 1;
  17290. /**
  17291. * The rotation of the environment map in radians. Only influences physical materials
  17292. * in the scene when {@link Scene#environment} is used.
  17293. *
  17294. * @type {Euler}
  17295. * @default (0,0,0)
  17296. */
  17297. this.environmentRotation = new Euler();
  17298. /**
  17299. * Forces everything in the scene to be rendered with the defined material. It is possible
  17300. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17301. *
  17302. * @type {?Material}
  17303. * @default null
  17304. */
  17305. this.overrideMaterial = null;
  17306. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17307. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17308. }
  17309. }
  17310. copy( source, recursive ) {
  17311. super.copy( source, recursive );
  17312. if ( source.background !== null ) this.background = source.background.clone();
  17313. if ( source.environment !== null ) this.environment = source.environment.clone();
  17314. if ( source.fog !== null ) this.fog = source.fog.clone();
  17315. this.backgroundBlurriness = source.backgroundBlurriness;
  17316. this.backgroundIntensity = source.backgroundIntensity;
  17317. this.backgroundRotation.copy( source.backgroundRotation );
  17318. this.environmentIntensity = source.environmentIntensity;
  17319. this.environmentRotation.copy( source.environmentRotation );
  17320. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17321. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17322. return this;
  17323. }
  17324. toJSON( meta ) {
  17325. const data = super.toJSON( meta );
  17326. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17327. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17328. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17329. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17330. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17331. data.object.environmentRotation = this.environmentRotation.toArray();
  17332. return data;
  17333. }
  17334. }
  17335. /**
  17336. * "Interleaved" means that multiple attributes, possibly of different types,
  17337. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17338. *
  17339. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17340. */
  17341. class InterleavedBuffer {
  17342. /**
  17343. * Constructs a new interleaved buffer.
  17344. *
  17345. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17346. * @param {number} stride - The number of typed-array elements per vertex.
  17347. */
  17348. constructor( array, stride ) {
  17349. /**
  17350. * This flag can be used for type testing.
  17351. *
  17352. * @type {boolean}
  17353. * @readonly
  17354. * @default true
  17355. */
  17356. this.isInterleavedBuffer = true;
  17357. /**
  17358. * A typed array with a shared buffer storing attribute data.
  17359. *
  17360. * @type {TypedArray}
  17361. */
  17362. this.array = array;
  17363. /**
  17364. * The number of typed-array elements per vertex.
  17365. *
  17366. * @type {number}
  17367. */
  17368. this.stride = stride;
  17369. /**
  17370. * The total number of elements in the array
  17371. *
  17372. * @type {number}
  17373. * @readonly
  17374. */
  17375. this.count = array !== undefined ? array.length / stride : 0;
  17376. /**
  17377. * Defines the intended usage pattern of the data store for optimization purposes.
  17378. *
  17379. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17380. * instantiate a new one and set the desired usage before the next render.
  17381. *
  17382. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17383. * @default StaticDrawUsage
  17384. */
  17385. this.usage = StaticDrawUsage;
  17386. /**
  17387. * This can be used to only update some components of stored vectors (for example, just the
  17388. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17389. *
  17390. * @type {Array<Object>}
  17391. */
  17392. this.updateRanges = [];
  17393. /**
  17394. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17395. *
  17396. * @type {number}
  17397. */
  17398. this.version = 0;
  17399. /**
  17400. * The UUID of the interleaved buffer.
  17401. *
  17402. * @type {string}
  17403. * @readonly
  17404. */
  17405. this.uuid = generateUUID();
  17406. }
  17407. /**
  17408. * A callback function that is executed after the renderer has transferred the attribute array
  17409. * data to the GPU.
  17410. */
  17411. onUploadCallback() {}
  17412. /**
  17413. * Flag to indicate that this attribute has changed and should be re-sent to
  17414. * the GPU. Set this to `true` when you modify the value of the array.
  17415. *
  17416. * @type {number}
  17417. * @default false
  17418. * @param {boolean} value
  17419. */
  17420. set needsUpdate( value ) {
  17421. if ( value === true ) this.version ++;
  17422. }
  17423. /**
  17424. * Sets the usage of this interleaved buffer.
  17425. *
  17426. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17427. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17428. */
  17429. setUsage( value ) {
  17430. this.usage = value;
  17431. return this;
  17432. }
  17433. /**
  17434. * Adds a range of data in the data array to be updated on the GPU.
  17435. *
  17436. * @param {number} start - Position at which to start update.
  17437. * @param {number} count - The number of components to update.
  17438. */
  17439. addUpdateRange( start, count ) {
  17440. this.updateRanges.push( { start, count } );
  17441. }
  17442. /**
  17443. * Clears the update ranges.
  17444. */
  17445. clearUpdateRanges() {
  17446. this.updateRanges.length = 0;
  17447. }
  17448. /**
  17449. * Copies the values of the given interleaved buffer to this instance.
  17450. *
  17451. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17452. * @return {InterleavedBuffer} A reference to this instance.
  17453. */
  17454. copy( source ) {
  17455. this.array = new source.array.constructor( source.array );
  17456. this.count = source.count;
  17457. this.stride = source.stride;
  17458. this.usage = source.usage;
  17459. return this;
  17460. }
  17461. /**
  17462. * Copies a vector from the given interleaved buffer to this one. The start
  17463. * and destination position in the attribute buffers are represented by the
  17464. * given indices.
  17465. *
  17466. * @param {number} index1 - The destination index into this interleaved buffer.
  17467. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17468. * @param {number} index2 - The source index into the given interleaved buffer.
  17469. * @return {InterleavedBuffer} A reference to this instance.
  17470. */
  17471. copyAt( index1, interleavedBuffer, index2 ) {
  17472. index1 *= this.stride;
  17473. index2 *= interleavedBuffer.stride;
  17474. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17475. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17476. }
  17477. return this;
  17478. }
  17479. /**
  17480. * Sets the given array data in the interleaved buffer.
  17481. *
  17482. * @param {(TypedArray|Array)} value - The array data to set.
  17483. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17484. * @return {InterleavedBuffer} A reference to this instance.
  17485. */
  17486. set( value, offset = 0 ) {
  17487. this.array.set( value, offset );
  17488. return this;
  17489. }
  17490. /**
  17491. * Returns a new interleaved buffer with copied values from this instance.
  17492. *
  17493. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17494. * @return {InterleavedBuffer} A clone of this instance.
  17495. */
  17496. clone( data ) {
  17497. if ( data.arrayBuffers === undefined ) {
  17498. data.arrayBuffers = {};
  17499. }
  17500. if ( this.array.buffer._uuid === undefined ) {
  17501. this.array.buffer._uuid = generateUUID();
  17502. }
  17503. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17504. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17505. }
  17506. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17507. const ib = new this.constructor( array, this.stride );
  17508. ib.setUsage( this.usage );
  17509. return ib;
  17510. }
  17511. /**
  17512. * Sets the given callback function that is executed after the Renderer has transferred
  17513. * the array data to the GPU. Can be used to perform clean-up operations after
  17514. * the upload when data are not needed anymore on the CPU side.
  17515. *
  17516. * @param {Function} callback - The `onUpload()` callback.
  17517. * @return {InterleavedBuffer} A reference to this instance.
  17518. */
  17519. onUpload( callback ) {
  17520. this.onUploadCallback = callback;
  17521. return this;
  17522. }
  17523. /**
  17524. * Serializes the interleaved buffer into JSON.
  17525. *
  17526. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17527. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17528. */
  17529. toJSON( data ) {
  17530. if ( data.arrayBuffers === undefined ) {
  17531. data.arrayBuffers = {};
  17532. }
  17533. // generate UUID for array buffer if necessary
  17534. if ( this.array.buffer._uuid === undefined ) {
  17535. this.array.buffer._uuid = generateUUID();
  17536. }
  17537. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17538. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17539. }
  17540. //
  17541. return {
  17542. uuid: this.uuid,
  17543. buffer: this.array.buffer._uuid,
  17544. type: this.array.constructor.name,
  17545. stride: this.stride
  17546. };
  17547. }
  17548. }
  17549. const _vector$7 = /*@__PURE__*/ new Vector3();
  17550. /**
  17551. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17552. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17553. * different offsets into the buffer.
  17554. */
  17555. class InterleavedBufferAttribute {
  17556. /**
  17557. * Constructs a new interleaved buffer attribute.
  17558. *
  17559. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17560. * @param {number} itemSize - The item size.
  17561. * @param {number} offset - The attribute offset into the buffer.
  17562. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17563. */
  17564. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17565. /**
  17566. * This flag can be used for type testing.
  17567. *
  17568. * @type {boolean}
  17569. * @readonly
  17570. * @default true
  17571. */
  17572. this.isInterleavedBufferAttribute = true;
  17573. /**
  17574. * The name of the buffer attribute.
  17575. *
  17576. * @type {string}
  17577. */
  17578. this.name = '';
  17579. /**
  17580. * The buffer holding the interleaved data.
  17581. *
  17582. * @type {InterleavedBuffer}
  17583. */
  17584. this.data = interleavedBuffer;
  17585. /**
  17586. * The item size, see {@link BufferAttribute#itemSize}.
  17587. *
  17588. * @type {number}
  17589. */
  17590. this.itemSize = itemSize;
  17591. /**
  17592. * The attribute offset into the buffer.
  17593. *
  17594. * @type {number}
  17595. */
  17596. this.offset = offset;
  17597. /**
  17598. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17599. *
  17600. * @type {InterleavedBuffer}
  17601. */
  17602. this.normalized = normalized;
  17603. }
  17604. /**
  17605. * The item count of this buffer attribute.
  17606. *
  17607. * @type {number}
  17608. * @readonly
  17609. */
  17610. get count() {
  17611. return this.data.count;
  17612. }
  17613. /**
  17614. * The array holding the interleaved buffer attribute data.
  17615. *
  17616. * @type {TypedArray}
  17617. */
  17618. get array() {
  17619. return this.data.array;
  17620. }
  17621. /**
  17622. * Flag to indicate that this attribute has changed and should be re-sent to
  17623. * the GPU. Set this to `true` when you modify the value of the array.
  17624. *
  17625. * @type {number}
  17626. * @default false
  17627. * @param {boolean} value
  17628. */
  17629. set needsUpdate( value ) {
  17630. this.data.needsUpdate = value;
  17631. }
  17632. /**
  17633. * Applies the given 4x4 matrix to the given attribute. Only works with
  17634. * item size `3`.
  17635. *
  17636. * @param {Matrix4} m - The matrix to apply.
  17637. * @return {InterleavedBufferAttribute} A reference to this instance.
  17638. */
  17639. applyMatrix4( m ) {
  17640. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17641. _vector$7.fromBufferAttribute( this, i );
  17642. _vector$7.applyMatrix4( m );
  17643. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17644. }
  17645. return this;
  17646. }
  17647. /**
  17648. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17649. * item size `3`.
  17650. *
  17651. * @param {Matrix3} m - The normal matrix to apply.
  17652. * @return {InterleavedBufferAttribute} A reference to this instance.
  17653. */
  17654. applyNormalMatrix( m ) {
  17655. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17656. _vector$7.fromBufferAttribute( this, i );
  17657. _vector$7.applyNormalMatrix( m );
  17658. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17659. }
  17660. return this;
  17661. }
  17662. /**
  17663. * Applies the given 4x4 matrix to the given attribute. Only works with
  17664. * item size `3` and with direction vectors.
  17665. *
  17666. * @param {Matrix4} m - The matrix to apply.
  17667. * @return {InterleavedBufferAttribute} A reference to this instance.
  17668. */
  17669. transformDirection( m ) {
  17670. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17671. _vector$7.fromBufferAttribute( this, i );
  17672. _vector$7.transformDirection( m );
  17673. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17674. }
  17675. return this;
  17676. }
  17677. /**
  17678. * Returns the given component of the vector at the given index.
  17679. *
  17680. * @param {number} index - The index into the buffer attribute.
  17681. * @param {number} component - The component index.
  17682. * @return {number} The returned value.
  17683. */
  17684. getComponent( index, component ) {
  17685. let value = this.array[ index * this.data.stride + this.offset + component ];
  17686. if ( this.normalized ) value = denormalize( value, this.array );
  17687. return value;
  17688. }
  17689. /**
  17690. * Sets the given value to the given component of the vector at the given index.
  17691. *
  17692. * @param {number} index - The index into the buffer attribute.
  17693. * @param {number} component - The component index.
  17694. * @param {number} value - The value to set.
  17695. * @return {InterleavedBufferAttribute} A reference to this instance.
  17696. */
  17697. setComponent( index, component, value ) {
  17698. if ( this.normalized ) value = normalize( value, this.array );
  17699. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17700. return this;
  17701. }
  17702. /**
  17703. * Sets the x component of the vector at the given index.
  17704. *
  17705. * @param {number} index - The index into the buffer attribute.
  17706. * @param {number} x - The value to set.
  17707. * @return {InterleavedBufferAttribute} A reference to this instance.
  17708. */
  17709. setX( index, x ) {
  17710. if ( this.normalized ) x = normalize( x, this.array );
  17711. this.data.array[ index * this.data.stride + this.offset ] = x;
  17712. return this;
  17713. }
  17714. /**
  17715. * Sets the y component of the vector at the given index.
  17716. *
  17717. * @param {number} index - The index into the buffer attribute.
  17718. * @param {number} y - The value to set.
  17719. * @return {InterleavedBufferAttribute} A reference to this instance.
  17720. */
  17721. setY( index, y ) {
  17722. if ( this.normalized ) y = normalize( y, this.array );
  17723. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17724. return this;
  17725. }
  17726. /**
  17727. * Sets the z component of the vector at the given index.
  17728. *
  17729. * @param {number} index - The index into the buffer attribute.
  17730. * @param {number} z - The value to set.
  17731. * @return {InterleavedBufferAttribute} A reference to this instance.
  17732. */
  17733. setZ( index, z ) {
  17734. if ( this.normalized ) z = normalize( z, this.array );
  17735. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17736. return this;
  17737. }
  17738. /**
  17739. * Sets the w component of the vector at the given index.
  17740. *
  17741. * @param {number} index - The index into the buffer attribute.
  17742. * @param {number} w - The value to set.
  17743. * @return {InterleavedBufferAttribute} A reference to this instance.
  17744. */
  17745. setW( index, w ) {
  17746. if ( this.normalized ) w = normalize( w, this.array );
  17747. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17748. return this;
  17749. }
  17750. /**
  17751. * Returns the x component of the vector at the given index.
  17752. *
  17753. * @param {number} index - The index into the buffer attribute.
  17754. * @return {number} The x component.
  17755. */
  17756. getX( index ) {
  17757. let x = this.data.array[ index * this.data.stride + this.offset ];
  17758. if ( this.normalized ) x = denormalize( x, this.array );
  17759. return x;
  17760. }
  17761. /**
  17762. * Returns the y component of the vector at the given index.
  17763. *
  17764. * @param {number} index - The index into the buffer attribute.
  17765. * @return {number} The y component.
  17766. */
  17767. getY( index ) {
  17768. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17769. if ( this.normalized ) y = denormalize( y, this.array );
  17770. return y;
  17771. }
  17772. /**
  17773. * Returns the z component of the vector at the given index.
  17774. *
  17775. * @param {number} index - The index into the buffer attribute.
  17776. * @return {number} The z component.
  17777. */
  17778. getZ( index ) {
  17779. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17780. if ( this.normalized ) z = denormalize( z, this.array );
  17781. return z;
  17782. }
  17783. /**
  17784. * Returns the w component of the vector at the given index.
  17785. *
  17786. * @param {number} index - The index into the buffer attribute.
  17787. * @return {number} The w component.
  17788. */
  17789. getW( index ) {
  17790. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17791. if ( this.normalized ) w = denormalize( w, this.array );
  17792. return w;
  17793. }
  17794. /**
  17795. * Sets the x and y component of the vector at the given index.
  17796. *
  17797. * @param {number} index - The index into the buffer attribute.
  17798. * @param {number} x - The value for the x component to set.
  17799. * @param {number} y - The value for the y component to set.
  17800. * @return {InterleavedBufferAttribute} A reference to this instance.
  17801. */
  17802. setXY( index, x, y ) {
  17803. index = index * this.data.stride + this.offset;
  17804. if ( this.normalized ) {
  17805. x = normalize( x, this.array );
  17806. y = normalize( y, this.array );
  17807. }
  17808. this.data.array[ index + 0 ] = x;
  17809. this.data.array[ index + 1 ] = y;
  17810. return this;
  17811. }
  17812. /**
  17813. * Sets the x, y and z component of the vector at the given index.
  17814. *
  17815. * @param {number} index - The index into the buffer attribute.
  17816. * @param {number} x - The value for the x component to set.
  17817. * @param {number} y - The value for the y component to set.
  17818. * @param {number} z - The value for the z component to set.
  17819. * @return {InterleavedBufferAttribute} A reference to this instance.
  17820. */
  17821. setXYZ( index, x, y, z ) {
  17822. index = index * this.data.stride + this.offset;
  17823. if ( this.normalized ) {
  17824. x = normalize( x, this.array );
  17825. y = normalize( y, this.array );
  17826. z = normalize( z, this.array );
  17827. }
  17828. this.data.array[ index + 0 ] = x;
  17829. this.data.array[ index + 1 ] = y;
  17830. this.data.array[ index + 2 ] = z;
  17831. return this;
  17832. }
  17833. /**
  17834. * Sets the x, y, z and w component of the vector at the given index.
  17835. *
  17836. * @param {number} index - The index into the buffer attribute.
  17837. * @param {number} x - The value for the x component to set.
  17838. * @param {number} y - The value for the y component to set.
  17839. * @param {number} z - The value for the z component to set.
  17840. * @param {number} w - The value for the w component to set.
  17841. * @return {InterleavedBufferAttribute} A reference to this instance.
  17842. */
  17843. setXYZW( index, x, y, z, w ) {
  17844. index = index * this.data.stride + this.offset;
  17845. if ( this.normalized ) {
  17846. x = normalize( x, this.array );
  17847. y = normalize( y, this.array );
  17848. z = normalize( z, this.array );
  17849. w = normalize( w, this.array );
  17850. }
  17851. this.data.array[ index + 0 ] = x;
  17852. this.data.array[ index + 1 ] = y;
  17853. this.data.array[ index + 2 ] = z;
  17854. this.data.array[ index + 3 ] = w;
  17855. return this;
  17856. }
  17857. /**
  17858. * Returns a new buffer attribute with copied values from this instance.
  17859. *
  17860. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17861. *
  17862. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17863. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17864. */
  17865. clone( data ) {
  17866. if ( data === undefined ) {
  17867. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17868. const array = [];
  17869. for ( let i = 0; i < this.count; i ++ ) {
  17870. const index = i * this.data.stride + this.offset;
  17871. for ( let j = 0; j < this.itemSize; j ++ ) {
  17872. array.push( this.data.array[ index + j ] );
  17873. }
  17874. }
  17875. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17876. } else {
  17877. if ( data.interleavedBuffers === undefined ) {
  17878. data.interleavedBuffers = {};
  17879. }
  17880. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17881. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17882. }
  17883. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17884. }
  17885. }
  17886. /**
  17887. * Serializes the buffer attribute into JSON.
  17888. *
  17889. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17890. *
  17891. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17892. * @return {Object} A JSON object representing the serialized buffer attribute.
  17893. */
  17894. toJSON( data ) {
  17895. if ( data === undefined ) {
  17896. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17897. const array = [];
  17898. for ( let i = 0; i < this.count; i ++ ) {
  17899. const index = i * this.data.stride + this.offset;
  17900. for ( let j = 0; j < this.itemSize; j ++ ) {
  17901. array.push( this.data.array[ index + j ] );
  17902. }
  17903. }
  17904. // de-interleave data and save it as an ordinary buffer attribute for now
  17905. return {
  17906. itemSize: this.itemSize,
  17907. type: this.array.constructor.name,
  17908. array: array,
  17909. normalized: this.normalized
  17910. };
  17911. } else {
  17912. // save as true interleaved attribute
  17913. if ( data.interleavedBuffers === undefined ) {
  17914. data.interleavedBuffers = {};
  17915. }
  17916. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17917. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17918. }
  17919. return {
  17920. isInterleavedBufferAttribute: true,
  17921. itemSize: this.itemSize,
  17922. data: this.data.uuid,
  17923. offset: this.offset,
  17924. normalized: this.normalized
  17925. };
  17926. }
  17927. }
  17928. }
  17929. /**
  17930. * A material for rendering instances of {@link Sprite}.
  17931. *
  17932. * ```js
  17933. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17934. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17935. *
  17936. * const sprite = new THREE.Sprite( material );
  17937. * sprite.scale.set(200, 200, 1)
  17938. * scene.add( sprite );
  17939. * ```
  17940. *
  17941. * @augments Material
  17942. */
  17943. class SpriteMaterial extends Material {
  17944. /**
  17945. * Constructs a new sprite material.
  17946. *
  17947. * @param {Object} [parameters] - An object with one or more properties
  17948. * defining the material's appearance. Any property of the material
  17949. * (including any property from inherited materials) can be passed
  17950. * in here. Color values can be passed any type of value accepted
  17951. * by {@link Color#set}.
  17952. */
  17953. constructor( parameters ) {
  17954. super();
  17955. /**
  17956. * This flag can be used for type testing.
  17957. *
  17958. * @type {boolean}
  17959. * @readonly
  17960. * @default true
  17961. */
  17962. this.isSpriteMaterial = true;
  17963. this.type = 'SpriteMaterial';
  17964. /**
  17965. * Color of the material.
  17966. *
  17967. * @type {Color}
  17968. * @default (1,1,1)
  17969. */
  17970. this.color = new Color( 0xffffff );
  17971. /**
  17972. * The color map. May optionally include an alpha channel, typically combined
  17973. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17974. * color is modulated by the diffuse `color`.
  17975. *
  17976. * @type {?Texture}
  17977. * @default null
  17978. */
  17979. this.map = null;
  17980. /**
  17981. * The alpha map is a grayscale texture that controls the opacity across the
  17982. * surface (black: fully transparent; white: fully opaque).
  17983. *
  17984. * Only the color of the texture is used, ignoring the alpha channel if one
  17985. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17986. * when sampling this texture due to the extra bit of precision provided for
  17987. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17988. * luminance/alpha textures will also still work as expected.
  17989. *
  17990. * @type {?Texture}
  17991. * @default null
  17992. */
  17993. this.alphaMap = null;
  17994. /**
  17995. * The rotation of the sprite in radians.
  17996. *
  17997. * @type {number}
  17998. * @default 0
  17999. */
  18000. this.rotation = 0;
  18001. /**
  18002. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18003. *
  18004. * @type {boolean}
  18005. * @default true
  18006. */
  18007. this.sizeAttenuation = true;
  18008. /**
  18009. * Overwritten since sprite materials are transparent
  18010. * by default.
  18011. *
  18012. * @type {boolean}
  18013. * @default true
  18014. */
  18015. this.transparent = true;
  18016. /**
  18017. * Whether the material is affected by fog or not.
  18018. *
  18019. * @type {boolean}
  18020. * @default true
  18021. */
  18022. this.fog = true;
  18023. this.setValues( parameters );
  18024. }
  18025. copy( source ) {
  18026. super.copy( source );
  18027. this.color.copy( source.color );
  18028. this.map = source.map;
  18029. this.alphaMap = source.alphaMap;
  18030. this.rotation = source.rotation;
  18031. this.sizeAttenuation = source.sizeAttenuation;
  18032. this.fog = source.fog;
  18033. return this;
  18034. }
  18035. }
  18036. let _geometry;
  18037. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18038. const _worldScale = /*@__PURE__*/ new Vector3();
  18039. const _mvPosition = /*@__PURE__*/ new Vector3();
  18040. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18041. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18042. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18043. const _vA = /*@__PURE__*/ new Vector3();
  18044. const _vB = /*@__PURE__*/ new Vector3();
  18045. const _vC = /*@__PURE__*/ new Vector3();
  18046. const _uvA = /*@__PURE__*/ new Vector2();
  18047. const _uvB = /*@__PURE__*/ new Vector2();
  18048. const _uvC = /*@__PURE__*/ new Vector2();
  18049. /**
  18050. * A sprite is a plane that always faces towards the camera, generally with a
  18051. * partially transparent texture applied.
  18052. *
  18053. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18054. * have no effect.
  18055. *
  18056. * ```js
  18057. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18058. * const material = new THREE.SpriteMaterial( { map: map } );
  18059. *
  18060. * const sprite = new THREE.Sprite( material );
  18061. * scene.add( sprite );
  18062. * ```
  18063. *
  18064. * @augments Object3D
  18065. */
  18066. class Sprite extends Object3D {
  18067. /**
  18068. * Constructs a new sprite.
  18069. *
  18070. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18071. */
  18072. constructor( material = new SpriteMaterial() ) {
  18073. super();
  18074. /**
  18075. * This flag can be used for type testing.
  18076. *
  18077. * @type {boolean}
  18078. * @readonly
  18079. * @default true
  18080. */
  18081. this.isSprite = true;
  18082. this.type = 'Sprite';
  18083. if ( _geometry === undefined ) {
  18084. _geometry = new BufferGeometry();
  18085. const float32Array = new Float32Array( [
  18086. -0.5, -0.5, 0, 0, 0,
  18087. 0.5, -0.5, 0, 1, 0,
  18088. 0.5, 0.5, 0, 1, 1,
  18089. -0.5, 0.5, 0, 0, 1
  18090. ] );
  18091. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18092. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18093. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18094. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18095. }
  18096. /**
  18097. * The sprite geometry.
  18098. *
  18099. * @type {BufferGeometry}
  18100. */
  18101. this.geometry = _geometry;
  18102. /**
  18103. * The sprite material.
  18104. *
  18105. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18106. */
  18107. this.material = material;
  18108. /**
  18109. * The sprite's anchor point, and the point around which the sprite rotates.
  18110. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18111. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18112. *
  18113. * @type {Vector2}
  18114. * @default (0.5,0.5)
  18115. */
  18116. this.center = new Vector2( 0.5, 0.5 );
  18117. /**
  18118. * The number of instances of this sprite.
  18119. * Can only be used with {@link WebGPURenderer}.
  18120. *
  18121. * @type {number}
  18122. * @default 1
  18123. */
  18124. this.count = 1;
  18125. }
  18126. /**
  18127. * Computes intersection points between a casted ray and this sprite.
  18128. *
  18129. * @param {Raycaster} raycaster - The raycaster.
  18130. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18131. */
  18132. raycast( raycaster, intersects ) {
  18133. if ( raycaster.camera === null ) {
  18134. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18135. }
  18136. _worldScale.setFromMatrixScale( this.matrixWorld );
  18137. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18138. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18139. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18140. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18141. _worldScale.multiplyScalar( - _mvPosition.z );
  18142. }
  18143. const rotation = this.material.rotation;
  18144. let sin, cos;
  18145. if ( rotation !== 0 ) {
  18146. cos = Math.cos( rotation );
  18147. sin = Math.sin( rotation );
  18148. }
  18149. const center = this.center;
  18150. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18151. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18152. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18153. _uvA.set( 0, 0 );
  18154. _uvB.set( 1, 0 );
  18155. _uvC.set( 1, 1 );
  18156. // check first triangle
  18157. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18158. if ( intersect === null ) {
  18159. // check second triangle
  18160. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18161. _uvB.set( 0, 1 );
  18162. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18163. if ( intersect === null ) {
  18164. return;
  18165. }
  18166. }
  18167. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18168. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18169. intersects.push( {
  18170. distance: distance,
  18171. point: _intersectPoint.clone(),
  18172. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18173. face: null,
  18174. object: this
  18175. } );
  18176. }
  18177. copy( source, recursive ) {
  18178. super.copy( source, recursive );
  18179. if ( source.center !== undefined ) this.center.copy( source.center );
  18180. this.material = source.material;
  18181. return this;
  18182. }
  18183. }
  18184. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18185. // compute position in camera space
  18186. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18187. // to check if rotation is not zero
  18188. if ( sin !== undefined ) {
  18189. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18190. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18191. } else {
  18192. _rotatedPosition.copy( _alignedPosition );
  18193. }
  18194. vertexPosition.copy( mvPosition );
  18195. vertexPosition.x += _rotatedPosition.x;
  18196. vertexPosition.y += _rotatedPosition.y;
  18197. // transform to world space
  18198. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18199. }
  18200. const _v1$2 = /*@__PURE__*/ new Vector3();
  18201. const _v2$1 = /*@__PURE__*/ new Vector3();
  18202. /**
  18203. * A component for providing a basic Level of Detail (LOD) mechanism.
  18204. *
  18205. * Every LOD level is associated with an object, and rendering can be switched
  18206. * between them at the distances specified. Typically you would create, say,
  18207. * three meshes, one for far away (low detail), one for mid range (medium
  18208. * detail) and one for close up (high detail).
  18209. *
  18210. * ```js
  18211. * const lod = new THREE.LOD();
  18212. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18213. *
  18214. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18215. * for( let i = 0; i < 3; i++ ) {
  18216. *
  18217. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18218. * const mesh = new THREE.Mesh( geometry, material );
  18219. * lod.addLevel( mesh, i * 75 );
  18220. *
  18221. * }
  18222. *
  18223. * scene.add( lod );
  18224. * ```
  18225. *
  18226. * @augments Object3D
  18227. */
  18228. class LOD extends Object3D {
  18229. /**
  18230. * Constructs a new LOD.
  18231. */
  18232. constructor() {
  18233. super();
  18234. /**
  18235. * This flag can be used for type testing.
  18236. *
  18237. * @type {boolean}
  18238. * @readonly
  18239. * @default true
  18240. */
  18241. this.isLOD = true;
  18242. /**
  18243. * The current LOD index.
  18244. *
  18245. * @private
  18246. * @type {number}
  18247. * @default 0
  18248. */
  18249. this._currentLevel = 0;
  18250. this.type = 'LOD';
  18251. Object.defineProperties( this, {
  18252. /**
  18253. * This array holds the LOD levels.
  18254. *
  18255. * @name LOD#levels
  18256. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18257. */
  18258. levels: {
  18259. enumerable: true,
  18260. value: []
  18261. }
  18262. } );
  18263. /**
  18264. * Whether the LOD object is updated automatically by the renderer per frame
  18265. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18266. * render loop by yourself.
  18267. *
  18268. * @type {boolean}
  18269. * @default true
  18270. */
  18271. this.autoUpdate = true;
  18272. }
  18273. copy( source ) {
  18274. super.copy( source, false );
  18275. const levels = source.levels;
  18276. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18277. const level = levels[ i ];
  18278. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18279. }
  18280. this.autoUpdate = source.autoUpdate;
  18281. return this;
  18282. }
  18283. /**
  18284. * Adds a mesh that will display at a certain distance and greater. Typically
  18285. * the further away the distance, the lower the detail on the mesh.
  18286. *
  18287. * @param {Object3D} object - The 3D object to display at this level.
  18288. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18289. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18290. * @return {LOD} A reference to this instance.
  18291. */
  18292. addLevel( object, distance = 0, hysteresis = 0 ) {
  18293. distance = Math.abs( distance );
  18294. const levels = this.levels;
  18295. let l;
  18296. for ( l = 0; l < levels.length; l ++ ) {
  18297. if ( distance < levels[ l ].distance ) {
  18298. break;
  18299. }
  18300. }
  18301. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18302. this.add( object );
  18303. return this;
  18304. }
  18305. /**
  18306. * Removes an existing level, based on the distance from the camera.
  18307. * Returns `true` when the level has been removed. Otherwise `false`.
  18308. *
  18309. * @param {number} distance - Distance of the level to remove.
  18310. * @return {boolean} Whether the level has been removed or not.
  18311. */
  18312. removeLevel( distance ) {
  18313. const levels = this.levels;
  18314. for ( let i = 0; i < levels.length; i ++ ) {
  18315. if ( levels[ i ].distance === distance ) {
  18316. const removedElements = levels.splice( i, 1 );
  18317. this.remove( removedElements[ 0 ].object );
  18318. return true;
  18319. }
  18320. }
  18321. return false;
  18322. }
  18323. /**
  18324. * Returns the currently active LOD level index.
  18325. *
  18326. * @return {number} The current active LOD level index.
  18327. */
  18328. getCurrentLevel() {
  18329. return this._currentLevel;
  18330. }
  18331. /**
  18332. * Returns a reference to the first 3D object that is greater than
  18333. * the given distance.
  18334. *
  18335. * @param {number} distance - The LOD distance.
  18336. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18337. */
  18338. getObjectForDistance( distance ) {
  18339. const levels = this.levels;
  18340. if ( levels.length > 0 ) {
  18341. let i, l;
  18342. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18343. let levelDistance = levels[ i ].distance;
  18344. if ( levels[ i ].object.visible ) {
  18345. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18346. }
  18347. if ( distance < levelDistance ) {
  18348. break;
  18349. }
  18350. }
  18351. return levels[ i - 1 ].object;
  18352. }
  18353. return null;
  18354. }
  18355. /**
  18356. * Computes intersection points between a casted ray and this LOD.
  18357. *
  18358. * @param {Raycaster} raycaster - The raycaster.
  18359. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18360. */
  18361. raycast( raycaster, intersects ) {
  18362. const levels = this.levels;
  18363. if ( levels.length > 0 ) {
  18364. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18365. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18366. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18367. }
  18368. }
  18369. /**
  18370. * Updates the LOD by computing which LOD level should be visible according
  18371. * to the current distance of the given camera.
  18372. *
  18373. * @param {Camera} camera - The camera the scene is rendered with.
  18374. */
  18375. update( camera ) {
  18376. const levels = this.levels;
  18377. if ( levels.length > 1 ) {
  18378. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18379. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18380. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18381. levels[ 0 ].object.visible = true;
  18382. let i, l;
  18383. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18384. let levelDistance = levels[ i ].distance;
  18385. if ( levels[ i ].object.visible ) {
  18386. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18387. }
  18388. if ( distance >= levelDistance ) {
  18389. levels[ i - 1 ].object.visible = false;
  18390. levels[ i ].object.visible = true;
  18391. } else {
  18392. break;
  18393. }
  18394. }
  18395. this._currentLevel = i - 1;
  18396. for ( ; i < l; i ++ ) {
  18397. levels[ i ].object.visible = false;
  18398. }
  18399. }
  18400. }
  18401. toJSON( meta ) {
  18402. const data = super.toJSON( meta );
  18403. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18404. data.object.levels = [];
  18405. const levels = this.levels;
  18406. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18407. const level = levels[ i ];
  18408. data.object.levels.push( {
  18409. object: level.object.uuid,
  18410. distance: level.distance,
  18411. hysteresis: level.hysteresis
  18412. } );
  18413. }
  18414. return data;
  18415. }
  18416. }
  18417. const _basePosition = /*@__PURE__*/ new Vector3();
  18418. const _skinIndex = /*@__PURE__*/ new Vector4();
  18419. const _skinWeight = /*@__PURE__*/ new Vector4();
  18420. const _vector3 = /*@__PURE__*/ new Vector3();
  18421. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18422. const _vertex = /*@__PURE__*/ new Vector3();
  18423. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18424. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18425. const _ray$2 = /*@__PURE__*/ new Ray();
  18426. /**
  18427. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18428. * vertices of the geometry with skinning/skeleton animation.
  18429. *
  18430. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18431. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18432. * vertex to a certain extend.
  18433. *
  18434. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18435. * or {@link FBXLoader } import respective models.
  18436. *
  18437. * @augments Mesh
  18438. * @demo scenes/bones-browser.html
  18439. */
  18440. class SkinnedMesh extends Mesh {
  18441. /**
  18442. * Constructs a new skinned mesh.
  18443. *
  18444. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18445. * @param {Material|Array<Material>} [material] - The mesh material.
  18446. */
  18447. constructor( geometry, material ) {
  18448. super( geometry, material );
  18449. /**
  18450. * This flag can be used for type testing.
  18451. *
  18452. * @type {boolean}
  18453. * @readonly
  18454. * @default true
  18455. */
  18456. this.isSkinnedMesh = true;
  18457. this.type = 'SkinnedMesh';
  18458. /**
  18459. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18460. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18461. * across multiple skinned meshes.
  18462. *
  18463. * @type {(AttachedBindMode|DetachedBindMode)}
  18464. * @default AttachedBindMode
  18465. */
  18466. this.bindMode = AttachedBindMode;
  18467. /**
  18468. * The base matrix that is used for the bound bone transforms.
  18469. *
  18470. * @type {Matrix4}
  18471. */
  18472. this.bindMatrix = new Matrix4();
  18473. /**
  18474. * The base matrix that is used for resetting the bound bone transforms.
  18475. *
  18476. * @type {Matrix4}
  18477. */
  18478. this.bindMatrixInverse = new Matrix4();
  18479. /**
  18480. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18481. *
  18482. * @type {?Box3}
  18483. * @default null
  18484. */
  18485. this.boundingBox = null;
  18486. /**
  18487. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18488. *
  18489. * @type {?Sphere}
  18490. * @default null
  18491. */
  18492. this.boundingSphere = null;
  18493. }
  18494. /**
  18495. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18496. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18497. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18498. * the current animation state.
  18499. */
  18500. computeBoundingBox() {
  18501. const geometry = this.geometry;
  18502. if ( this.boundingBox === null ) {
  18503. this.boundingBox = new Box3();
  18504. }
  18505. this.boundingBox.makeEmpty();
  18506. const positionAttribute = geometry.getAttribute( 'position' );
  18507. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18508. this.getVertexPosition( i, _vertex );
  18509. this.boundingBox.expandByPoint( _vertex );
  18510. }
  18511. }
  18512. /**
  18513. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18514. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18515. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18516. * per frame in order to reflect the current animation state.
  18517. */
  18518. computeBoundingSphere() {
  18519. const geometry = this.geometry;
  18520. if ( this.boundingSphere === null ) {
  18521. this.boundingSphere = new Sphere();
  18522. }
  18523. this.boundingSphere.makeEmpty();
  18524. const positionAttribute = geometry.getAttribute( 'position' );
  18525. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18526. this.getVertexPosition( i, _vertex );
  18527. this.boundingSphere.expandByPoint( _vertex );
  18528. }
  18529. }
  18530. copy( source, recursive ) {
  18531. super.copy( source, recursive );
  18532. this.bindMode = source.bindMode;
  18533. this.bindMatrix.copy( source.bindMatrix );
  18534. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18535. this.skeleton = source.skeleton;
  18536. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18537. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18538. return this;
  18539. }
  18540. raycast( raycaster, intersects ) {
  18541. const material = this.material;
  18542. const matrixWorld = this.matrixWorld;
  18543. if ( material === undefined ) return;
  18544. // test with bounding sphere in world space
  18545. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18546. _sphere$5.copy( this.boundingSphere );
  18547. _sphere$5.applyMatrix4( matrixWorld );
  18548. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18549. // convert ray to local space of skinned mesh
  18550. _inverseMatrix$2.copy( matrixWorld ).invert();
  18551. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18552. // test with bounding box in local space
  18553. if ( this.boundingBox !== null ) {
  18554. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18555. }
  18556. // test for intersections with geometry
  18557. this._computeIntersections( raycaster, intersects, _ray$2 );
  18558. }
  18559. getVertexPosition( index, target ) {
  18560. super.getVertexPosition( index, target );
  18561. this.applyBoneTransform( index, target );
  18562. return target;
  18563. }
  18564. /**
  18565. * Binds the given skeleton to the skinned mesh.
  18566. *
  18567. * @param {Skeleton} skeleton - The skeleton to bind.
  18568. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18569. * the skinned mesh's world matrix will be used instead.
  18570. */
  18571. bind( skeleton, bindMatrix ) {
  18572. this.skeleton = skeleton;
  18573. if ( bindMatrix === undefined ) {
  18574. this.updateMatrixWorld( true );
  18575. this.skeleton.calculateInverses();
  18576. bindMatrix = this.matrixWorld;
  18577. }
  18578. this.bindMatrix.copy( bindMatrix );
  18579. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18580. }
  18581. /**
  18582. * This method sets the skinned mesh in the rest pose).
  18583. */
  18584. pose() {
  18585. this.skeleton.pose();
  18586. }
  18587. /**
  18588. * Normalizes the skin weights which are defined as a buffer attribute
  18589. * in the skinned mesh's geometry.
  18590. */
  18591. normalizeSkinWeights() {
  18592. const vector = new Vector4();
  18593. const skinWeight = this.geometry.attributes.skinWeight;
  18594. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18595. vector.fromBufferAttribute( skinWeight, i );
  18596. const scale = 1.0 / vector.manhattanLength();
  18597. if ( scale !== Infinity ) {
  18598. vector.multiplyScalar( scale );
  18599. } else {
  18600. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18601. }
  18602. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18603. }
  18604. }
  18605. updateMatrixWorld( force ) {
  18606. super.updateMatrixWorld( force );
  18607. if ( this.bindMode === AttachedBindMode ) {
  18608. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18609. } else if ( this.bindMode === DetachedBindMode ) {
  18610. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18611. } else {
  18612. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18613. }
  18614. }
  18615. /**
  18616. * Applies the bone transform associated with the given index to the given
  18617. * vertex position. Returns the updated vector.
  18618. *
  18619. * @param {number} index - The vertex index.
  18620. * @param {Vector3} target - The target object that is used to store the method's result.
  18621. * the skinned mesh's world matrix will be used instead.
  18622. * @return {Vector3} The updated vertex position.
  18623. */
  18624. applyBoneTransform( index, target ) {
  18625. const skeleton = this.skeleton;
  18626. const geometry = this.geometry;
  18627. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18628. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18629. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18630. target.set( 0, 0, 0 );
  18631. for ( let i = 0; i < 4; i ++ ) {
  18632. const weight = _skinWeight.getComponent( i );
  18633. if ( weight !== 0 ) {
  18634. const boneIndex = _skinIndex.getComponent( i );
  18635. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18636. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18637. }
  18638. }
  18639. return target.applyMatrix4( this.bindMatrixInverse );
  18640. }
  18641. }
  18642. /**
  18643. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18644. * the {@link SkinnedMesh}.
  18645. *
  18646. * ```js
  18647. * const root = new THREE.Bone();
  18648. * const child = new THREE.Bone();
  18649. *
  18650. * root.add( child );
  18651. * child.position.y = 5;
  18652. * ```
  18653. *
  18654. * @augments Object3D
  18655. */
  18656. class Bone extends Object3D {
  18657. /**
  18658. * Constructs a new bone.
  18659. */
  18660. constructor() {
  18661. super();
  18662. /**
  18663. * This flag can be used for type testing.
  18664. *
  18665. * @type {boolean}
  18666. * @readonly
  18667. * @default true
  18668. */
  18669. this.isBone = true;
  18670. this.type = 'Bone';
  18671. }
  18672. }
  18673. /**
  18674. * Creates a texture directly from raw buffer data.
  18675. *
  18676. * The interpretation of the data depends on type and format: If the type is
  18677. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18678. * texel data. If the format is `RGBAFormat`, data needs four values for
  18679. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18680. *
  18681. * @augments Texture
  18682. */
  18683. class DataTexture extends Texture {
  18684. /**
  18685. * Constructs a new data texture.
  18686. *
  18687. * @param {?TypedArray} [data=null] - The buffer data.
  18688. * @param {number} [width=1] - The width of the texture.
  18689. * @param {number} [height=1] - The height of the texture.
  18690. * @param {number} [format=RGBAFormat] - The texture format.
  18691. * @param {number} [type=UnsignedByteType] - The texture type.
  18692. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18693. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18694. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18695. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18696. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18697. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18698. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18699. */
  18700. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18701. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18702. /**
  18703. * This flag can be used for type testing.
  18704. *
  18705. * @type {boolean}
  18706. * @readonly
  18707. * @default true
  18708. */
  18709. this.isDataTexture = true;
  18710. /**
  18711. * The image definition of a data texture.
  18712. *
  18713. * @type {{data:TypedArray,width:number,height:number}}
  18714. */
  18715. this.image = { data: data, width: width, height: height };
  18716. /**
  18717. * Whether to generate mipmaps (if possible) for a texture.
  18718. *
  18719. * Overwritten and set to `false` by default.
  18720. *
  18721. * @type {boolean}
  18722. * @default false
  18723. */
  18724. this.generateMipmaps = false;
  18725. /**
  18726. * If set to `true`, the texture is flipped along the vertical axis when
  18727. * uploaded to the GPU.
  18728. *
  18729. * Overwritten and set to `false` by default.
  18730. *
  18731. * @type {boolean}
  18732. * @default false
  18733. */
  18734. this.flipY = false;
  18735. /**
  18736. * Specifies the alignment requirements for the start of each pixel row in memory.
  18737. *
  18738. * Overwritten and set to `1` by default.
  18739. *
  18740. * @type {boolean}
  18741. * @default 1
  18742. */
  18743. this.unpackAlignment = 1;
  18744. }
  18745. }
  18746. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18747. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18748. /**
  18749. * Class for representing the armatures in `three.js`. The skeleton
  18750. * is defined by a hierarchy of bones.
  18751. *
  18752. * ```js
  18753. * const bones = [];
  18754. *
  18755. * const shoulder = new THREE.Bone();
  18756. * const elbow = new THREE.Bone();
  18757. * const hand = new THREE.Bone();
  18758. *
  18759. * shoulder.add( elbow );
  18760. * elbow.add( hand );
  18761. *
  18762. * bones.push( shoulder , elbow, hand);
  18763. *
  18764. * shoulder.position.y = -5;
  18765. * elbow.position.y = 0;
  18766. * hand.position.y = 5;
  18767. *
  18768. * const armSkeleton = new THREE.Skeleton( bones );
  18769. * ```
  18770. */
  18771. class Skeleton {
  18772. /**
  18773. * Constructs a new skeleton.
  18774. *
  18775. * @param {Array<Bone>} [bones] - An array of bones.
  18776. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18777. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18778. */
  18779. constructor( bones = [], boneInverses = [] ) {
  18780. this.uuid = generateUUID();
  18781. /**
  18782. * An array of bones defining the skeleton.
  18783. *
  18784. * @type {Array<Bone>}
  18785. */
  18786. this.bones = bones.slice( 0 );
  18787. /**
  18788. * An array of bone inverse matrices.
  18789. *
  18790. * @type {Array<Matrix4>}
  18791. */
  18792. this.boneInverses = boneInverses;
  18793. /**
  18794. * An array buffer holding the bone data.
  18795. * Input data for {@link Skeleton#boneTexture}.
  18796. *
  18797. * @type {?Float32Array}
  18798. * @default null
  18799. */
  18800. this.boneMatrices = null;
  18801. /**
  18802. * An array buffer holding the bone data of the previous frame.
  18803. * Required for computing velocity. Maintained in {@link SkinningNode}.
  18804. *
  18805. * @type {?Float32Array}
  18806. * @default null
  18807. */
  18808. this.previousBoneMatrices = null;
  18809. /**
  18810. * A texture holding the bone data for use
  18811. * in the vertex shader.
  18812. *
  18813. * @type {?DataTexture}
  18814. * @default null
  18815. */
  18816. this.boneTexture = null;
  18817. this.init();
  18818. }
  18819. /**
  18820. * Initializes the skeleton. This method gets automatically called by the constructor
  18821. * but depending on how the skeleton is created it might be necessary to call this method
  18822. * manually.
  18823. */
  18824. init() {
  18825. const bones = this.bones;
  18826. const boneInverses = this.boneInverses;
  18827. this.boneMatrices = new Float32Array( bones.length * 16 );
  18828. // calculate inverse bone matrices if necessary
  18829. if ( boneInverses.length === 0 ) {
  18830. this.calculateInverses();
  18831. } else {
  18832. // handle special case
  18833. if ( bones.length !== boneInverses.length ) {
  18834. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18835. this.boneInverses = [];
  18836. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18837. this.boneInverses.push( new Matrix4() );
  18838. }
  18839. }
  18840. }
  18841. }
  18842. /**
  18843. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18844. * and fills it with new matrices.
  18845. */
  18846. calculateInverses() {
  18847. this.boneInverses.length = 0;
  18848. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18849. const inverse = new Matrix4();
  18850. if ( this.bones[ i ] ) {
  18851. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18852. }
  18853. this.boneInverses.push( inverse );
  18854. }
  18855. }
  18856. /**
  18857. * Resets the skeleton to the base pose.
  18858. */
  18859. pose() {
  18860. // recover the bind-time world matrices
  18861. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18862. const bone = this.bones[ i ];
  18863. if ( bone ) {
  18864. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18865. }
  18866. }
  18867. // compute the local matrices, positions, rotations and scales
  18868. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18869. const bone = this.bones[ i ];
  18870. if ( bone ) {
  18871. if ( bone.parent && bone.parent.isBone ) {
  18872. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18873. bone.matrix.multiply( bone.matrixWorld );
  18874. } else {
  18875. bone.matrix.copy( bone.matrixWorld );
  18876. }
  18877. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18878. }
  18879. }
  18880. }
  18881. /**
  18882. * Resets the skeleton to the base pose.
  18883. */
  18884. update() {
  18885. const bones = this.bones;
  18886. const boneInverses = this.boneInverses;
  18887. const boneMatrices = this.boneMatrices;
  18888. const boneTexture = this.boneTexture;
  18889. // flatten bone matrices to array
  18890. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18891. // compute the offset between the current and the original transform
  18892. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18893. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18894. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18895. }
  18896. if ( boneTexture !== null ) {
  18897. boneTexture.needsUpdate = true;
  18898. }
  18899. }
  18900. /**
  18901. * Returns a new skeleton with copied values from this instance.
  18902. *
  18903. * @return {Skeleton} A clone of this instance.
  18904. */
  18905. clone() {
  18906. return new Skeleton( this.bones, this.boneInverses );
  18907. }
  18908. /**
  18909. * Computes a data texture for passing bone data to the vertex shader.
  18910. *
  18911. * @return {Skeleton} A reference of this instance.
  18912. */
  18913. computeBoneTexture() {
  18914. // layout (1 matrix = 4 pixels)
  18915. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18916. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18917. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18918. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18919. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18920. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18921. size = Math.ceil( size / 4 ) * 4;
  18922. size = Math.max( size, 4 );
  18923. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18924. boneMatrices.set( this.boneMatrices ); // copy current values
  18925. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18926. boneTexture.needsUpdate = true;
  18927. this.boneMatrices = boneMatrices;
  18928. this.boneTexture = boneTexture;
  18929. return this;
  18930. }
  18931. /**
  18932. * Searches through the skeleton's bone array and returns the first with a
  18933. * matching name.
  18934. *
  18935. * @param {string} name - The name of the bone.
  18936. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18937. */
  18938. getBoneByName( name ) {
  18939. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18940. const bone = this.bones[ i ];
  18941. if ( bone.name === name ) {
  18942. return bone;
  18943. }
  18944. }
  18945. return undefined;
  18946. }
  18947. /**
  18948. * Frees the GPU-related resources allocated by this instance. Call this
  18949. * method whenever this instance is no longer used in your app.
  18950. */
  18951. dispose( ) {
  18952. if ( this.boneTexture !== null ) {
  18953. this.boneTexture.dispose();
  18954. this.boneTexture = null;
  18955. }
  18956. }
  18957. /**
  18958. * Setups the skeleton by the given JSON and bones.
  18959. *
  18960. * @param {Object} json - The skeleton as serialized JSON.
  18961. * @param {Object<string, Bone>} bones - An array of bones.
  18962. * @return {Skeleton} A reference of this instance.
  18963. */
  18964. fromJSON( json, bones ) {
  18965. this.uuid = json.uuid;
  18966. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18967. const uuid = json.bones[ i ];
  18968. let bone = bones[ uuid ];
  18969. if ( bone === undefined ) {
  18970. warn( 'Skeleton: No bone found with UUID:', uuid );
  18971. bone = new Bone();
  18972. }
  18973. this.bones.push( bone );
  18974. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18975. }
  18976. this.init();
  18977. return this;
  18978. }
  18979. /**
  18980. * Serializes the skeleton into JSON.
  18981. *
  18982. * @return {Object} A JSON object representing the serialized skeleton.
  18983. * @see {@link ObjectLoader#parse}
  18984. */
  18985. toJSON() {
  18986. const data = {
  18987. metadata: {
  18988. version: 4.7,
  18989. type: 'Skeleton',
  18990. generator: 'Skeleton.toJSON'
  18991. },
  18992. bones: [],
  18993. boneInverses: []
  18994. };
  18995. data.uuid = this.uuid;
  18996. const bones = this.bones;
  18997. const boneInverses = this.boneInverses;
  18998. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18999. const bone = bones[ i ];
  19000. data.bones.push( bone.uuid );
  19001. const boneInverse = boneInverses[ i ];
  19002. data.boneInverses.push( boneInverse.toArray() );
  19003. }
  19004. return data;
  19005. }
  19006. }
  19007. /**
  19008. * An instanced version of a buffer attribute.
  19009. *
  19010. * @augments BufferAttribute
  19011. */
  19012. class InstancedBufferAttribute extends BufferAttribute {
  19013. /**
  19014. * Constructs a new instanced buffer attribute.
  19015. *
  19016. * @param {TypedArray} array - The array holding the attribute data.
  19017. * @param {number} itemSize - The item size.
  19018. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19019. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19020. */
  19021. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19022. super( array, itemSize, normalized );
  19023. /**
  19024. * This flag can be used for type testing.
  19025. *
  19026. * @type {boolean}
  19027. * @readonly
  19028. * @default true
  19029. */
  19030. this.isInstancedBufferAttribute = true;
  19031. /**
  19032. * Defines how often a value of this buffer attribute should be repeated. A
  19033. * value of one means that each value of the instanced attribute is used for
  19034. * a single instance. A value of two means that each value is used for two
  19035. * consecutive instances (and so on).
  19036. *
  19037. * @type {number}
  19038. * @default 1
  19039. */
  19040. this.meshPerAttribute = meshPerAttribute;
  19041. }
  19042. copy( source ) {
  19043. super.copy( source );
  19044. this.meshPerAttribute = source.meshPerAttribute;
  19045. return this;
  19046. }
  19047. toJSON() {
  19048. const data = super.toJSON();
  19049. data.meshPerAttribute = this.meshPerAttribute;
  19050. data.isInstancedBufferAttribute = true;
  19051. return data;
  19052. }
  19053. }
  19054. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19055. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19056. const _instanceIntersects = [];
  19057. const _box3 = /*@__PURE__*/ new Box3();
  19058. const _identity = /*@__PURE__*/ new Matrix4();
  19059. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19060. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19061. /**
  19062. * A special version of a mesh with instanced rendering support. Use
  19063. * this class if you have to render a large number of objects with the same
  19064. * geometry and material(s) but with different world transformations. The usage
  19065. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19066. * improve the overall rendering performance in your application.
  19067. *
  19068. * @augments Mesh
  19069. */
  19070. class InstancedMesh extends Mesh {
  19071. /**
  19072. * Constructs a new instanced mesh.
  19073. *
  19074. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19075. * @param {Material|Array<Material>} [material] - The mesh material.
  19076. * @param {number} count - The number of instances.
  19077. */
  19078. constructor( geometry, material, count ) {
  19079. super( geometry, material );
  19080. /**
  19081. * This flag can be used for type testing.
  19082. *
  19083. * @type {boolean}
  19084. * @readonly
  19085. * @default true
  19086. */
  19087. this.isInstancedMesh = true;
  19088. /**
  19089. * Represents the local transformation of all instances. You have to set its
  19090. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19091. * via {@link InstancedMesh#setMatrixAt}.
  19092. *
  19093. * @type {InstancedBufferAttribute}
  19094. */
  19095. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19096. /**
  19097. * Represents the color of all instances. You have to set its
  19098. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19099. * via {@link InstancedMesh#setColorAt}.
  19100. *
  19101. * @type {?InstancedBufferAttribute}
  19102. * @default null
  19103. */
  19104. this.instanceColor = null;
  19105. /**
  19106. * Represents the morph target weights of all instances. You have to set its
  19107. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19108. * via {@link InstancedMesh#setMorphAt}.
  19109. *
  19110. * @type {?DataTexture}
  19111. * @default null
  19112. */
  19113. this.morphTexture = null;
  19114. /**
  19115. * The number of instances.
  19116. *
  19117. * @type {number}
  19118. */
  19119. this.count = count;
  19120. /**
  19121. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19122. *
  19123. * @type {?Box3}
  19124. * @default null
  19125. */
  19126. this.boundingBox = null;
  19127. /**
  19128. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19129. *
  19130. * @type {?Sphere}
  19131. * @default null
  19132. */
  19133. this.boundingSphere = null;
  19134. for ( let i = 0; i < count; i ++ ) {
  19135. this.setMatrixAt( i, _identity );
  19136. }
  19137. }
  19138. /**
  19139. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19140. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19141. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19142. */
  19143. computeBoundingBox() {
  19144. const geometry = this.geometry;
  19145. const count = this.count;
  19146. if ( this.boundingBox === null ) {
  19147. this.boundingBox = new Box3();
  19148. }
  19149. if ( geometry.boundingBox === null ) {
  19150. geometry.computeBoundingBox();
  19151. }
  19152. this.boundingBox.makeEmpty();
  19153. for ( let i = 0; i < count; i ++ ) {
  19154. this.getMatrixAt( i, _instanceLocalMatrix );
  19155. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19156. this.boundingBox.union( _box3 );
  19157. }
  19158. }
  19159. /**
  19160. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19161. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19162. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19163. */
  19164. computeBoundingSphere() {
  19165. const geometry = this.geometry;
  19166. const count = this.count;
  19167. if ( this.boundingSphere === null ) {
  19168. this.boundingSphere = new Sphere();
  19169. }
  19170. if ( geometry.boundingSphere === null ) {
  19171. geometry.computeBoundingSphere();
  19172. }
  19173. this.boundingSphere.makeEmpty();
  19174. for ( let i = 0; i < count; i ++ ) {
  19175. this.getMatrixAt( i, _instanceLocalMatrix );
  19176. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19177. this.boundingSphere.union( _sphere$4 );
  19178. }
  19179. }
  19180. copy( source, recursive ) {
  19181. super.copy( source, recursive );
  19182. this.instanceMatrix.copy( source.instanceMatrix );
  19183. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19184. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19185. this.count = source.count;
  19186. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19187. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19188. return this;
  19189. }
  19190. /**
  19191. * Gets the color of the defined instance.
  19192. *
  19193. * @param {number} index - The instance index.
  19194. * @param {Color} color - The target object that is used to store the method's result.
  19195. */
  19196. getColorAt( index, color ) {
  19197. color.fromArray( this.instanceColor.array, index * 3 );
  19198. }
  19199. /**
  19200. * Gets the local transformation matrix of the defined instance.
  19201. *
  19202. * @param {number} index - The instance index.
  19203. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19204. */
  19205. getMatrixAt( index, matrix ) {
  19206. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19207. }
  19208. /**
  19209. * Gets the morph target weights of the defined instance.
  19210. *
  19211. * @param {number} index - The instance index.
  19212. * @param {Mesh} object - The target object that is used to store the method's result.
  19213. */
  19214. getMorphAt( index, object ) {
  19215. const objectInfluences = object.morphTargetInfluences;
  19216. const array = this.morphTexture.source.data.data;
  19217. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19218. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19219. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19220. objectInfluences[ i ] = array[ dataIndex + i ];
  19221. }
  19222. }
  19223. raycast( raycaster, intersects ) {
  19224. const matrixWorld = this.matrixWorld;
  19225. const raycastTimes = this.count;
  19226. _mesh$1.geometry = this.geometry;
  19227. _mesh$1.material = this.material;
  19228. if ( _mesh$1.material === undefined ) return;
  19229. // test with bounding sphere first
  19230. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19231. _sphere$4.copy( this.boundingSphere );
  19232. _sphere$4.applyMatrix4( matrixWorld );
  19233. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19234. // now test each instance
  19235. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19236. // calculate the world matrix for each instance
  19237. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19238. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19239. // the mesh represents this single instance
  19240. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19241. _mesh$1.raycast( raycaster, _instanceIntersects );
  19242. // process the result of raycast
  19243. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19244. const intersect = _instanceIntersects[ i ];
  19245. intersect.instanceId = instanceId;
  19246. intersect.object = this;
  19247. intersects.push( intersect );
  19248. }
  19249. _instanceIntersects.length = 0;
  19250. }
  19251. }
  19252. /**
  19253. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19254. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19255. *
  19256. * @param {number} index - The instance index.
  19257. * @param {Color} color - The instance color.
  19258. */
  19259. setColorAt( index, color ) {
  19260. if ( this.instanceColor === null ) {
  19261. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19262. }
  19263. color.toArray( this.instanceColor.array, index * 3 );
  19264. }
  19265. /**
  19266. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19267. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19268. *
  19269. * @param {number} index - The instance index.
  19270. * @param {Matrix4} matrix - The local transformation.
  19271. */
  19272. setMatrixAt( index, matrix ) {
  19273. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19274. }
  19275. /**
  19276. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19277. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19278. *
  19279. * @param {number} index - The instance index.
  19280. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19281. * of a single instance.
  19282. */
  19283. setMorphAt( index, object ) {
  19284. const objectInfluences = object.morphTargetInfluences;
  19285. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19286. if ( this.morphTexture === null ) {
  19287. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19288. }
  19289. const array = this.morphTexture.source.data.data;
  19290. let morphInfluencesSum = 0;
  19291. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19292. morphInfluencesSum += objectInfluences[ i ];
  19293. }
  19294. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19295. const dataIndex = len * index;
  19296. array[ dataIndex ] = morphBaseInfluence;
  19297. array.set( objectInfluences, dataIndex + 1 );
  19298. }
  19299. updateMorphTargets() {
  19300. }
  19301. /**
  19302. * Frees the GPU-related resources allocated by this instance. Call this
  19303. * method whenever this instance is no longer used in your app.
  19304. */
  19305. dispose() {
  19306. this.dispatchEvent( { type: 'dispose' } );
  19307. if ( this.morphTexture !== null ) {
  19308. this.morphTexture.dispose();
  19309. this.morphTexture = null;
  19310. }
  19311. }
  19312. }
  19313. const _vector1 = /*@__PURE__*/ new Vector3();
  19314. const _vector2 = /*@__PURE__*/ new Vector3();
  19315. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19316. /**
  19317. * A two dimensional surface that extends infinitely in 3D space, represented
  19318. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19319. * by a unit length normal vector and a constant.
  19320. */
  19321. class Plane {
  19322. /**
  19323. * Constructs a new plane.
  19324. *
  19325. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19326. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19327. */
  19328. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19329. /**
  19330. * This flag can be used for type testing.
  19331. *
  19332. * @type {boolean}
  19333. * @readonly
  19334. * @default true
  19335. */
  19336. this.isPlane = true;
  19337. /**
  19338. * A unit length vector defining the normal of the plane.
  19339. *
  19340. * @type {Vector3}
  19341. */
  19342. this.normal = normal;
  19343. /**
  19344. * The signed distance from the origin to the plane.
  19345. *
  19346. * @type {number}
  19347. * @default 0
  19348. */
  19349. this.constant = constant;
  19350. }
  19351. /**
  19352. * Sets the plane components by copying the given values.
  19353. *
  19354. * @param {Vector3} normal - The normal.
  19355. * @param {number} constant - The constant.
  19356. * @return {Plane} A reference to this plane.
  19357. */
  19358. set( normal, constant ) {
  19359. this.normal.copy( normal );
  19360. this.constant = constant;
  19361. return this;
  19362. }
  19363. /**
  19364. * Sets the plane components by defining `x`, `y`, `z` as the
  19365. * plane normal and `w` as the constant.
  19366. *
  19367. * @param {number} x - The value for the normal's x component.
  19368. * @param {number} y - The value for the normal's y component.
  19369. * @param {number} z - The value for the normal's z component.
  19370. * @param {number} w - The constant value.
  19371. * @return {Plane} A reference to this plane.
  19372. */
  19373. setComponents( x, y, z, w ) {
  19374. this.normal.set( x, y, z );
  19375. this.constant = w;
  19376. return this;
  19377. }
  19378. /**
  19379. * Sets the plane from the given normal and coplanar point (that is a point
  19380. * that lies onto the plane).
  19381. *
  19382. * @param {Vector3} normal - The normal.
  19383. * @param {Vector3} point - A coplanar point.
  19384. * @return {Plane} A reference to this plane.
  19385. */
  19386. setFromNormalAndCoplanarPoint( normal, point ) {
  19387. this.normal.copy( normal );
  19388. this.constant = - point.dot( this.normal );
  19389. return this;
  19390. }
  19391. /**
  19392. * Sets the plane from three coplanar points. The winding order is
  19393. * assumed to be counter-clockwise, and determines the direction of
  19394. * the plane normal.
  19395. *
  19396. * @param {Vector3} a - The first coplanar point.
  19397. * @param {Vector3} b - The second coplanar point.
  19398. * @param {Vector3} c - The third coplanar point.
  19399. * @return {Plane} A reference to this plane.
  19400. */
  19401. setFromCoplanarPoints( a, b, c ) {
  19402. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19403. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19404. this.setFromNormalAndCoplanarPoint( normal, a );
  19405. return this;
  19406. }
  19407. /**
  19408. * Copies the values of the given plane to this instance.
  19409. *
  19410. * @param {Plane} plane - The plane to copy.
  19411. * @return {Plane} A reference to this plane.
  19412. */
  19413. copy( plane ) {
  19414. this.normal.copy( plane.normal );
  19415. this.constant = plane.constant;
  19416. return this;
  19417. }
  19418. /**
  19419. * Normalizes the plane normal and adjusts the constant accordingly.
  19420. *
  19421. * @return {Plane} A reference to this plane.
  19422. */
  19423. normalize() {
  19424. // Note: will lead to a divide by zero if the plane is invalid.
  19425. const inverseNormalLength = 1.0 / this.normal.length();
  19426. this.normal.multiplyScalar( inverseNormalLength );
  19427. this.constant *= inverseNormalLength;
  19428. return this;
  19429. }
  19430. /**
  19431. * Negates both the plane normal and the constant.
  19432. *
  19433. * @return {Plane} A reference to this plane.
  19434. */
  19435. negate() {
  19436. this.constant *= -1;
  19437. this.normal.negate();
  19438. return this;
  19439. }
  19440. /**
  19441. * Returns the signed distance from the given point to this plane.
  19442. *
  19443. * @param {Vector3} point - The point to compute the distance for.
  19444. * @return {number} The signed distance.
  19445. */
  19446. distanceToPoint( point ) {
  19447. return this.normal.dot( point ) + this.constant;
  19448. }
  19449. /**
  19450. * Returns the signed distance from the given sphere to this plane.
  19451. *
  19452. * @param {Sphere} sphere - The sphere to compute the distance for.
  19453. * @return {number} The signed distance.
  19454. */
  19455. distanceToSphere( sphere ) {
  19456. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19457. }
  19458. /**
  19459. * Projects a the given point onto the plane.
  19460. *
  19461. * @param {Vector3} point - The point to project.
  19462. * @param {Vector3} target - The target vector that is used to store the method's result.
  19463. * @return {Vector3} The projected point on the plane.
  19464. */
  19465. projectPoint( point, target ) {
  19466. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19467. }
  19468. /**
  19469. * Returns the intersection point of the passed line and the plane. Returns
  19470. * `null` if the line does not intersect. Returns the line's starting point if
  19471. * the line is coplanar with the plane.
  19472. *
  19473. * @param {Line3} line - The line to compute the intersection for.
  19474. * @param {Vector3} target - The target vector that is used to store the method's result.
  19475. * @return {?Vector3} The intersection point.
  19476. */
  19477. intersectLine( line, target ) {
  19478. const direction = line.delta( _vector1 );
  19479. const denominator = this.normal.dot( direction );
  19480. if ( denominator === 0 ) {
  19481. // line is coplanar, return origin
  19482. if ( this.distanceToPoint( line.start ) === 0 ) {
  19483. return target.copy( line.start );
  19484. }
  19485. // Unsure if this is the correct method to handle this case.
  19486. return null;
  19487. }
  19488. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19489. if ( t < 0 || t > 1 ) {
  19490. return null;
  19491. }
  19492. return target.copy( line.start ).addScaledVector( direction, t );
  19493. }
  19494. /**
  19495. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19496. *
  19497. * @param {Line3} line - The line to test.
  19498. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19499. */
  19500. intersectsLine( line ) {
  19501. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19502. const startSign = this.distanceToPoint( line.start );
  19503. const endSign = this.distanceToPoint( line.end );
  19504. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19505. }
  19506. /**
  19507. * Returns `true` if the given bounding box intersects with the plane.
  19508. *
  19509. * @param {Box3} box - The bounding box to test.
  19510. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19511. */
  19512. intersectsBox( box ) {
  19513. return box.intersectsPlane( this );
  19514. }
  19515. /**
  19516. * Returns `true` if the given bounding sphere intersects with the plane.
  19517. *
  19518. * @param {Sphere} sphere - The bounding sphere to test.
  19519. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19520. */
  19521. intersectsSphere( sphere ) {
  19522. return sphere.intersectsPlane( this );
  19523. }
  19524. /**
  19525. * Returns a coplanar vector to the plane, by calculating the
  19526. * projection of the normal at the origin onto the plane.
  19527. *
  19528. * @param {Vector3} target - The target vector that is used to store the method's result.
  19529. * @return {Vector3} The coplanar point.
  19530. */
  19531. coplanarPoint( target ) {
  19532. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19533. }
  19534. /**
  19535. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19536. *
  19537. * The optional normal matrix can be pre-computed like so:
  19538. * ```js
  19539. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19540. * ```
  19541. *
  19542. * @param {Matrix4} matrix - The transformation matrix.
  19543. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19544. * @return {Plane} A reference to this plane.
  19545. */
  19546. applyMatrix4( matrix, optionalNormalMatrix ) {
  19547. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19548. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19549. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19550. this.constant = - referencePoint.dot( normal );
  19551. return this;
  19552. }
  19553. /**
  19554. * Translates the plane by the distance defined by the given offset vector.
  19555. * Note that this only affects the plane constant and will not affect the normal vector.
  19556. *
  19557. * @param {Vector3} offset - The offset vector.
  19558. * @return {Plane} A reference to this plane.
  19559. */
  19560. translate( offset ) {
  19561. this.constant -= offset.dot( this.normal );
  19562. return this;
  19563. }
  19564. /**
  19565. * Returns `true` if this plane is equal with the given one.
  19566. *
  19567. * @param {Plane} plane - The plane to test for equality.
  19568. * @return {boolean} Whether this plane is equal with the given one.
  19569. */
  19570. equals( plane ) {
  19571. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19572. }
  19573. /**
  19574. * Returns a new plane with copied values from this instance.
  19575. *
  19576. * @return {Plane} A clone of this instance.
  19577. */
  19578. clone() {
  19579. return new this.constructor().copy( this );
  19580. }
  19581. }
  19582. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19583. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19584. const _vector$6 = /*@__PURE__*/ new Vector3();
  19585. /**
  19586. * Frustums are used to determine what is inside the camera's field of view.
  19587. * They help speed up the rendering process - objects which lie outside a camera's
  19588. * frustum can safely be excluded from rendering.
  19589. *
  19590. * This class is mainly intended for use internally by a renderer.
  19591. */
  19592. class Frustum {
  19593. /**
  19594. * Constructs a new frustum.
  19595. *
  19596. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19597. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19598. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19599. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19600. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19601. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19602. */
  19603. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19604. /**
  19605. * This array holds the planes that enclose the frustum.
  19606. *
  19607. * @type {Array<Plane>}
  19608. */
  19609. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19610. }
  19611. /**
  19612. * Sets the frustum planes by copying the given planes.
  19613. *
  19614. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19615. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19616. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19617. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19618. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19619. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19620. * @return {Frustum} A reference to this frustum.
  19621. */
  19622. set( p0, p1, p2, p3, p4, p5 ) {
  19623. const planes = this.planes;
  19624. planes[ 0 ].copy( p0 );
  19625. planes[ 1 ].copy( p1 );
  19626. planes[ 2 ].copy( p2 );
  19627. planes[ 3 ].copy( p3 );
  19628. planes[ 4 ].copy( p4 );
  19629. planes[ 5 ].copy( p5 );
  19630. return this;
  19631. }
  19632. /**
  19633. * Copies the values of the given frustum to this instance.
  19634. *
  19635. * @param {Frustum} frustum - The frustum to copy.
  19636. * @return {Frustum} A reference to this frustum.
  19637. */
  19638. copy( frustum ) {
  19639. const planes = this.planes;
  19640. for ( let i = 0; i < 6; i ++ ) {
  19641. planes[ i ].copy( frustum.planes[ i ] );
  19642. }
  19643. return this;
  19644. }
  19645. /**
  19646. * Sets the frustum planes from the given projection matrix.
  19647. *
  19648. * @param {Matrix4} m - The projection matrix.
  19649. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19650. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19651. * @return {Frustum} A reference to this frustum.
  19652. */
  19653. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19654. const planes = this.planes;
  19655. const me = m.elements;
  19656. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19657. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19658. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19659. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19660. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19661. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19662. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19663. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19664. if ( reversedDepth ) {
  19665. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19666. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19667. } else {
  19668. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19669. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19670. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19671. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19672. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19673. } else {
  19674. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19675. }
  19676. }
  19677. return this;
  19678. }
  19679. /**
  19680. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19681. *
  19682. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19683. *
  19684. * @param {Object3D} object - The 3D object to test.
  19685. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19686. */
  19687. intersectsObject( object ) {
  19688. if ( object.boundingSphere !== undefined ) {
  19689. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19690. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19691. } else {
  19692. const geometry = object.geometry;
  19693. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19694. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19695. }
  19696. return this.intersectsSphere( _sphere$3 );
  19697. }
  19698. /**
  19699. * Returns `true` if the given sprite is intersecting this frustum.
  19700. *
  19701. * @param {Sprite} sprite - The sprite to test.
  19702. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19703. */
  19704. intersectsSprite( sprite ) {
  19705. _sphere$3.center.set( 0, 0, 0 );
  19706. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19707. _sphere$3.radius = 0.7071067811865476 + offset;
  19708. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19709. return this.intersectsSphere( _sphere$3 );
  19710. }
  19711. /**
  19712. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19713. *
  19714. * @param {Sphere} sphere - The bounding sphere to test.
  19715. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19716. */
  19717. intersectsSphere( sphere ) {
  19718. const planes = this.planes;
  19719. const center = sphere.center;
  19720. const negRadius = - sphere.radius;
  19721. for ( let i = 0; i < 6; i ++ ) {
  19722. const distance = planes[ i ].distanceToPoint( center );
  19723. if ( distance < negRadius ) {
  19724. return false;
  19725. }
  19726. }
  19727. return true;
  19728. }
  19729. /**
  19730. * Returns `true` if the given bounding box is intersecting this frustum.
  19731. *
  19732. * @param {Box3} box - The bounding box to test.
  19733. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19734. */
  19735. intersectsBox( box ) {
  19736. const planes = this.planes;
  19737. for ( let i = 0; i < 6; i ++ ) {
  19738. const plane = planes[ i ];
  19739. // corner at max distance
  19740. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19741. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19742. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19743. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19744. return false;
  19745. }
  19746. }
  19747. return true;
  19748. }
  19749. /**
  19750. * Returns `true` if the given point lies within the frustum.
  19751. *
  19752. * @param {Vector3} point - The point to test.
  19753. * @return {boolean} Whether the point lies within this frustum or not.
  19754. */
  19755. containsPoint( point ) {
  19756. const planes = this.planes;
  19757. for ( let i = 0; i < 6; i ++ ) {
  19758. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19759. return false;
  19760. }
  19761. }
  19762. return true;
  19763. }
  19764. /**
  19765. * Returns a new frustum with copied values from this instance.
  19766. *
  19767. * @return {Frustum} A clone of this instance.
  19768. */
  19769. clone() {
  19770. return new this.constructor().copy( this );
  19771. }
  19772. }
  19773. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19774. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19775. /**
  19776. * FrustumArray is used to determine if an object is visible in at least one camera
  19777. * from an array of cameras. This is particularly useful for multi-view renderers.
  19778. */
  19779. class FrustumArray {
  19780. /**
  19781. * Constructs a new frustum array.
  19782. *
  19783. */
  19784. constructor() {
  19785. /**
  19786. * The coordinate system to use.
  19787. *
  19788. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19789. * @default WebGLCoordinateSystem
  19790. */
  19791. this.coordinateSystem = WebGLCoordinateSystem;
  19792. }
  19793. /**
  19794. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19795. * from the camera array.
  19796. *
  19797. * @param {Object3D} object - The 3D object to test.
  19798. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19799. * @return {boolean} Whether the 3D object is visible in any camera.
  19800. */
  19801. intersectsObject( object, cameraArray ) {
  19802. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19803. return false;
  19804. }
  19805. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19806. const camera = cameraArray.cameras[ i ];
  19807. _projScreenMatrix$2.multiplyMatrices(
  19808. camera.projectionMatrix,
  19809. camera.matrixWorldInverse
  19810. );
  19811. _frustum$1.setFromProjectionMatrix(
  19812. _projScreenMatrix$2,
  19813. camera.coordinateSystem,
  19814. camera.reversedDepth
  19815. );
  19816. if ( _frustum$1.intersectsObject( object ) ) {
  19817. return true; // Object is visible in at least one camera
  19818. }
  19819. }
  19820. return false; // Not visible in any camera
  19821. }
  19822. /**
  19823. * Returns `true` if the given sprite is intersecting any frustum
  19824. * from the camera array.
  19825. *
  19826. * @param {Sprite} sprite - The sprite to test.
  19827. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19828. * @return {boolean} Whether the sprite is visible in any camera.
  19829. */
  19830. intersectsSprite( sprite, cameraArray ) {
  19831. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19832. return false;
  19833. }
  19834. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19835. const camera = cameraArray.cameras[ i ];
  19836. _projScreenMatrix$2.multiplyMatrices(
  19837. camera.projectionMatrix,
  19838. camera.matrixWorldInverse
  19839. );
  19840. _frustum$1.setFromProjectionMatrix(
  19841. _projScreenMatrix$2,
  19842. camera.coordinateSystem,
  19843. camera.reversedDepth
  19844. );
  19845. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19846. return true; // Sprite is visible in at least one camera
  19847. }
  19848. }
  19849. return false; // Not visible in any camera
  19850. }
  19851. /**
  19852. * Returns `true` if the given bounding sphere is intersecting any frustum
  19853. * from the camera array.
  19854. *
  19855. * @param {Sphere} sphere - The bounding sphere to test.
  19856. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19857. * @return {boolean} Whether the sphere is visible in any camera.
  19858. */
  19859. intersectsSphere( sphere, cameraArray ) {
  19860. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19861. return false;
  19862. }
  19863. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19864. const camera = cameraArray.cameras[ i ];
  19865. _projScreenMatrix$2.multiplyMatrices(
  19866. camera.projectionMatrix,
  19867. camera.matrixWorldInverse
  19868. );
  19869. _frustum$1.setFromProjectionMatrix(
  19870. _projScreenMatrix$2,
  19871. camera.coordinateSystem,
  19872. camera.reversedDepth
  19873. );
  19874. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19875. return true; // Sphere is visible in at least one camera
  19876. }
  19877. }
  19878. return false; // Not visible in any camera
  19879. }
  19880. /**
  19881. * Returns `true` if the given bounding box is intersecting any frustum
  19882. * from the camera array.
  19883. *
  19884. * @param {Box3} box - The bounding box to test.
  19885. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19886. * @return {boolean} Whether the box is visible in any camera.
  19887. */
  19888. intersectsBox( box, cameraArray ) {
  19889. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19890. return false;
  19891. }
  19892. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19893. const camera = cameraArray.cameras[ i ];
  19894. _projScreenMatrix$2.multiplyMatrices(
  19895. camera.projectionMatrix,
  19896. camera.matrixWorldInverse
  19897. );
  19898. _frustum$1.setFromProjectionMatrix(
  19899. _projScreenMatrix$2,
  19900. camera.coordinateSystem,
  19901. camera.reversedDepth
  19902. );
  19903. if ( _frustum$1.intersectsBox( box ) ) {
  19904. return true; // Box is visible in at least one camera
  19905. }
  19906. }
  19907. return false; // Not visible in any camera
  19908. }
  19909. /**
  19910. * Returns `true` if the given point lies within any frustum
  19911. * from the camera array.
  19912. *
  19913. * @param {Vector3} point - The point to test.
  19914. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19915. * @return {boolean} Whether the point is visible in any camera.
  19916. */
  19917. containsPoint( point, cameraArray ) {
  19918. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19919. return false;
  19920. }
  19921. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19922. const camera = cameraArray.cameras[ i ];
  19923. _projScreenMatrix$2.multiplyMatrices(
  19924. camera.projectionMatrix,
  19925. camera.matrixWorldInverse
  19926. );
  19927. _frustum$1.setFromProjectionMatrix(
  19928. _projScreenMatrix$2,
  19929. camera.coordinateSystem,
  19930. camera.reversedDepth
  19931. );
  19932. if ( _frustum$1.containsPoint( point ) ) {
  19933. return true; // Point is visible in at least one camera
  19934. }
  19935. }
  19936. return false; // Not visible in any camera
  19937. }
  19938. /**
  19939. * Returns a new frustum array with copied values from this instance.
  19940. *
  19941. * @return {FrustumArray} A clone of this instance.
  19942. */
  19943. clone() {
  19944. return new FrustumArray();
  19945. }
  19946. }
  19947. function ascIdSort( a, b ) {
  19948. return a - b;
  19949. }
  19950. function sortOpaque( a, b ) {
  19951. return a.z - b.z;
  19952. }
  19953. function sortTransparent( a, b ) {
  19954. return b.z - a.z;
  19955. }
  19956. class MultiDrawRenderList {
  19957. constructor() {
  19958. this.index = 0;
  19959. this.pool = [];
  19960. this.list = [];
  19961. }
  19962. push( start, count, z, index ) {
  19963. const pool = this.pool;
  19964. const list = this.list;
  19965. if ( this.index >= pool.length ) {
  19966. pool.push( {
  19967. start: -1,
  19968. count: -1,
  19969. z: -1,
  19970. index: -1,
  19971. } );
  19972. }
  19973. const item = pool[ this.index ];
  19974. list.push( item );
  19975. this.index ++;
  19976. item.start = start;
  19977. item.count = count;
  19978. item.z = z;
  19979. item.index = index;
  19980. }
  19981. reset() {
  19982. this.list.length = 0;
  19983. this.index = 0;
  19984. }
  19985. }
  19986. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19987. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19988. const _frustum = /*@__PURE__*/ new Frustum();
  19989. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19990. const _box$1 = /*@__PURE__*/ new Box3();
  19991. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19992. const _vector$5 = /*@__PURE__*/ new Vector3();
  19993. const _forward$1 = /*@__PURE__*/ new Vector3();
  19994. const _temp = /*@__PURE__*/ new Vector3();
  19995. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19996. const _mesh = /*@__PURE__*/ new Mesh();
  19997. const _batchIntersects = [];
  19998. // copies data from attribute "src" into "target" starting at "targetOffset"
  19999. function copyAttributeData( src, target, targetOffset = 0 ) {
  20000. const itemSize = target.itemSize;
  20001. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  20002. // use the component getters and setters if the array data cannot
  20003. // be copied directly
  20004. const vertexCount = src.count;
  20005. for ( let i = 0; i < vertexCount; i ++ ) {
  20006. for ( let c = 0; c < itemSize; c ++ ) {
  20007. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  20008. }
  20009. }
  20010. } else {
  20011. // faster copy approach using typed array set function
  20012. target.array.set( src.array, targetOffset * itemSize );
  20013. }
  20014. target.needsUpdate = true;
  20015. }
  20016. // safely copies array contents to a potentially smaller array
  20017. function copyArrayContents( src, target ) {
  20018. if ( src.constructor !== target.constructor ) {
  20019. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20020. const len = Math.min( src.length, target.length );
  20021. for ( let i = 0; i < len; i ++ ) {
  20022. target[ i ] = src[ i ];
  20023. }
  20024. } else {
  20025. // if the arrays use the same data layout we can use a fast block copy
  20026. const len = Math.min( src.length, target.length );
  20027. target.set( new src.constructor( src.buffer, 0, len ) );
  20028. }
  20029. }
  20030. /**
  20031. * A special version of a mesh with multi draw batch rendering support. Use
  20032. * this class if you have to render a large number of objects with the same
  20033. * material but with different geometries or world transformations. The usage of
  20034. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20035. * rendering performance in your application.
  20036. *
  20037. * ```js
  20038. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20039. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20040. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20041. *
  20042. * // initialize and add geometries into the batched mesh
  20043. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20044. * const boxGeometryId = batchedMesh.addGeometry( box );
  20045. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20046. *
  20047. * // create instances of those geometries
  20048. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20049. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20050. *
  20051. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20052. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20053. *
  20054. * // position the geometries
  20055. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20056. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20057. *
  20058. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20059. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20060. *
  20061. * scene.add( batchedMesh );
  20062. * ```
  20063. *
  20064. * @augments Mesh
  20065. */
  20066. class BatchedMesh extends Mesh {
  20067. /**
  20068. * Constructs a new batched mesh.
  20069. *
  20070. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20071. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20072. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20073. * @param {Material|Array<Material>} [material] - The mesh material.
  20074. */
  20075. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20076. super( new BufferGeometry(), material );
  20077. /**
  20078. * This flag can be used for type testing.
  20079. *
  20080. * @type {boolean}
  20081. * @readonly
  20082. * @default true
  20083. */
  20084. this.isBatchedMesh = true;
  20085. /**
  20086. * When set ot `true`, the individual objects of a batch are frustum culled.
  20087. *
  20088. * @type {boolean}
  20089. * @default true
  20090. */
  20091. this.perObjectFrustumCulled = true;
  20092. /**
  20093. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20094. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20095. * rendered front to back.
  20096. *
  20097. * @type {boolean}
  20098. * @default true
  20099. */
  20100. this.sortObjects = true;
  20101. /**
  20102. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20103. *
  20104. * @type {?Box3}
  20105. * @default null
  20106. */
  20107. this.boundingBox = null;
  20108. /**
  20109. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20110. *
  20111. * @type {?Sphere}
  20112. * @default null
  20113. */
  20114. this.boundingSphere = null;
  20115. /**
  20116. * Takes a sort a function that is run before render. The function takes a list of instances to
  20117. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20118. * sort with.
  20119. *
  20120. * @type {?Function}
  20121. * @default null
  20122. */
  20123. this.customSort = null;
  20124. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20125. this._instanceInfo = [];
  20126. this._geometryInfo = [];
  20127. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20128. this._availableInstanceIds = [];
  20129. this._availableGeometryIds = [];
  20130. // used to track where the next point is that geometry should be inserted
  20131. this._nextIndexStart = 0;
  20132. this._nextVertexStart = 0;
  20133. this._geometryCount = 0;
  20134. // flags
  20135. this._visibilityChanged = true;
  20136. this._geometryInitialized = false;
  20137. // cached user options
  20138. this._maxInstanceCount = maxInstanceCount;
  20139. this._maxVertexCount = maxVertexCount;
  20140. this._maxIndexCount = maxIndexCount;
  20141. // buffers for multi draw
  20142. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20143. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20144. this._multiDrawCount = 0;
  20145. this._multiDrawInstances = null;
  20146. // Local matrix per geometry by using data texture
  20147. this._matricesTexture = null;
  20148. this._indirectTexture = null;
  20149. this._colorsTexture = null;
  20150. this._initMatricesTexture();
  20151. this._initIndirectTexture();
  20152. }
  20153. /**
  20154. * The maximum number of individual instances that can be stored in the batch.
  20155. *
  20156. * @type {number}
  20157. * @readonly
  20158. */
  20159. get maxInstanceCount() {
  20160. return this._maxInstanceCount;
  20161. }
  20162. /**
  20163. * The instance count.
  20164. *
  20165. * @type {number}
  20166. * @readonly
  20167. */
  20168. get instanceCount() {
  20169. return this._instanceInfo.length - this._availableInstanceIds.length;
  20170. }
  20171. /**
  20172. * The number of unused vertices.
  20173. *
  20174. * @type {number}
  20175. * @readonly
  20176. */
  20177. get unusedVertexCount() {
  20178. return this._maxVertexCount - this._nextVertexStart;
  20179. }
  20180. /**
  20181. * The number of unused indices.
  20182. *
  20183. * @type {number}
  20184. * @readonly
  20185. */
  20186. get unusedIndexCount() {
  20187. return this._maxIndexCount - this._nextIndexStart;
  20188. }
  20189. _initMatricesTexture() {
  20190. // layout (1 matrix = 4 pixels)
  20191. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20192. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20193. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20194. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20195. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20196. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20197. size = Math.ceil( size / 4 ) * 4;
  20198. size = Math.max( size, 4 );
  20199. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20200. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20201. this._matricesTexture = matricesTexture;
  20202. }
  20203. _initIndirectTexture() {
  20204. let size = Math.sqrt( this._maxInstanceCount );
  20205. size = Math.ceil( size );
  20206. const indirectArray = new Uint32Array( size * size );
  20207. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20208. this._indirectTexture = indirectTexture;
  20209. }
  20210. _initColorsTexture() {
  20211. let size = Math.sqrt( this._maxInstanceCount );
  20212. size = Math.ceil( size );
  20213. // 4 floats per RGBA pixel initialized to white
  20214. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20215. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20216. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20217. this._colorsTexture = colorsTexture;
  20218. }
  20219. _initializeGeometry( reference ) {
  20220. const geometry = this.geometry;
  20221. const maxVertexCount = this._maxVertexCount;
  20222. const maxIndexCount = this._maxIndexCount;
  20223. if ( this._geometryInitialized === false ) {
  20224. for ( const attributeName in reference.attributes ) {
  20225. const srcAttribute = reference.getAttribute( attributeName );
  20226. const { array, itemSize, normalized } = srcAttribute;
  20227. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20228. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20229. geometry.setAttribute( attributeName, dstAttribute );
  20230. }
  20231. if ( reference.getIndex() !== null ) {
  20232. // Reserve last u16 index for primitive restart.
  20233. const indexArray = maxVertexCount > 65535
  20234. ? new Uint32Array( maxIndexCount )
  20235. : new Uint16Array( maxIndexCount );
  20236. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20237. }
  20238. this._geometryInitialized = true;
  20239. }
  20240. }
  20241. // Make sure the geometry is compatible with the existing combined geometry attributes
  20242. _validateGeometry( geometry ) {
  20243. // check to ensure the geometries are using consistent attributes and indices
  20244. const batchGeometry = this.geometry;
  20245. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20246. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20247. }
  20248. for ( const attributeName in batchGeometry.attributes ) {
  20249. if ( ! geometry.hasAttribute( attributeName ) ) {
  20250. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20251. }
  20252. const srcAttribute = geometry.getAttribute( attributeName );
  20253. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20254. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20255. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20256. }
  20257. }
  20258. }
  20259. /**
  20260. * Validates the instance defined by the given ID.
  20261. *
  20262. * @param {number} instanceId - The instance to validate.
  20263. */
  20264. validateInstanceId( instanceId ) {
  20265. const instanceInfo = this._instanceInfo;
  20266. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20267. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20268. }
  20269. }
  20270. /**
  20271. * Validates the geometry defined by the given ID.
  20272. *
  20273. * @param {number} geometryId - The geometry to validate.
  20274. */
  20275. validateGeometryId( geometryId ) {
  20276. const geometryInfoList = this._geometryInfo;
  20277. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20278. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20279. }
  20280. }
  20281. /**
  20282. * Takes a sort a function that is run before render. The function takes a list of instances to
  20283. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20284. *
  20285. * @param {Function} func - The custom sort function.
  20286. * @return {BatchedMesh} A reference to this batched mesh.
  20287. */
  20288. setCustomSort( func ) {
  20289. this.customSort = func;
  20290. return this;
  20291. }
  20292. /**
  20293. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20294. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20295. * otherwise they are `null`.
  20296. */
  20297. computeBoundingBox() {
  20298. if ( this.boundingBox === null ) {
  20299. this.boundingBox = new Box3();
  20300. }
  20301. const boundingBox = this.boundingBox;
  20302. const instanceInfo = this._instanceInfo;
  20303. boundingBox.makeEmpty();
  20304. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20305. if ( instanceInfo[ i ].active === false ) continue;
  20306. const geometryId = instanceInfo[ i ].geometryIndex;
  20307. this.getMatrixAt( i, _matrix$1 );
  20308. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20309. boundingBox.union( _box$1 );
  20310. }
  20311. }
  20312. /**
  20313. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20314. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20315. * otherwise they are `null`.
  20316. */
  20317. computeBoundingSphere() {
  20318. if ( this.boundingSphere === null ) {
  20319. this.boundingSphere = new Sphere();
  20320. }
  20321. const boundingSphere = this.boundingSphere;
  20322. const instanceInfo = this._instanceInfo;
  20323. boundingSphere.makeEmpty();
  20324. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20325. if ( instanceInfo[ i ].active === false ) continue;
  20326. const geometryId = instanceInfo[ i ].geometryIndex;
  20327. this.getMatrixAt( i, _matrix$1 );
  20328. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20329. boundingSphere.union( _sphere$2 );
  20330. }
  20331. }
  20332. /**
  20333. * Adds a new instance to the batch using the geometry of the given ID and returns
  20334. * a new id referring to the new instance to be used by other functions.
  20335. *
  20336. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20337. * @return {number} The instance ID.
  20338. */
  20339. addInstance( geometryId ) {
  20340. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20341. // ensure we're not over geometry
  20342. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20343. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20344. }
  20345. const instanceInfo = {
  20346. visible: true,
  20347. active: true,
  20348. geometryIndex: geometryId,
  20349. };
  20350. let drawId = null;
  20351. // Prioritize using previously freed instance ids
  20352. if ( this._availableInstanceIds.length > 0 ) {
  20353. this._availableInstanceIds.sort( ascIdSort );
  20354. drawId = this._availableInstanceIds.shift();
  20355. this._instanceInfo[ drawId ] = instanceInfo;
  20356. } else {
  20357. drawId = this._instanceInfo.length;
  20358. this._instanceInfo.push( instanceInfo );
  20359. }
  20360. const matricesTexture = this._matricesTexture;
  20361. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20362. matricesTexture.needsUpdate = true;
  20363. const colorsTexture = this._colorsTexture;
  20364. if ( colorsTexture ) {
  20365. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20366. colorsTexture.needsUpdate = true;
  20367. }
  20368. this._visibilityChanged = true;
  20369. return drawId;
  20370. }
  20371. /**
  20372. * Adds the given geometry to the batch and returns the associated
  20373. * geometry id referring to it to be used in other functions.
  20374. *
  20375. * @param {BufferGeometry} geometry - The geometry to add.
  20376. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20377. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20378. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20379. * Defaults to the length of the given geometry vertex buffer.
  20380. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20381. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20382. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20383. * the length of the given geometry index buffer.
  20384. * @return {number} The geometry ID.
  20385. */
  20386. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20387. this._initializeGeometry( geometry );
  20388. this._validateGeometry( geometry );
  20389. const geometryInfo = {
  20390. // geometry information
  20391. vertexStart: -1,
  20392. vertexCount: -1,
  20393. reservedVertexCount: -1,
  20394. indexStart: -1,
  20395. indexCount: -1,
  20396. reservedIndexCount: -1,
  20397. // draw range information
  20398. start: -1,
  20399. count: -1,
  20400. // state
  20401. boundingBox: null,
  20402. boundingSphere: null,
  20403. active: true,
  20404. };
  20405. const geometryInfoList = this._geometryInfo;
  20406. geometryInfo.vertexStart = this._nextVertexStart;
  20407. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20408. const index = geometry.getIndex();
  20409. const hasIndex = index !== null;
  20410. if ( hasIndex ) {
  20411. geometryInfo.indexStart = this._nextIndexStart;
  20412. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20413. }
  20414. if (
  20415. geometryInfo.indexStart !== -1 &&
  20416. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20417. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20418. ) {
  20419. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20420. }
  20421. // update id
  20422. let geometryId;
  20423. if ( this._availableGeometryIds.length > 0 ) {
  20424. this._availableGeometryIds.sort( ascIdSort );
  20425. geometryId = this._availableGeometryIds.shift();
  20426. geometryInfoList[ geometryId ] = geometryInfo;
  20427. } else {
  20428. geometryId = this._geometryCount;
  20429. this._geometryCount ++;
  20430. geometryInfoList.push( geometryInfo );
  20431. }
  20432. // update the geometry
  20433. this.setGeometryAt( geometryId, geometry );
  20434. // increment the next geometry position
  20435. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20436. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20437. return geometryId;
  20438. }
  20439. /**
  20440. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20441. * is not enough space reserved for geometry. Calling this will change all instances that are
  20442. * rendering that geometry.
  20443. *
  20444. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20445. * @param {BufferGeometry} geometry - The new geometry.
  20446. * @return {number} The geometry ID.
  20447. */
  20448. setGeometryAt( geometryId, geometry ) {
  20449. if ( geometryId >= this._geometryCount ) {
  20450. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20451. }
  20452. this._validateGeometry( geometry );
  20453. const batchGeometry = this.geometry;
  20454. const hasIndex = batchGeometry.getIndex() !== null;
  20455. const dstIndex = batchGeometry.getIndex();
  20456. const srcIndex = geometry.getIndex();
  20457. const geometryInfo = this._geometryInfo[ geometryId ];
  20458. if (
  20459. hasIndex &&
  20460. srcIndex.count > geometryInfo.reservedIndexCount ||
  20461. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20462. ) {
  20463. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20464. }
  20465. // copy geometry buffer data over
  20466. const vertexStart = geometryInfo.vertexStart;
  20467. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20468. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20469. for ( const attributeName in batchGeometry.attributes ) {
  20470. // copy attribute data
  20471. const srcAttribute = geometry.getAttribute( attributeName );
  20472. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20473. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20474. // fill the rest in with zeroes
  20475. const itemSize = srcAttribute.itemSize;
  20476. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20477. const index = vertexStart + i;
  20478. for ( let c = 0; c < itemSize; c ++ ) {
  20479. dstAttribute.setComponent( index, c, 0 );
  20480. }
  20481. }
  20482. dstAttribute.needsUpdate = true;
  20483. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20484. }
  20485. // copy index
  20486. if ( hasIndex ) {
  20487. const indexStart = geometryInfo.indexStart;
  20488. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20489. geometryInfo.indexCount = geometry.getIndex().count;
  20490. // copy index data over
  20491. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20492. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20493. }
  20494. // fill the rest in with zeroes
  20495. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20496. dstIndex.setX( indexStart + i, vertexStart );
  20497. }
  20498. dstIndex.needsUpdate = true;
  20499. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20500. }
  20501. // update the draw range
  20502. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20503. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20504. // store the bounding boxes
  20505. geometryInfo.boundingBox = null;
  20506. if ( geometry.boundingBox !== null ) {
  20507. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20508. }
  20509. geometryInfo.boundingSphere = null;
  20510. if ( geometry.boundingSphere !== null ) {
  20511. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20512. }
  20513. this._visibilityChanged = true;
  20514. return geometryId;
  20515. }
  20516. /**
  20517. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20518. * this geometry will also be removed as a side effect.
  20519. *
  20520. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20521. * @return {BatchedMesh} A reference to this batched mesh.
  20522. */
  20523. deleteGeometry( geometryId ) {
  20524. const geometryInfoList = this._geometryInfo;
  20525. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20526. return this;
  20527. }
  20528. // delete any instances associated with this geometry
  20529. const instanceInfo = this._instanceInfo;
  20530. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20531. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20532. this.deleteInstance( i );
  20533. }
  20534. }
  20535. geometryInfoList[ geometryId ].active = false;
  20536. this._availableGeometryIds.push( geometryId );
  20537. this._visibilityChanged = true;
  20538. return this;
  20539. }
  20540. /**
  20541. * Deletes an existing instance from the batch using the given ID.
  20542. *
  20543. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20544. * @return {BatchedMesh} A reference to this batched mesh.
  20545. */
  20546. deleteInstance( instanceId ) {
  20547. this.validateInstanceId( instanceId );
  20548. this._instanceInfo[ instanceId ].active = false;
  20549. this._availableInstanceIds.push( instanceId );
  20550. this._visibilityChanged = true;
  20551. return this;
  20552. }
  20553. /**
  20554. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20555. * previously deleted geometry, freeing up space to add new geometry.
  20556. *
  20557. * @return {BatchedMesh} A reference to this batched mesh.
  20558. */
  20559. optimize() {
  20560. // track the next indices to copy data to
  20561. let nextVertexStart = 0;
  20562. let nextIndexStart = 0;
  20563. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20564. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20565. const geometryInfoList = this._geometryInfo;
  20566. const indices = geometryInfoList
  20567. .map( ( e, i ) => i )
  20568. .sort( ( a, b ) => {
  20569. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20570. } );
  20571. const geometry = this.geometry;
  20572. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20573. // if a geometry range is inactive then don't copy anything
  20574. const index = indices[ i ];
  20575. const geometryInfo = geometryInfoList[ index ];
  20576. if ( geometryInfo.active === false ) {
  20577. continue;
  20578. }
  20579. // if a geometry contains an index buffer then shift it, as well
  20580. if ( geometry.index !== null ) {
  20581. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20582. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20583. const index = geometry.index;
  20584. const array = index.array;
  20585. // shift the index pointers based on how the vertex data will shift
  20586. // adjusting the index must happen first so the original vertex start value is available
  20587. const elementDelta = nextVertexStart - vertexStart;
  20588. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20589. array[ j ] = array[ j ] + elementDelta;
  20590. }
  20591. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20592. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20593. index.needsUpdate = true;
  20594. geometryInfo.indexStart = nextIndexStart;
  20595. }
  20596. nextIndexStart += geometryInfo.reservedIndexCount;
  20597. }
  20598. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20599. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20600. const { vertexStart, reservedVertexCount } = geometryInfo;
  20601. const attributes = geometry.attributes;
  20602. for ( const key in attributes ) {
  20603. const attribute = attributes[ key ];
  20604. const { array, itemSize } = attribute;
  20605. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20606. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20607. attribute.needsUpdate = true;
  20608. }
  20609. geometryInfo.vertexStart = nextVertexStart;
  20610. }
  20611. nextVertexStart += geometryInfo.reservedVertexCount;
  20612. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20613. // step the next geometry points to the shifted position
  20614. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20615. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20616. }
  20617. this._visibilityChanged = true;
  20618. return this;
  20619. }
  20620. /**
  20621. * Returns the bounding box for the given geometry.
  20622. *
  20623. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20624. * @param {Box3} target - The target object that is used to store the method's result.
  20625. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20626. */
  20627. getBoundingBoxAt( geometryId, target ) {
  20628. if ( geometryId >= this._geometryCount ) {
  20629. return null;
  20630. }
  20631. // compute bounding box
  20632. const geometry = this.geometry;
  20633. const geometryInfo = this._geometryInfo[ geometryId ];
  20634. if ( geometryInfo.boundingBox === null ) {
  20635. const box = new Box3();
  20636. const index = geometry.index;
  20637. const position = geometry.attributes.position;
  20638. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20639. let iv = i;
  20640. if ( index ) {
  20641. iv = index.getX( iv );
  20642. }
  20643. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20644. }
  20645. geometryInfo.boundingBox = box;
  20646. }
  20647. target.copy( geometryInfo.boundingBox );
  20648. return target;
  20649. }
  20650. /**
  20651. * Returns the bounding sphere for the given geometry.
  20652. *
  20653. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20654. * @param {Sphere} target - The target object that is used to store the method's result.
  20655. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20656. */
  20657. getBoundingSphereAt( geometryId, target ) {
  20658. if ( geometryId >= this._geometryCount ) {
  20659. return null;
  20660. }
  20661. // compute bounding sphere
  20662. const geometry = this.geometry;
  20663. const geometryInfo = this._geometryInfo[ geometryId ];
  20664. if ( geometryInfo.boundingSphere === null ) {
  20665. const sphere = new Sphere();
  20666. this.getBoundingBoxAt( geometryId, _box$1 );
  20667. _box$1.getCenter( sphere.center );
  20668. const index = geometry.index;
  20669. const position = geometry.attributes.position;
  20670. let maxRadiusSq = 0;
  20671. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20672. let iv = i;
  20673. if ( index ) {
  20674. iv = index.getX( iv );
  20675. }
  20676. _vector$5.fromBufferAttribute( position, iv );
  20677. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20678. }
  20679. sphere.radius = Math.sqrt( maxRadiusSq );
  20680. geometryInfo.boundingSphere = sphere;
  20681. }
  20682. target.copy( geometryInfo.boundingSphere );
  20683. return target;
  20684. }
  20685. /**
  20686. * Sets the given local transformation matrix to the defined instance.
  20687. * Negatively scaled matrices are not supported.
  20688. *
  20689. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20690. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20691. * @return {BatchedMesh} A reference to this batched mesh.
  20692. */
  20693. setMatrixAt( instanceId, matrix ) {
  20694. this.validateInstanceId( instanceId );
  20695. const matricesTexture = this._matricesTexture;
  20696. const matricesArray = this._matricesTexture.image.data;
  20697. matrix.toArray( matricesArray, instanceId * 16 );
  20698. matricesTexture.needsUpdate = true;
  20699. return this;
  20700. }
  20701. /**
  20702. * Returns the local transformation matrix of the defined instance.
  20703. *
  20704. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20705. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20706. * @return {Matrix4} The instance's local transformation matrix.
  20707. */
  20708. getMatrixAt( instanceId, matrix ) {
  20709. this.validateInstanceId( instanceId );
  20710. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20711. }
  20712. /**
  20713. * Sets the given color to the defined instance.
  20714. *
  20715. * @param {number} instanceId - The ID of an instance to set the color of.
  20716. * @param {Color} color - The color to set the instance to.
  20717. * @return {BatchedMesh} A reference to this batched mesh.
  20718. */
  20719. setColorAt( instanceId, color ) {
  20720. this.validateInstanceId( instanceId );
  20721. if ( this._colorsTexture === null ) {
  20722. this._initColorsTexture();
  20723. }
  20724. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20725. this._colorsTexture.needsUpdate = true;
  20726. return this;
  20727. }
  20728. /**
  20729. * Returns the color of the defined instance.
  20730. *
  20731. * @param {number} instanceId - The ID of an instance to get the color of.
  20732. * @param {Color} color - The target object that is used to store the method's result.
  20733. * @return {Color} The instance's color.
  20734. */
  20735. getColorAt( instanceId, color ) {
  20736. this.validateInstanceId( instanceId );
  20737. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20738. }
  20739. /**
  20740. * Sets the visibility of the instance.
  20741. *
  20742. * @param {number} instanceId - The id of the instance to set the visibility of.
  20743. * @param {boolean} visible - Whether the instance is visible or not.
  20744. * @return {BatchedMesh} A reference to this batched mesh.
  20745. */
  20746. setVisibleAt( instanceId, visible ) {
  20747. this.validateInstanceId( instanceId );
  20748. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20749. return this;
  20750. }
  20751. this._instanceInfo[ instanceId ].visible = visible;
  20752. this._visibilityChanged = true;
  20753. return this;
  20754. }
  20755. /**
  20756. * Returns the visibility state of the defined instance.
  20757. *
  20758. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20759. * @return {boolean} Whether the instance is visible or not.
  20760. */
  20761. getVisibleAt( instanceId ) {
  20762. this.validateInstanceId( instanceId );
  20763. return this._instanceInfo[ instanceId ].visible;
  20764. }
  20765. /**
  20766. * Sets the geometry ID of the instance at the given index.
  20767. *
  20768. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20769. * @param {number} geometryId - The geometry ID to be use by the instance.
  20770. * @return {BatchedMesh} A reference to this batched mesh.
  20771. */
  20772. setGeometryIdAt( instanceId, geometryId ) {
  20773. this.validateInstanceId( instanceId );
  20774. this.validateGeometryId( geometryId );
  20775. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20776. return this;
  20777. }
  20778. /**
  20779. * Returns the geometry ID of the defined instance.
  20780. *
  20781. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20782. * @return {number} The instance's geometry ID.
  20783. */
  20784. getGeometryIdAt( instanceId ) {
  20785. this.validateInstanceId( instanceId );
  20786. return this._instanceInfo[ instanceId ].geometryIndex;
  20787. }
  20788. /**
  20789. * Get the range representing the subset of triangles related to the attached geometry,
  20790. * indicating the starting offset and count, or `null` if invalid.
  20791. *
  20792. * @param {number} geometryId - The id of the geometry to get the range of.
  20793. * @param {Object} [target] - The target object that is used to store the method's result.
  20794. * @return {{
  20795. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20796. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20797. * start:number,count:number
  20798. * }} The result object with range data.
  20799. */
  20800. getGeometryRangeAt( geometryId, target = {} ) {
  20801. this.validateGeometryId( geometryId );
  20802. const geometryInfo = this._geometryInfo[ geometryId ];
  20803. target.vertexStart = geometryInfo.vertexStart;
  20804. target.vertexCount = geometryInfo.vertexCount;
  20805. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20806. target.indexStart = geometryInfo.indexStart;
  20807. target.indexCount = geometryInfo.indexCount;
  20808. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20809. target.start = geometryInfo.start;
  20810. target.count = geometryInfo.count;
  20811. return target;
  20812. }
  20813. /**
  20814. * Resizes the necessary buffers to support the provided number of instances.
  20815. * If the provided arguments shrink the number of instances but there are not enough
  20816. * unused Ids at the end of the list then an error is thrown.
  20817. *
  20818. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20819. */
  20820. setInstanceCount( maxInstanceCount ) {
  20821. // shrink the available instances as much as possible
  20822. const availableInstanceIds = this._availableInstanceIds;
  20823. const instanceInfo = this._instanceInfo;
  20824. availableInstanceIds.sort( ascIdSort );
  20825. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20826. instanceInfo.pop();
  20827. availableInstanceIds.pop();
  20828. }
  20829. // throw an error if it can't be shrunk to the desired size
  20830. if ( maxInstanceCount < instanceInfo.length ) {
  20831. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20832. }
  20833. // copy the multi draw counts
  20834. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20835. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20836. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20837. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20838. this._multiDrawCounts = multiDrawCounts;
  20839. this._multiDrawStarts = multiDrawStarts;
  20840. this._maxInstanceCount = maxInstanceCount;
  20841. // update texture data for instance sampling
  20842. const indirectTexture = this._indirectTexture;
  20843. const matricesTexture = this._matricesTexture;
  20844. const colorsTexture = this._colorsTexture;
  20845. indirectTexture.dispose();
  20846. this._initIndirectTexture();
  20847. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20848. matricesTexture.dispose();
  20849. this._initMatricesTexture();
  20850. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20851. if ( colorsTexture ) {
  20852. colorsTexture.dispose();
  20853. this._initColorsTexture();
  20854. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20855. }
  20856. }
  20857. /**
  20858. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20859. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20860. * end of the geometry attributes then an error is thrown.
  20861. *
  20862. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20863. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20864. */
  20865. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20866. // Check if we can shrink to the requested vertex attribute size
  20867. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20868. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20869. if ( requiredVertexLength > maxVertexCount ) {
  20870. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20871. }
  20872. // Check if we can shrink to the requested index attribute size
  20873. if ( this.geometry.index ) {
  20874. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20875. if ( requiredIndexLength > maxIndexCount ) {
  20876. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20877. }
  20878. }
  20879. //
  20880. // dispose of the previous geometry
  20881. const oldGeometry = this.geometry;
  20882. oldGeometry.dispose();
  20883. // recreate the geometry needed based on the previous variant
  20884. this._maxVertexCount = maxVertexCount;
  20885. this._maxIndexCount = maxIndexCount;
  20886. if ( this._geometryInitialized ) {
  20887. this._geometryInitialized = false;
  20888. this.geometry = new BufferGeometry();
  20889. this._initializeGeometry( oldGeometry );
  20890. }
  20891. // copy data from the previous geometry
  20892. const geometry = this.geometry;
  20893. if ( oldGeometry.index ) {
  20894. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20895. }
  20896. for ( const key in oldGeometry.attributes ) {
  20897. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20898. }
  20899. }
  20900. raycast( raycaster, intersects ) {
  20901. const instanceInfo = this._instanceInfo;
  20902. const geometryInfoList = this._geometryInfo;
  20903. const matrixWorld = this.matrixWorld;
  20904. const batchGeometry = this.geometry;
  20905. // iterate over each geometry
  20906. _mesh.material = this.material;
  20907. _mesh.geometry.index = batchGeometry.index;
  20908. _mesh.geometry.attributes = batchGeometry.attributes;
  20909. if ( _mesh.geometry.boundingBox === null ) {
  20910. _mesh.geometry.boundingBox = new Box3();
  20911. }
  20912. if ( _mesh.geometry.boundingSphere === null ) {
  20913. _mesh.geometry.boundingSphere = new Sphere();
  20914. }
  20915. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20916. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20917. continue;
  20918. }
  20919. const geometryId = instanceInfo[ i ].geometryIndex;
  20920. const geometryInfo = geometryInfoList[ geometryId ];
  20921. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20922. // get the intersects
  20923. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20924. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20925. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20926. _mesh.raycast( raycaster, _batchIntersects );
  20927. // add batch id to the intersects
  20928. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20929. const intersect = _batchIntersects[ j ];
  20930. intersect.object = this;
  20931. intersect.batchId = i;
  20932. intersects.push( intersect );
  20933. }
  20934. _batchIntersects.length = 0;
  20935. }
  20936. _mesh.material = null;
  20937. _mesh.geometry.index = null;
  20938. _mesh.geometry.attributes = {};
  20939. _mesh.geometry.setDrawRange( 0, Infinity );
  20940. }
  20941. copy( source ) {
  20942. super.copy( source );
  20943. this.geometry = source.geometry.clone();
  20944. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20945. this.sortObjects = source.sortObjects;
  20946. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20947. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20948. this._geometryInfo = source._geometryInfo.map( info => ( {
  20949. ...info,
  20950. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20951. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20952. } ) );
  20953. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20954. this._availableInstanceIds = source._availableInstanceIds.slice();
  20955. this._availableGeometryIds = source._availableGeometryIds.slice();
  20956. this._nextIndexStart = source._nextIndexStart;
  20957. this._nextVertexStart = source._nextVertexStart;
  20958. this._geometryCount = source._geometryCount;
  20959. this._maxInstanceCount = source._maxInstanceCount;
  20960. this._maxVertexCount = source._maxVertexCount;
  20961. this._maxIndexCount = source._maxIndexCount;
  20962. this._geometryInitialized = source._geometryInitialized;
  20963. this._multiDrawCounts = source._multiDrawCounts.slice();
  20964. this._multiDrawStarts = source._multiDrawStarts.slice();
  20965. this._indirectTexture = source._indirectTexture.clone();
  20966. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20967. this._matricesTexture = source._matricesTexture.clone();
  20968. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20969. if ( this._colorsTexture !== null ) {
  20970. this._colorsTexture = source._colorsTexture.clone();
  20971. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20972. }
  20973. return this;
  20974. }
  20975. /**
  20976. * Frees the GPU-related resources allocated by this instance. Call this
  20977. * method whenever this instance is no longer used in your app.
  20978. */
  20979. dispose() {
  20980. // Assuming the geometry is not shared with other meshes
  20981. this.geometry.dispose();
  20982. this._matricesTexture.dispose();
  20983. this._matricesTexture = null;
  20984. this._indirectTexture.dispose();
  20985. this._indirectTexture = null;
  20986. if ( this._colorsTexture !== null ) {
  20987. this._colorsTexture.dispose();
  20988. this._colorsTexture = null;
  20989. }
  20990. }
  20991. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20992. // if visibility has not changed and frustum culling and object sorting is not required
  20993. // then skip iterating over all items
  20994. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20995. return;
  20996. }
  20997. // the indexed version of the multi draw function requires specifying the start
  20998. // offset in bytes.
  20999. const index = geometry.getIndex();
  21000. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  21001. const instanceInfo = this._instanceInfo;
  21002. const multiDrawStarts = this._multiDrawStarts;
  21003. const multiDrawCounts = this._multiDrawCounts;
  21004. const geometryInfoList = this._geometryInfo;
  21005. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  21006. const indirectTexture = this._indirectTexture;
  21007. const indirectArray = indirectTexture.image.data;
  21008. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21009. // prepare the frustum in the local frame
  21010. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21011. _matrix$1
  21012. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21013. .multiply( this.matrixWorld );
  21014. _frustum.setFromProjectionMatrix(
  21015. _matrix$1,
  21016. camera.coordinateSystem,
  21017. camera.reversedDepth
  21018. );
  21019. }
  21020. let multiDrawCount = 0;
  21021. if ( this.sortObjects ) {
  21022. // get the camera position in the local frame
  21023. _matrix$1.copy( this.matrixWorld ).invert();
  21024. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21025. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21026. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21027. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21028. const geometryId = instanceInfo[ i ].geometryIndex;
  21029. // get the bounds in world space
  21030. this.getMatrixAt( i, _matrix$1 );
  21031. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21032. // determine whether the batched geometry is within the frustum
  21033. let culled = false;
  21034. if ( perObjectFrustumCulled ) {
  21035. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21036. }
  21037. if ( ! culled ) {
  21038. // get the distance from camera used for sorting
  21039. const geometryInfo = geometryInfoList[ geometryId ];
  21040. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21041. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21042. }
  21043. }
  21044. }
  21045. // Sort the draw ranges and prep for rendering
  21046. const list = _renderList.list;
  21047. const customSort = this.customSort;
  21048. if ( customSort === null ) {
  21049. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21050. } else {
  21051. customSort.call( this, list, camera );
  21052. }
  21053. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21054. const item = list[ i ];
  21055. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21056. multiDrawCounts[ multiDrawCount ] = item.count;
  21057. indirectArray[ multiDrawCount ] = item.index;
  21058. multiDrawCount ++;
  21059. }
  21060. _renderList.reset();
  21061. } else {
  21062. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21063. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21064. const geometryId = instanceInfo[ i ].geometryIndex;
  21065. // determine whether the batched geometry is within the frustum
  21066. let culled = false;
  21067. if ( perObjectFrustumCulled ) {
  21068. // get the bounds in world space
  21069. this.getMatrixAt( i, _matrix$1 );
  21070. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21071. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21072. }
  21073. if ( ! culled ) {
  21074. const geometryInfo = geometryInfoList[ geometryId ];
  21075. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21076. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21077. indirectArray[ multiDrawCount ] = i;
  21078. multiDrawCount ++;
  21079. }
  21080. }
  21081. }
  21082. }
  21083. indirectTexture.needsUpdate = true;
  21084. this._multiDrawCount = multiDrawCount;
  21085. this._visibilityChanged = false;
  21086. }
  21087. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21088. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21089. }
  21090. }
  21091. /**
  21092. * A material for rendering line primitives.
  21093. *
  21094. * Materials define the appearance of renderable 3D objects.
  21095. *
  21096. * ```js
  21097. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21098. * ```
  21099. *
  21100. * @augments Material
  21101. */
  21102. class LineBasicMaterial extends Material {
  21103. /**
  21104. * Constructs a new line basic material.
  21105. *
  21106. * @param {Object} [parameters] - An object with one or more properties
  21107. * defining the material's appearance. Any property of the material
  21108. * (including any property from inherited materials) can be passed
  21109. * in here. Color values can be passed any type of value accepted
  21110. * by {@link Color#set}.
  21111. */
  21112. constructor( parameters ) {
  21113. super();
  21114. /**
  21115. * This flag can be used for type testing.
  21116. *
  21117. * @type {boolean}
  21118. * @readonly
  21119. * @default true
  21120. */
  21121. this.isLineBasicMaterial = true;
  21122. this.type = 'LineBasicMaterial';
  21123. /**
  21124. * Color of the material.
  21125. *
  21126. * @type {Color}
  21127. * @default (1,1,1)
  21128. */
  21129. this.color = new Color( 0xffffff );
  21130. /**
  21131. * Sets the color of the lines using data from a texture. The texture map
  21132. * color is modulated by the diffuse `color`.
  21133. *
  21134. * @type {?Texture}
  21135. * @default null
  21136. */
  21137. this.map = null;
  21138. /**
  21139. * Controls line thickness or lines.
  21140. *
  21141. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21142. * ignore this setting and always render line primitives with a
  21143. * width of one pixel.
  21144. *
  21145. * @type {number}
  21146. * @default 1
  21147. */
  21148. this.linewidth = 1;
  21149. /**
  21150. * Defines appearance of line ends.
  21151. *
  21152. * Can only be used with {@link SVGRenderer}.
  21153. *
  21154. * @type {('butt'|'round'|'square')}
  21155. * @default 'round'
  21156. */
  21157. this.linecap = 'round';
  21158. /**
  21159. * Defines appearance of line joints.
  21160. *
  21161. * Can only be used with {@link SVGRenderer}.
  21162. *
  21163. * @type {('round'|'bevel'|'miter')}
  21164. * @default 'round'
  21165. */
  21166. this.linejoin = 'round';
  21167. /**
  21168. * Whether the material is affected by fog or not.
  21169. *
  21170. * @type {boolean}
  21171. * @default true
  21172. */
  21173. this.fog = true;
  21174. this.setValues( parameters );
  21175. }
  21176. copy( source ) {
  21177. super.copy( source );
  21178. this.color.copy( source.color );
  21179. this.map = source.map;
  21180. this.linewidth = source.linewidth;
  21181. this.linecap = source.linecap;
  21182. this.linejoin = source.linejoin;
  21183. this.fog = source.fog;
  21184. return this;
  21185. }
  21186. }
  21187. const _vStart = /*@__PURE__*/ new Vector3();
  21188. const _vEnd = /*@__PURE__*/ new Vector3();
  21189. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21190. const _ray$1 = /*@__PURE__*/ new Ray();
  21191. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21192. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21193. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21194. /**
  21195. * A continuous line. The line are rendered by connecting consecutive
  21196. * vertices with straight lines.
  21197. *
  21198. * ```js
  21199. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21200. *
  21201. * const points = [];
  21202. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21203. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21204. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21205. *
  21206. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21207. *
  21208. * const line = new THREE.Line( geometry, material );
  21209. * scene.add( line );
  21210. * ```
  21211. *
  21212. * @augments Object3D
  21213. */
  21214. class Line extends Object3D {
  21215. /**
  21216. * Constructs a new line.
  21217. *
  21218. * @param {BufferGeometry} [geometry] - The line geometry.
  21219. * @param {Material|Array<Material>} [material] - The line material.
  21220. */
  21221. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21222. super();
  21223. /**
  21224. * This flag can be used for type testing.
  21225. *
  21226. * @type {boolean}
  21227. * @readonly
  21228. * @default true
  21229. */
  21230. this.isLine = true;
  21231. this.type = 'Line';
  21232. /**
  21233. * The line geometry.
  21234. *
  21235. * @type {BufferGeometry}
  21236. */
  21237. this.geometry = geometry;
  21238. /**
  21239. * The line material.
  21240. *
  21241. * @type {Material|Array<Material>}
  21242. * @default LineBasicMaterial
  21243. */
  21244. this.material = material;
  21245. /**
  21246. * A dictionary representing the morph targets in the geometry. The key is the
  21247. * morph targets name, the value its attribute index. This member is `undefined`
  21248. * by default and only set when morph targets are detected in the geometry.
  21249. *
  21250. * @type {Object<string,number>|undefined}
  21251. * @default undefined
  21252. */
  21253. this.morphTargetDictionary = undefined;
  21254. /**
  21255. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21256. * is applied. This member is `undefined` by default and only set when morph targets are
  21257. * detected in the geometry.
  21258. *
  21259. * @type {Array<number>|undefined}
  21260. * @default undefined
  21261. */
  21262. this.morphTargetInfluences = undefined;
  21263. this.updateMorphTargets();
  21264. }
  21265. copy( source, recursive ) {
  21266. super.copy( source, recursive );
  21267. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21268. this.geometry = source.geometry;
  21269. return this;
  21270. }
  21271. /**
  21272. * Computes an array of distance values which are necessary for rendering dashed lines.
  21273. * For each vertex in the geometry, the method calculates the cumulative length from the
  21274. * current point to the very beginning of the line.
  21275. *
  21276. * @return {Line} A reference to this line.
  21277. */
  21278. computeLineDistances() {
  21279. const geometry = this.geometry;
  21280. // we assume non-indexed geometry
  21281. if ( geometry.index === null ) {
  21282. const positionAttribute = geometry.attributes.position;
  21283. const lineDistances = [ 0 ];
  21284. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21285. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21286. _vEnd.fromBufferAttribute( positionAttribute, i );
  21287. lineDistances[ i ] = lineDistances[ i - 1 ];
  21288. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21289. }
  21290. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21291. } else {
  21292. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21293. }
  21294. return this;
  21295. }
  21296. /**
  21297. * Computes intersection points between a casted ray and this line.
  21298. *
  21299. * @param {Raycaster} raycaster - The raycaster.
  21300. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21301. */
  21302. raycast( raycaster, intersects ) {
  21303. const geometry = this.geometry;
  21304. const matrixWorld = this.matrixWorld;
  21305. const threshold = raycaster.params.Line.threshold;
  21306. const drawRange = geometry.drawRange;
  21307. // Checking boundingSphere distance to ray
  21308. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21309. _sphere$1.copy( geometry.boundingSphere );
  21310. _sphere$1.applyMatrix4( matrixWorld );
  21311. _sphere$1.radius += threshold;
  21312. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21313. //
  21314. _inverseMatrix$1.copy( matrixWorld ).invert();
  21315. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21316. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21317. const localThresholdSq = localThreshold * localThreshold;
  21318. const step = this.isLineSegments ? 2 : 1;
  21319. const index = geometry.index;
  21320. const attributes = geometry.attributes;
  21321. const positionAttribute = attributes.position;
  21322. if ( index !== null ) {
  21323. const start = Math.max( 0, drawRange.start );
  21324. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21325. for ( let i = start, l = end - 1; i < l; i += step ) {
  21326. const a = index.getX( i );
  21327. const b = index.getX( i + 1 );
  21328. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21329. if ( intersect ) {
  21330. intersects.push( intersect );
  21331. }
  21332. }
  21333. if ( this.isLineLoop ) {
  21334. const a = index.getX( end - 1 );
  21335. const b = index.getX( start );
  21336. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21337. if ( intersect ) {
  21338. intersects.push( intersect );
  21339. }
  21340. }
  21341. } else {
  21342. const start = Math.max( 0, drawRange.start );
  21343. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21344. for ( let i = start, l = end - 1; i < l; i += step ) {
  21345. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21346. if ( intersect ) {
  21347. intersects.push( intersect );
  21348. }
  21349. }
  21350. if ( this.isLineLoop ) {
  21351. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21352. if ( intersect ) {
  21353. intersects.push( intersect );
  21354. }
  21355. }
  21356. }
  21357. }
  21358. /**
  21359. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21360. * to make sure existing morph targets can influence this 3D object.
  21361. */
  21362. updateMorphTargets() {
  21363. const geometry = this.geometry;
  21364. const morphAttributes = geometry.morphAttributes;
  21365. const keys = Object.keys( morphAttributes );
  21366. if ( keys.length > 0 ) {
  21367. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21368. if ( morphAttribute !== undefined ) {
  21369. this.morphTargetInfluences = [];
  21370. this.morphTargetDictionary = {};
  21371. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21372. const name = morphAttribute[ m ].name || String( m );
  21373. this.morphTargetInfluences.push( 0 );
  21374. this.morphTargetDictionary[ name ] = m;
  21375. }
  21376. }
  21377. }
  21378. }
  21379. }
  21380. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21381. const positionAttribute = object.geometry.attributes.position;
  21382. _vStart.fromBufferAttribute( positionAttribute, a );
  21383. _vEnd.fromBufferAttribute( positionAttribute, b );
  21384. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21385. if ( distSq > thresholdSq ) return;
  21386. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21387. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21388. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21389. return {
  21390. distance: distance,
  21391. // What do we want? intersection point on the ray or on the segment??
  21392. // point: raycaster.ray.at( distance ),
  21393. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21394. index: i,
  21395. face: null,
  21396. faceIndex: null,
  21397. barycoord: null,
  21398. object: object
  21399. };
  21400. }
  21401. const _start = /*@__PURE__*/ new Vector3();
  21402. const _end = /*@__PURE__*/ new Vector3();
  21403. /**
  21404. * A series of lines drawn between pairs of vertices.
  21405. *
  21406. * @augments Line
  21407. */
  21408. class LineSegments extends Line {
  21409. /**
  21410. * Constructs a new line segments.
  21411. *
  21412. * @param {BufferGeometry} [geometry] - The line geometry.
  21413. * @param {Material|Array<Material>} [material] - The line material.
  21414. */
  21415. constructor( geometry, material ) {
  21416. super( geometry, material );
  21417. /**
  21418. * This flag can be used for type testing.
  21419. *
  21420. * @type {boolean}
  21421. * @readonly
  21422. * @default true
  21423. */
  21424. this.isLineSegments = true;
  21425. this.type = 'LineSegments';
  21426. }
  21427. computeLineDistances() {
  21428. const geometry = this.geometry;
  21429. // we assume non-indexed geometry
  21430. if ( geometry.index === null ) {
  21431. const positionAttribute = geometry.attributes.position;
  21432. const lineDistances = [];
  21433. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21434. _start.fromBufferAttribute( positionAttribute, i );
  21435. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21436. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21437. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21438. }
  21439. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21440. } else {
  21441. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21442. }
  21443. return this;
  21444. }
  21445. }
  21446. /**
  21447. * A continuous line. This is nearly the same as {@link Line} the only difference
  21448. * is that the last vertex is connected with the first vertex in order to close
  21449. * the line to form a loop.
  21450. *
  21451. * @augments Line
  21452. */
  21453. class LineLoop extends Line {
  21454. /**
  21455. * Constructs a new line loop.
  21456. *
  21457. * @param {BufferGeometry} [geometry] - The line geometry.
  21458. * @param {Material|Array<Material>} [material] - The line material.
  21459. */
  21460. constructor( geometry, material ) {
  21461. super( geometry, material );
  21462. /**
  21463. * This flag can be used for type testing.
  21464. *
  21465. * @type {boolean}
  21466. * @readonly
  21467. * @default true
  21468. */
  21469. this.isLineLoop = true;
  21470. this.type = 'LineLoop';
  21471. }
  21472. }
  21473. /**
  21474. * A material for rendering point primitives.
  21475. *
  21476. * Materials define the appearance of renderable 3D objects.
  21477. *
  21478. * ```js
  21479. * const vertices = [];
  21480. *
  21481. * for ( let i = 0; i < 10000; i ++ ) {
  21482. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21483. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21484. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21485. *
  21486. * vertices.push( x, y, z );
  21487. * }
  21488. *
  21489. * const geometry = new THREE.BufferGeometry();
  21490. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21491. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21492. * const points = new THREE.Points( geometry, material );
  21493. * scene.add( points );
  21494. * ```
  21495. *
  21496. * @augments Material
  21497. */
  21498. class PointsMaterial extends Material {
  21499. /**
  21500. * Constructs a new points material.
  21501. *
  21502. * @param {Object} [parameters] - An object with one or more properties
  21503. * defining the material's appearance. Any property of the material
  21504. * (including any property from inherited materials) can be passed
  21505. * in here. Color values can be passed any type of value accepted
  21506. * by {@link Color#set}.
  21507. */
  21508. constructor( parameters ) {
  21509. super();
  21510. /**
  21511. * This flag can be used for type testing.
  21512. *
  21513. * @type {boolean}
  21514. * @readonly
  21515. * @default true
  21516. */
  21517. this.isPointsMaterial = true;
  21518. this.type = 'PointsMaterial';
  21519. /**
  21520. * Color of the material.
  21521. *
  21522. * @type {Color}
  21523. * @default (1,1,1)
  21524. */
  21525. this.color = new Color( 0xffffff );
  21526. /**
  21527. * The color map. May optionally include an alpha channel, typically combined
  21528. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21529. * color is modulated by the diffuse `color`.
  21530. *
  21531. * @type {?Texture}
  21532. * @default null
  21533. */
  21534. this.map = null;
  21535. /**
  21536. * The alpha map is a grayscale texture that controls the opacity across the
  21537. * surface (black: fully transparent; white: fully opaque).
  21538. *
  21539. * Only the color of the texture is used, ignoring the alpha channel if one
  21540. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21541. * when sampling this texture due to the extra bit of precision provided for
  21542. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21543. * luminance/alpha textures will also still work as expected.
  21544. *
  21545. * @type {?Texture}
  21546. * @default null
  21547. */
  21548. this.alphaMap = null;
  21549. /**
  21550. * Defines the size of the points in pixels.
  21551. *
  21552. * Might be capped if the value exceeds hardware dependent parameters like [gl.ALIASED_POINT_SIZE_RANGE](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getParamete).
  21553. *
  21554. * @type {number}
  21555. * @default 1
  21556. */
  21557. this.size = 1;
  21558. /**
  21559. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21560. *
  21561. * @type {boolean}
  21562. * @default true
  21563. */
  21564. this.sizeAttenuation = true;
  21565. /**
  21566. * Whether the material is affected by fog or not.
  21567. *
  21568. * @type {boolean}
  21569. * @default true
  21570. */
  21571. this.fog = true;
  21572. this.setValues( parameters );
  21573. }
  21574. copy( source ) {
  21575. super.copy( source );
  21576. this.color.copy( source.color );
  21577. this.map = source.map;
  21578. this.alphaMap = source.alphaMap;
  21579. this.size = source.size;
  21580. this.sizeAttenuation = source.sizeAttenuation;
  21581. this.fog = source.fog;
  21582. return this;
  21583. }
  21584. }
  21585. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21586. const _ray = /*@__PURE__*/ new Ray();
  21587. const _sphere = /*@__PURE__*/ new Sphere();
  21588. const _position$2 = /*@__PURE__*/ new Vector3();
  21589. /**
  21590. * A class for displaying points or point clouds.
  21591. *
  21592. * @augments Object3D
  21593. */
  21594. class Points extends Object3D {
  21595. /**
  21596. * Constructs a new point cloud.
  21597. *
  21598. * @param {BufferGeometry} [geometry] - The points geometry.
  21599. * @param {Material|Array<Material>} [material] - The points material.
  21600. */
  21601. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21602. super();
  21603. /**
  21604. * This flag can be used for type testing.
  21605. *
  21606. * @type {boolean}
  21607. * @readonly
  21608. * @default true
  21609. */
  21610. this.isPoints = true;
  21611. this.type = 'Points';
  21612. /**
  21613. * The points geometry.
  21614. *
  21615. * @type {BufferGeometry}
  21616. */
  21617. this.geometry = geometry;
  21618. /**
  21619. * The line material.
  21620. *
  21621. * @type {Material|Array<Material>}
  21622. * @default PointsMaterial
  21623. */
  21624. this.material = material;
  21625. /**
  21626. * A dictionary representing the morph targets in the geometry. The key is the
  21627. * morph targets name, the value its attribute index. This member is `undefined`
  21628. * by default and only set when morph targets are detected in the geometry.
  21629. *
  21630. * @type {Object<string,number>|undefined}
  21631. * @default undefined
  21632. */
  21633. this.morphTargetDictionary = undefined;
  21634. /**
  21635. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21636. * is applied. This member is `undefined` by default and only set when morph targets are
  21637. * detected in the geometry.
  21638. *
  21639. * @type {Array<number>|undefined}
  21640. * @default undefined
  21641. */
  21642. this.morphTargetInfluences = undefined;
  21643. this.updateMorphTargets();
  21644. }
  21645. copy( source, recursive ) {
  21646. super.copy( source, recursive );
  21647. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21648. this.geometry = source.geometry;
  21649. return this;
  21650. }
  21651. /**
  21652. * Computes intersection points between a casted ray and this point cloud.
  21653. *
  21654. * @param {Raycaster} raycaster - The raycaster.
  21655. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21656. */
  21657. raycast( raycaster, intersects ) {
  21658. const geometry = this.geometry;
  21659. const matrixWorld = this.matrixWorld;
  21660. const threshold = raycaster.params.Points.threshold;
  21661. const drawRange = geometry.drawRange;
  21662. // Checking boundingSphere distance to ray
  21663. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21664. _sphere.copy( geometry.boundingSphere );
  21665. _sphere.applyMatrix4( matrixWorld );
  21666. _sphere.radius += threshold;
  21667. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21668. //
  21669. _inverseMatrix.copy( matrixWorld ).invert();
  21670. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21671. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21672. const localThresholdSq = localThreshold * localThreshold;
  21673. const index = geometry.index;
  21674. const attributes = geometry.attributes;
  21675. const positionAttribute = attributes.position;
  21676. if ( index !== null ) {
  21677. const start = Math.max( 0, drawRange.start );
  21678. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21679. for ( let i = start, il = end; i < il; i ++ ) {
  21680. const a = index.getX( i );
  21681. _position$2.fromBufferAttribute( positionAttribute, a );
  21682. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21683. }
  21684. } else {
  21685. const start = Math.max( 0, drawRange.start );
  21686. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21687. for ( let i = start, l = end; i < l; i ++ ) {
  21688. _position$2.fromBufferAttribute( positionAttribute, i );
  21689. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21690. }
  21691. }
  21692. }
  21693. /**
  21694. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21695. * to make sure existing morph targets can influence this 3D object.
  21696. */
  21697. updateMorphTargets() {
  21698. const geometry = this.geometry;
  21699. const morphAttributes = geometry.morphAttributes;
  21700. const keys = Object.keys( morphAttributes );
  21701. if ( keys.length > 0 ) {
  21702. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21703. if ( morphAttribute !== undefined ) {
  21704. this.morphTargetInfluences = [];
  21705. this.morphTargetDictionary = {};
  21706. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21707. const name = morphAttribute[ m ].name || String( m );
  21708. this.morphTargetInfluences.push( 0 );
  21709. this.morphTargetDictionary[ name ] = m;
  21710. }
  21711. }
  21712. }
  21713. }
  21714. }
  21715. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21716. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21717. if ( rayPointDistanceSq < localThresholdSq ) {
  21718. const intersectPoint = new Vector3();
  21719. _ray.closestPointToPoint( point, intersectPoint );
  21720. intersectPoint.applyMatrix4( matrixWorld );
  21721. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21722. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21723. intersects.push( {
  21724. distance: distance,
  21725. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21726. point: intersectPoint,
  21727. index: index,
  21728. face: null,
  21729. faceIndex: null,
  21730. barycoord: null,
  21731. object: object
  21732. } );
  21733. }
  21734. }
  21735. /**
  21736. * A texture for use with a video.
  21737. *
  21738. * ```js
  21739. * // assuming you have created a HTML video element with id="video"
  21740. * const video = document.getElementById( 'video' );
  21741. * const texture = new THREE.VideoTexture( video );
  21742. * ```
  21743. *
  21744. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21745. * set to THREE.SRGBColorSpace.
  21746. *
  21747. * Note: After the initial use of a texture, its dimensions, format, and type
  21748. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21749. *
  21750. * @augments Texture
  21751. */
  21752. class VideoTexture extends Texture {
  21753. /**
  21754. * Constructs a new video texture.
  21755. *
  21756. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21757. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21758. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21759. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21760. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21761. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21762. * @param {number} [format=RGBAFormat] - The texture format.
  21763. * @param {number} [type=UnsignedByteType] - The texture type.
  21764. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21765. */
  21766. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21767. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21768. /**
  21769. * This flag can be used for type testing.
  21770. *
  21771. * @type {boolean}
  21772. * @readonly
  21773. * @default true
  21774. */
  21775. this.isVideoTexture = true;
  21776. /**
  21777. * Whether to generate mipmaps (if possible) for a texture.
  21778. *
  21779. * Overwritten and set to `false` by default.
  21780. *
  21781. * @type {boolean}
  21782. * @default false
  21783. */
  21784. this.generateMipmaps = false;
  21785. /**
  21786. * The video frame request callback identifier, which is a positive integer.
  21787. *
  21788. * Value of 0 represents no scheduled rVFC.
  21789. *
  21790. * @private
  21791. * @type {number}
  21792. */
  21793. this._requestVideoFrameCallbackId = 0;
  21794. const scope = this;
  21795. function updateVideo() {
  21796. scope.needsUpdate = true;
  21797. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21798. }
  21799. if ( 'requestVideoFrameCallback' in video ) {
  21800. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21801. }
  21802. }
  21803. clone() {
  21804. return new this.constructor( this.image ).copy( this );
  21805. }
  21806. /**
  21807. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21808. * to `true` every time a new frame is available.
  21809. *
  21810. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21811. */
  21812. update() {
  21813. const video = this.image;
  21814. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21815. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21816. this.needsUpdate = true;
  21817. }
  21818. }
  21819. dispose() {
  21820. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21821. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21822. this._requestVideoFrameCallbackId = 0;
  21823. }
  21824. super.dispose();
  21825. }
  21826. }
  21827. /**
  21828. * This class can be used as an alternative way to define video data. Instead of using
  21829. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21830. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21831. * video frames are decoded with the WebCodecs API.
  21832. *
  21833. * ```js
  21834. * const texture = new THREE.VideoFrameTexture();
  21835. * texture.setFrame( frame );
  21836. * ```
  21837. *
  21838. * @augments VideoTexture
  21839. */
  21840. class VideoFrameTexture extends VideoTexture {
  21841. /**
  21842. * Constructs a new video frame texture.
  21843. *
  21844. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21845. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21846. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21847. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21848. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21849. * @param {number} [format=RGBAFormat] - The texture format.
  21850. * @param {number} [type=UnsignedByteType] - The texture type.
  21851. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21852. */
  21853. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21854. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21855. /**
  21856. * This flag can be used for type testing.
  21857. *
  21858. * @type {boolean}
  21859. * @readonly
  21860. * @default true
  21861. */
  21862. this.isVideoFrameTexture = true;
  21863. }
  21864. /**
  21865. * This method overwritten with an empty implementation since
  21866. * this type of texture is updated via `setFrame()`.
  21867. */
  21868. update() {}
  21869. clone() {
  21870. return new this.constructor().copy( this ); // restoring Texture.clone()
  21871. }
  21872. /**
  21873. * Sets the current frame of the video. This will automatically update the texture
  21874. * so the data can be used for rendering.
  21875. *
  21876. * @param {VideoFrame} frame - The video frame.
  21877. */
  21878. setFrame( frame ) {
  21879. this.image = frame;
  21880. this.needsUpdate = true;
  21881. }
  21882. }
  21883. /**
  21884. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21885. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21886. * as a texture for further usage.
  21887. *
  21888. * ```js
  21889. * const pixelRatio = window.devicePixelRatio;
  21890. * const textureSize = 128 * pixelRatio;
  21891. *
  21892. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21893. *
  21894. * // calculate start position for copying part of the frame data
  21895. * const vector = new Vector2();
  21896. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21897. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21898. *
  21899. * renderer.render( scene, camera );
  21900. *
  21901. * // copy part of the rendered frame into the framebuffer texture
  21902. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21903. * ```
  21904. *
  21905. * @augments Texture
  21906. */
  21907. class FramebufferTexture extends Texture {
  21908. /**
  21909. * Constructs a new framebuffer texture.
  21910. *
  21911. * @param {number} [width] - The width of the texture.
  21912. * @param {number} [height] - The height of the texture.
  21913. */
  21914. constructor( width, height ) {
  21915. super( { width, height } );
  21916. /**
  21917. * This flag can be used for type testing.
  21918. *
  21919. * @type {boolean}
  21920. * @readonly
  21921. * @default true
  21922. */
  21923. this.isFramebufferTexture = true;
  21924. /**
  21925. * How the texture is sampled when a texel covers more than one pixel.
  21926. *
  21927. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21928. *
  21929. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21930. * @default NearestFilter
  21931. */
  21932. this.magFilter = NearestFilter;
  21933. /**
  21934. * How the texture is sampled when a texel covers less than one pixel.
  21935. *
  21936. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21937. *
  21938. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21939. * @default NearestFilter
  21940. */
  21941. this.minFilter = NearestFilter;
  21942. /**
  21943. * Whether to generate mipmaps (if possible) for a texture.
  21944. *
  21945. * Overwritten and set to `false` by default.
  21946. *
  21947. * @type {boolean}
  21948. * @default false
  21949. */
  21950. this.generateMipmaps = false;
  21951. this.needsUpdate = true;
  21952. }
  21953. }
  21954. /**
  21955. * Creates a texture based on data in compressed form.
  21956. *
  21957. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21958. *
  21959. * @augments Texture
  21960. */
  21961. class CompressedTexture extends Texture {
  21962. /**
  21963. * Constructs a new compressed texture.
  21964. *
  21965. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21966. * the data and dimensions.
  21967. * @param {number} width - The width of the texture.
  21968. * @param {number} height - The height of the texture.
  21969. * @param {number} [format=RGBAFormat] - The texture format.
  21970. * @param {number} [type=UnsignedByteType] - The texture type.
  21971. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21972. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21973. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21974. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21975. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21976. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21977. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21978. */
  21979. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21980. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21981. /**
  21982. * This flag can be used for type testing.
  21983. *
  21984. * @type {boolean}
  21985. * @readonly
  21986. * @default true
  21987. */
  21988. this.isCompressedTexture = true;
  21989. /**
  21990. * The image property of a compressed texture just defines its dimensions.
  21991. *
  21992. * @type {{width:number,height:number}}
  21993. */
  21994. this.image = { width: width, height: height };
  21995. /**
  21996. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21997. *
  21998. * @type {Array<Object>}
  21999. */
  22000. this.mipmaps = mipmaps;
  22001. /**
  22002. * If set to `true`, the texture is flipped along the vertical axis when
  22003. * uploaded to the GPU.
  22004. *
  22005. * Overwritten and set to `false` by default since it is not possible to
  22006. * flip compressed textures.
  22007. *
  22008. * @type {boolean}
  22009. * @default false
  22010. * @readonly
  22011. */
  22012. this.flipY = false;
  22013. /**
  22014. * Whether to generate mipmaps (if possible) for a texture.
  22015. *
  22016. * Overwritten and set to `false` by default since it is not
  22017. * possible to generate mipmaps for compressed data. Mipmaps
  22018. * must be embedded in the compressed texture file.
  22019. *
  22020. * @type {boolean}
  22021. * @default false
  22022. * @readonly
  22023. */
  22024. this.generateMipmaps = false;
  22025. }
  22026. }
  22027. /**
  22028. * Creates a texture 2D array based on data in compressed form.
  22029. *
  22030. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22031. *
  22032. * @augments CompressedTexture
  22033. */
  22034. class CompressedArrayTexture extends CompressedTexture {
  22035. /**
  22036. * Constructs a new compressed array texture.
  22037. *
  22038. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22039. * the data and dimensions.
  22040. * @param {number} width - The width of the texture.
  22041. * @param {number} height - The height of the texture.
  22042. * @param {number} depth - The depth of the texture.
  22043. * @param {number} [format=RGBAFormat] - The min filter value.
  22044. * @param {number} [type=UnsignedByteType] - The min filter value.
  22045. */
  22046. constructor( mipmaps, width, height, depth, format, type ) {
  22047. super( mipmaps, width, height, format, type );
  22048. /**
  22049. * This flag can be used for type testing.
  22050. *
  22051. * @type {boolean}
  22052. * @readonly
  22053. * @default true
  22054. */
  22055. this.isCompressedArrayTexture = true;
  22056. /**
  22057. * The image property of a compressed texture just defines its dimensions.
  22058. *
  22059. * @name CompressedArrayTexture#image
  22060. * @type {{width:number,height:number,depth:number}}
  22061. */
  22062. this.image.depth = depth;
  22063. /**
  22064. * This defines how the texture is wrapped in the depth and corresponds to
  22065. * *W* in UVW mapping.
  22066. *
  22067. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22068. * @default ClampToEdgeWrapping
  22069. */
  22070. this.wrapR = ClampToEdgeWrapping;
  22071. /**
  22072. * A set of all layers which need to be updated in the texture.
  22073. *
  22074. * @type {Set<number>}
  22075. */
  22076. this.layerUpdates = new Set();
  22077. }
  22078. /**
  22079. * Describes that a specific layer of the texture needs to be updated.
  22080. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22081. * entire compressed texture array is sent to the GPU. Marking specific
  22082. * layers will only transmit subsets of all mipmaps associated with a
  22083. * specific depth in the array which is often much more performant.
  22084. *
  22085. * @param {number} layerIndex - The layer index that should be updated.
  22086. */
  22087. addLayerUpdate( layerIndex ) {
  22088. this.layerUpdates.add( layerIndex );
  22089. }
  22090. /**
  22091. * Resets the layer updates registry.
  22092. */
  22093. clearLayerUpdates() {
  22094. this.layerUpdates.clear();
  22095. }
  22096. }
  22097. /**
  22098. * Creates a cube texture based on data in compressed form.
  22099. *
  22100. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22101. *
  22102. * @augments CompressedTexture
  22103. */
  22104. class CompressedCubeTexture extends CompressedTexture {
  22105. /**
  22106. * Constructs a new compressed texture.
  22107. *
  22108. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22109. * @param {number} [format=RGBAFormat] - The texture format.
  22110. * @param {number} [type=UnsignedByteType] - The texture type.
  22111. */
  22112. constructor( images, format, type ) {
  22113. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22114. /**
  22115. * This flag can be used for type testing.
  22116. *
  22117. * @type {boolean}
  22118. * @readonly
  22119. * @default true
  22120. */
  22121. this.isCompressedCubeTexture = true;
  22122. /**
  22123. * This flag can be used for type testing.
  22124. *
  22125. * @type {boolean}
  22126. * @readonly
  22127. * @default true
  22128. */
  22129. this.isCubeTexture = true;
  22130. this.image = images;
  22131. }
  22132. }
  22133. /**
  22134. * Creates a texture from a canvas element.
  22135. *
  22136. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22137. * to `true` immediately since a canvas can directly be used for rendering.
  22138. *
  22139. * @augments Texture
  22140. */
  22141. class CanvasTexture extends Texture {
  22142. /**
  22143. * Constructs a new texture.
  22144. *
  22145. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22146. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22147. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22148. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22149. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22150. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22151. * @param {number} [format=RGBAFormat] - The texture format.
  22152. * @param {number} [type=UnsignedByteType] - The texture type.
  22153. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22154. */
  22155. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22156. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22157. /**
  22158. * This flag can be used for type testing.
  22159. *
  22160. * @type {boolean}
  22161. * @readonly
  22162. * @default true
  22163. */
  22164. this.isCanvasTexture = true;
  22165. this.needsUpdate = true;
  22166. }
  22167. }
  22168. /**
  22169. * This class can be used to automatically save the depth information of a
  22170. * rendering into a texture.
  22171. *
  22172. * @augments Texture
  22173. */
  22174. class DepthTexture extends Texture {
  22175. /**
  22176. * Constructs a new depth texture.
  22177. *
  22178. * @param {number} width - The width of the texture.
  22179. * @param {number} height - The height of the texture.
  22180. * @param {number} [type=UnsignedIntType] - The texture type.
  22181. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22182. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22183. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22184. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22185. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22186. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22187. * @param {number} [format=DepthFormat] - The texture format.
  22188. * @param {number} [depth=1] - The depth of the texture.
  22189. */
  22190. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22191. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22192. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22193. }
  22194. const image = { width: width, height: height, depth: depth };
  22195. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22196. /**
  22197. * This flag can be used for type testing.
  22198. *
  22199. * @type {boolean}
  22200. * @readonly
  22201. * @default true
  22202. */
  22203. this.isDepthTexture = true;
  22204. /**
  22205. * If set to `true`, the texture is flipped along the vertical axis when
  22206. * uploaded to the GPU.
  22207. *
  22208. * Overwritten and set to `false` by default.
  22209. *
  22210. * @type {boolean}
  22211. * @default false
  22212. */
  22213. this.flipY = false;
  22214. /**
  22215. * Whether to generate mipmaps (if possible) for a texture.
  22216. *
  22217. * Overwritten and set to `false` by default.
  22218. *
  22219. * @type {boolean}
  22220. * @default false
  22221. */
  22222. this.generateMipmaps = false;
  22223. /**
  22224. * Code corresponding to the depth compare function.
  22225. *
  22226. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22227. * @default null
  22228. */
  22229. this.compareFunction = null;
  22230. }
  22231. copy( source ) {
  22232. super.copy( source );
  22233. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22234. this.compareFunction = source.compareFunction;
  22235. return this;
  22236. }
  22237. toJSON( meta ) {
  22238. const data = super.toJSON( meta );
  22239. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22240. return data;
  22241. }
  22242. }
  22243. /**
  22244. * This class can be used to automatically save the depth information of a
  22245. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22246. *
  22247. * @augments DepthTexture
  22248. */
  22249. class CubeDepthTexture extends DepthTexture {
  22250. /**
  22251. * Constructs a new cube depth texture.
  22252. *
  22253. * @param {number} size - The size (width and height) of each cube face.
  22254. * @param {number} [type=UnsignedIntType] - The texture type.
  22255. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22256. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22257. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22258. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22259. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22260. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22261. * @param {number} [format=DepthFormat] - The texture format.
  22262. */
  22263. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22264. // Create 6 identical image descriptors for the cube faces
  22265. const image = { width: size, height: size, depth: 1 };
  22266. const images = [ image, image, image, image, image, image ];
  22267. // Call DepthTexture constructor with width, height
  22268. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22269. // Replace the single image with the array of 6 images
  22270. this.image = images;
  22271. /**
  22272. * This flag can be used for type testing.
  22273. *
  22274. * @type {boolean}
  22275. * @readonly
  22276. * @default true
  22277. */
  22278. this.isCubeDepthTexture = true;
  22279. /**
  22280. * Set to true for cube texture handling in WebGLTextures.
  22281. *
  22282. * @type {boolean}
  22283. * @readonly
  22284. * @default true
  22285. */
  22286. this.isCubeTexture = true;
  22287. }
  22288. /**
  22289. * Alias for {@link CubeDepthTexture#image}.
  22290. *
  22291. * @type {Array<Image>}
  22292. */
  22293. get images() {
  22294. return this.image;
  22295. }
  22296. set images( value ) {
  22297. this.image = value;
  22298. }
  22299. }
  22300. /**
  22301. * Represents a texture created externally with the same renderer context.
  22302. *
  22303. * This may be a texture from a protected media stream, device camera feed,
  22304. * or other data feeds like a depth sensor.
  22305. *
  22306. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22307. * the {@link WebGPURenderer} WebGPU backend.
  22308. *
  22309. * @augments Texture
  22310. */
  22311. class ExternalTexture extends Texture {
  22312. /**
  22313. * Creates a new raw texture.
  22314. *
  22315. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22316. */
  22317. constructor( sourceTexture = null ) {
  22318. super();
  22319. /**
  22320. * The external source texture.
  22321. *
  22322. * @type {?(WebGLTexture|GPUTexture)}
  22323. * @default null
  22324. */
  22325. this.sourceTexture = sourceTexture;
  22326. /**
  22327. * This flag can be used for type testing.
  22328. *
  22329. * @type {boolean}
  22330. * @readonly
  22331. * @default true
  22332. */
  22333. this.isExternalTexture = true;
  22334. }
  22335. copy( source ) {
  22336. super.copy( source );
  22337. this.sourceTexture = source.sourceTexture;
  22338. return this;
  22339. }
  22340. }
  22341. /**
  22342. * A geometry class for representing a capsule.
  22343. *
  22344. * ```js
  22345. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22346. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22347. * const capsule = new THREE.Mesh( geometry, material );
  22348. * scene.add( capsule );
  22349. * ```
  22350. *
  22351. * @augments BufferGeometry
  22352. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22353. */
  22354. class CapsuleGeometry extends BufferGeometry {
  22355. /**
  22356. * Constructs a new capsule geometry.
  22357. *
  22358. * @param {number} [radius=1] - Radius of the capsule.
  22359. * @param {number} [height=1] - Height of the middle section.
  22360. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22361. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22362. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22363. */
  22364. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22365. super();
  22366. this.type = 'CapsuleGeometry';
  22367. /**
  22368. * Holds the constructor parameters that have been
  22369. * used to generate the geometry. Any modification
  22370. * after instantiation does not change the geometry.
  22371. *
  22372. * @type {Object}
  22373. */
  22374. this.parameters = {
  22375. radius: radius,
  22376. height: height,
  22377. capSegments: capSegments,
  22378. radialSegments: radialSegments,
  22379. heightSegments: heightSegments,
  22380. };
  22381. height = Math.max( 0, height );
  22382. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22383. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22384. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22385. // buffers
  22386. const indices = [];
  22387. const vertices = [];
  22388. const normals = [];
  22389. const uvs = [];
  22390. // helper variables
  22391. const halfHeight = height / 2;
  22392. const capArcLength = ( Math.PI / 2 ) * radius;
  22393. const cylinderPartLength = height;
  22394. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22395. const numVerticalSegments = capSegments * 2 + heightSegments;
  22396. const verticesPerRow = radialSegments + 1;
  22397. const normal = new Vector3();
  22398. const vertex = new Vector3();
  22399. // generate vertices, normals, and uvs
  22400. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22401. let currentArcLength = 0;
  22402. let profileY = 0;
  22403. let profileRadius = 0;
  22404. let normalYComponent = 0;
  22405. if ( iy <= capSegments ) {
  22406. // bottom cap
  22407. const segmentProgress = iy / capSegments;
  22408. const angle = ( segmentProgress * Math.PI ) / 2;
  22409. profileY = - halfHeight - radius * Math.cos( angle );
  22410. profileRadius = radius * Math.sin( angle );
  22411. normalYComponent = - radius * Math.cos( angle );
  22412. currentArcLength = segmentProgress * capArcLength;
  22413. } else if ( iy <= capSegments + heightSegments ) {
  22414. // middle section
  22415. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22416. profileY = - halfHeight + segmentProgress * height;
  22417. profileRadius = radius;
  22418. normalYComponent = 0;
  22419. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22420. } else {
  22421. // top cap
  22422. const segmentProgress =
  22423. ( iy - capSegments - heightSegments ) / capSegments;
  22424. const angle = ( segmentProgress * Math.PI ) / 2;
  22425. profileY = halfHeight + radius * Math.sin( angle );
  22426. profileRadius = radius * Math.cos( angle );
  22427. normalYComponent = radius * Math.sin( angle );
  22428. currentArcLength =
  22429. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22430. }
  22431. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22432. // special case for the poles
  22433. let uOffset = 0;
  22434. if ( iy === 0 ) {
  22435. uOffset = 0.5 / radialSegments;
  22436. } else if ( iy === numVerticalSegments ) {
  22437. uOffset = -0.5 / radialSegments;
  22438. }
  22439. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22440. const u = ix / radialSegments;
  22441. const theta = u * Math.PI * 2;
  22442. const sinTheta = Math.sin( theta );
  22443. const cosTheta = Math.cos( theta );
  22444. // vertex
  22445. vertex.x = - profileRadius * cosTheta;
  22446. vertex.y = profileY;
  22447. vertex.z = profileRadius * sinTheta;
  22448. vertices.push( vertex.x, vertex.y, vertex.z );
  22449. // normal
  22450. normal.set(
  22451. - profileRadius * cosTheta,
  22452. normalYComponent,
  22453. profileRadius * sinTheta
  22454. );
  22455. normal.normalize();
  22456. normals.push( normal.x, normal.y, normal.z );
  22457. // uv
  22458. uvs.push( u + uOffset, v );
  22459. }
  22460. if ( iy > 0 ) {
  22461. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22462. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22463. const i1 = prevIndexRow + ix;
  22464. const i2 = prevIndexRow + ix + 1;
  22465. const i3 = iy * verticesPerRow + ix;
  22466. const i4 = iy * verticesPerRow + ix + 1;
  22467. indices.push( i1, i2, i3 );
  22468. indices.push( i2, i4, i3 );
  22469. }
  22470. }
  22471. }
  22472. // build geometry
  22473. this.setIndex( indices );
  22474. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22475. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22476. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22477. }
  22478. copy( source ) {
  22479. super.copy( source );
  22480. this.parameters = Object.assign( {}, source.parameters );
  22481. return this;
  22482. }
  22483. /**
  22484. * Factory method for creating an instance of this class from the given
  22485. * JSON object.
  22486. *
  22487. * @param {Object} data - A JSON object representing the serialized geometry.
  22488. * @return {CapsuleGeometry} A new instance.
  22489. */
  22490. static fromJSON( data ) {
  22491. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22492. }
  22493. }
  22494. /**
  22495. * A simple shape of Euclidean geometry. It is constructed from a
  22496. * number of triangular segments that are oriented around a central point and
  22497. * extend as far out as a given radius. It is built counter-clockwise from a
  22498. * start angle and a given central angle. It can also be used to create
  22499. * regular polygons, where the number of segments determines the number of
  22500. * sides.
  22501. *
  22502. * ```js
  22503. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22504. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22505. * const circle = new THREE.Mesh( geometry, material );
  22506. * scene.add( circle )
  22507. * ```
  22508. *
  22509. * @augments BufferGeometry
  22510. * @demo scenes/geometry-browser.html#CircleGeometry
  22511. */
  22512. class CircleGeometry extends BufferGeometry {
  22513. /**
  22514. * Constructs a new circle geometry.
  22515. *
  22516. * @param {number} [radius=1] - Radius of the circle.
  22517. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22518. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22519. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22520. * of the circular sector in radians. The default value results in a complete circle.
  22521. */
  22522. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22523. super();
  22524. this.type = 'CircleGeometry';
  22525. /**
  22526. * Holds the constructor parameters that have been
  22527. * used to generate the geometry. Any modification
  22528. * after instantiation does not change the geometry.
  22529. *
  22530. * @type {Object}
  22531. */
  22532. this.parameters = {
  22533. radius: radius,
  22534. segments: segments,
  22535. thetaStart: thetaStart,
  22536. thetaLength: thetaLength
  22537. };
  22538. segments = Math.max( 3, segments );
  22539. // buffers
  22540. const indices = [];
  22541. const vertices = [];
  22542. const normals = [];
  22543. const uvs = [];
  22544. // helper variables
  22545. const vertex = new Vector3();
  22546. const uv = new Vector2();
  22547. // center point
  22548. vertices.push( 0, 0, 0 );
  22549. normals.push( 0, 0, 1 );
  22550. uvs.push( 0.5, 0.5 );
  22551. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22552. const segment = thetaStart + s / segments * thetaLength;
  22553. // vertex
  22554. vertex.x = radius * Math.cos( segment );
  22555. vertex.y = radius * Math.sin( segment );
  22556. vertices.push( vertex.x, vertex.y, vertex.z );
  22557. // normal
  22558. normals.push( 0, 0, 1 );
  22559. // uvs
  22560. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22561. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22562. uvs.push( uv.x, uv.y );
  22563. }
  22564. // indices
  22565. for ( let i = 1; i <= segments; i ++ ) {
  22566. indices.push( i, i + 1, 0 );
  22567. }
  22568. // build geometry
  22569. this.setIndex( indices );
  22570. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22571. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22572. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22573. }
  22574. copy( source ) {
  22575. super.copy( source );
  22576. this.parameters = Object.assign( {}, source.parameters );
  22577. return this;
  22578. }
  22579. /**
  22580. * Factory method for creating an instance of this class from the given
  22581. * JSON object.
  22582. *
  22583. * @param {Object} data - A JSON object representing the serialized geometry.
  22584. * @return {CircleGeometry} A new instance.
  22585. */
  22586. static fromJSON( data ) {
  22587. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22588. }
  22589. }
  22590. /**
  22591. * A geometry class for representing a cylinder.
  22592. *
  22593. * ```js
  22594. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22595. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22596. * const cylinder = new THREE.Mesh( geometry, material );
  22597. * scene.add( cylinder );
  22598. * ```
  22599. *
  22600. * @augments BufferGeometry
  22601. * @demo scenes/geometry-browser.html#CylinderGeometry
  22602. */
  22603. class CylinderGeometry extends BufferGeometry {
  22604. /**
  22605. * Constructs a new cylinder geometry.
  22606. *
  22607. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22608. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22609. * @param {number} [height=1] - Height of the cylinder.
  22610. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22611. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22612. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22613. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22614. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22615. * The default value results in a complete cylinder.
  22616. */
  22617. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22618. super();
  22619. this.type = 'CylinderGeometry';
  22620. /**
  22621. * Holds the constructor parameters that have been
  22622. * used to generate the geometry. Any modification
  22623. * after instantiation does not change the geometry.
  22624. *
  22625. * @type {Object}
  22626. */
  22627. this.parameters = {
  22628. radiusTop: radiusTop,
  22629. radiusBottom: radiusBottom,
  22630. height: height,
  22631. radialSegments: radialSegments,
  22632. heightSegments: heightSegments,
  22633. openEnded: openEnded,
  22634. thetaStart: thetaStart,
  22635. thetaLength: thetaLength
  22636. };
  22637. const scope = this;
  22638. radialSegments = Math.floor( radialSegments );
  22639. heightSegments = Math.floor( heightSegments );
  22640. // buffers
  22641. const indices = [];
  22642. const vertices = [];
  22643. const normals = [];
  22644. const uvs = [];
  22645. // helper variables
  22646. let index = 0;
  22647. const indexArray = [];
  22648. const halfHeight = height / 2;
  22649. let groupStart = 0;
  22650. // generate geometry
  22651. generateTorso();
  22652. if ( openEnded === false ) {
  22653. if ( radiusTop > 0 ) generateCap( true );
  22654. if ( radiusBottom > 0 ) generateCap( false );
  22655. }
  22656. // build geometry
  22657. this.setIndex( indices );
  22658. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22659. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22660. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22661. function generateTorso() {
  22662. const normal = new Vector3();
  22663. const vertex = new Vector3();
  22664. let groupCount = 0;
  22665. // this will be used to calculate the normal
  22666. const slope = ( radiusBottom - radiusTop ) / height;
  22667. // generate vertices, normals and uvs
  22668. for ( let y = 0; y <= heightSegments; y ++ ) {
  22669. const indexRow = [];
  22670. const v = y / heightSegments;
  22671. // calculate the radius of the current row
  22672. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22673. for ( let x = 0; x <= radialSegments; x ++ ) {
  22674. const u = x / radialSegments;
  22675. const theta = u * thetaLength + thetaStart;
  22676. const sinTheta = Math.sin( theta );
  22677. const cosTheta = Math.cos( theta );
  22678. // vertex
  22679. vertex.x = radius * sinTheta;
  22680. vertex.y = - v * height + halfHeight;
  22681. vertex.z = radius * cosTheta;
  22682. vertices.push( vertex.x, vertex.y, vertex.z );
  22683. // normal
  22684. normal.set( sinTheta, slope, cosTheta ).normalize();
  22685. normals.push( normal.x, normal.y, normal.z );
  22686. // uv
  22687. uvs.push( u, 1 - v );
  22688. // save index of vertex in respective row
  22689. indexRow.push( index ++ );
  22690. }
  22691. // now save vertices of the row in our index array
  22692. indexArray.push( indexRow );
  22693. }
  22694. // generate indices
  22695. for ( let x = 0; x < radialSegments; x ++ ) {
  22696. for ( let y = 0; y < heightSegments; y ++ ) {
  22697. // we use the index array to access the correct indices
  22698. const a = indexArray[ y ][ x ];
  22699. const b = indexArray[ y + 1 ][ x ];
  22700. const c = indexArray[ y + 1 ][ x + 1 ];
  22701. const d = indexArray[ y ][ x + 1 ];
  22702. // faces
  22703. if ( radiusTop > 0 || y !== 0 ) {
  22704. indices.push( a, b, d );
  22705. groupCount += 3;
  22706. }
  22707. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22708. indices.push( b, c, d );
  22709. groupCount += 3;
  22710. }
  22711. }
  22712. }
  22713. // add a group to the geometry. this will ensure multi material support
  22714. scope.addGroup( groupStart, groupCount, 0 );
  22715. // calculate new start value for groups
  22716. groupStart += groupCount;
  22717. }
  22718. function generateCap( top ) {
  22719. // save the index of the first center vertex
  22720. const centerIndexStart = index;
  22721. const uv = new Vector2();
  22722. const vertex = new Vector3();
  22723. let groupCount = 0;
  22724. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22725. const sign = ( top === true ) ? 1 : -1;
  22726. // first we generate the center vertex data of the cap.
  22727. // because the geometry needs one set of uvs per face,
  22728. // we must generate a center vertex per face/segment
  22729. for ( let x = 1; x <= radialSegments; x ++ ) {
  22730. // vertex
  22731. vertices.push( 0, halfHeight * sign, 0 );
  22732. // normal
  22733. normals.push( 0, sign, 0 );
  22734. // uv
  22735. uvs.push( 0.5, 0.5 );
  22736. // increase index
  22737. index ++;
  22738. }
  22739. // save the index of the last center vertex
  22740. const centerIndexEnd = index;
  22741. // now we generate the surrounding vertices, normals and uvs
  22742. for ( let x = 0; x <= radialSegments; x ++ ) {
  22743. const u = x / radialSegments;
  22744. const theta = u * thetaLength + thetaStart;
  22745. const cosTheta = Math.cos( theta );
  22746. const sinTheta = Math.sin( theta );
  22747. // vertex
  22748. vertex.x = radius * sinTheta;
  22749. vertex.y = halfHeight * sign;
  22750. vertex.z = radius * cosTheta;
  22751. vertices.push( vertex.x, vertex.y, vertex.z );
  22752. // normal
  22753. normals.push( 0, sign, 0 );
  22754. // uv
  22755. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22756. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22757. uvs.push( uv.x, uv.y );
  22758. // increase index
  22759. index ++;
  22760. }
  22761. // generate indices
  22762. for ( let x = 0; x < radialSegments; x ++ ) {
  22763. const c = centerIndexStart + x;
  22764. const i = centerIndexEnd + x;
  22765. if ( top === true ) {
  22766. // face top
  22767. indices.push( i, i + 1, c );
  22768. } else {
  22769. // face bottom
  22770. indices.push( i + 1, i, c );
  22771. }
  22772. groupCount += 3;
  22773. }
  22774. // add a group to the geometry. this will ensure multi material support
  22775. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22776. // calculate new start value for groups
  22777. groupStart += groupCount;
  22778. }
  22779. }
  22780. copy( source ) {
  22781. super.copy( source );
  22782. this.parameters = Object.assign( {}, source.parameters );
  22783. return this;
  22784. }
  22785. /**
  22786. * Factory method for creating an instance of this class from the given
  22787. * JSON object.
  22788. *
  22789. * @param {Object} data - A JSON object representing the serialized geometry.
  22790. * @return {CylinderGeometry} A new instance.
  22791. */
  22792. static fromJSON( data ) {
  22793. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22794. }
  22795. }
  22796. /**
  22797. * A geometry class for representing a cone.
  22798. *
  22799. * ```js
  22800. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22801. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22802. * const cone = new THREE.Mesh(geometry, material );
  22803. * scene.add( cone );
  22804. * ```
  22805. *
  22806. * @augments CylinderGeometry
  22807. * @demo scenes/geometry-browser.html#ConeGeometry
  22808. */
  22809. class ConeGeometry extends CylinderGeometry {
  22810. /**
  22811. * Constructs a new cone geometry.
  22812. *
  22813. * @param {number} [radius=1] - Radius of the cone base.
  22814. * @param {number} [height=1] - Height of the cone.
  22815. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22816. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22817. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22818. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22819. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22820. * The default value results in a complete cone.
  22821. */
  22822. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22823. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22824. this.type = 'ConeGeometry';
  22825. /**
  22826. * Holds the constructor parameters that have been
  22827. * used to generate the geometry. Any modification
  22828. * after instantiation does not change the geometry.
  22829. *
  22830. * @type {Object}
  22831. */
  22832. this.parameters = {
  22833. radius: radius,
  22834. height: height,
  22835. radialSegments: radialSegments,
  22836. heightSegments: heightSegments,
  22837. openEnded: openEnded,
  22838. thetaStart: thetaStart,
  22839. thetaLength: thetaLength
  22840. };
  22841. }
  22842. /**
  22843. * Factory method for creating an instance of this class from the given
  22844. * JSON object.
  22845. *
  22846. * @param {Object} data - A JSON object representing the serialized geometry.
  22847. * @return {ConeGeometry} A new instance.
  22848. */
  22849. static fromJSON( data ) {
  22850. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22851. }
  22852. }
  22853. /**
  22854. * A polyhedron is a solid in three dimensions with flat faces. This class
  22855. * will take an array of vertices, project them onto a sphere, and then
  22856. * divide them up to the desired level of detail.
  22857. *
  22858. * @augments BufferGeometry
  22859. */
  22860. class PolyhedronGeometry extends BufferGeometry {
  22861. /**
  22862. * Constructs a new polyhedron geometry.
  22863. *
  22864. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22865. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22866. * @param {number} [radius=1] - The radius of the shape.
  22867. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22868. */
  22869. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22870. super();
  22871. this.type = 'PolyhedronGeometry';
  22872. /**
  22873. * Holds the constructor parameters that have been
  22874. * used to generate the geometry. Any modification
  22875. * after instantiation does not change the geometry.
  22876. *
  22877. * @type {Object}
  22878. */
  22879. this.parameters = {
  22880. vertices: vertices,
  22881. indices: indices,
  22882. radius: radius,
  22883. detail: detail
  22884. };
  22885. // default buffer data
  22886. const vertexBuffer = [];
  22887. const uvBuffer = [];
  22888. // the subdivision creates the vertex buffer data
  22889. subdivide( detail );
  22890. // all vertices should lie on a conceptual sphere with a given radius
  22891. applyRadius( radius );
  22892. // finally, create the uv data
  22893. generateUVs();
  22894. // build non-indexed geometry
  22895. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22896. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22897. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22898. if ( detail === 0 ) {
  22899. this.computeVertexNormals(); // flat normals
  22900. } else {
  22901. this.normalizeNormals(); // smooth normals
  22902. }
  22903. // helper functions
  22904. function subdivide( detail ) {
  22905. const a = new Vector3();
  22906. const b = new Vector3();
  22907. const c = new Vector3();
  22908. // iterate over all faces and apply a subdivision with the given detail value
  22909. for ( let i = 0; i < indices.length; i += 3 ) {
  22910. // get the vertices of the face
  22911. getVertexByIndex( indices[ i + 0 ], a );
  22912. getVertexByIndex( indices[ i + 1 ], b );
  22913. getVertexByIndex( indices[ i + 2 ], c );
  22914. // perform subdivision
  22915. subdivideFace( a, b, c, detail );
  22916. }
  22917. }
  22918. function subdivideFace( a, b, c, detail ) {
  22919. const cols = detail + 1;
  22920. // we use this multidimensional array as a data structure for creating the subdivision
  22921. const v = [];
  22922. // construct all of the vertices for this subdivision
  22923. for ( let i = 0; i <= cols; i ++ ) {
  22924. v[ i ] = [];
  22925. const aj = a.clone().lerp( c, i / cols );
  22926. const bj = b.clone().lerp( c, i / cols );
  22927. const rows = cols - i;
  22928. for ( let j = 0; j <= rows; j ++ ) {
  22929. if ( j === 0 && i === cols ) {
  22930. v[ i ][ j ] = aj;
  22931. } else {
  22932. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22933. }
  22934. }
  22935. }
  22936. // construct all of the faces
  22937. for ( let i = 0; i < cols; i ++ ) {
  22938. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22939. const k = Math.floor( j / 2 );
  22940. if ( j % 2 === 0 ) {
  22941. pushVertex( v[ i ][ k + 1 ] );
  22942. pushVertex( v[ i + 1 ][ k ] );
  22943. pushVertex( v[ i ][ k ] );
  22944. } else {
  22945. pushVertex( v[ i ][ k + 1 ] );
  22946. pushVertex( v[ i + 1 ][ k + 1 ] );
  22947. pushVertex( v[ i + 1 ][ k ] );
  22948. }
  22949. }
  22950. }
  22951. }
  22952. function applyRadius( radius ) {
  22953. const vertex = new Vector3();
  22954. // iterate over the entire buffer and apply the radius to each vertex
  22955. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22956. vertex.x = vertexBuffer[ i + 0 ];
  22957. vertex.y = vertexBuffer[ i + 1 ];
  22958. vertex.z = vertexBuffer[ i + 2 ];
  22959. vertex.normalize().multiplyScalar( radius );
  22960. vertexBuffer[ i + 0 ] = vertex.x;
  22961. vertexBuffer[ i + 1 ] = vertex.y;
  22962. vertexBuffer[ i + 2 ] = vertex.z;
  22963. }
  22964. }
  22965. function generateUVs() {
  22966. const vertex = new Vector3();
  22967. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22968. vertex.x = vertexBuffer[ i + 0 ];
  22969. vertex.y = vertexBuffer[ i + 1 ];
  22970. vertex.z = vertexBuffer[ i + 2 ];
  22971. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22972. const v = inclination( vertex ) / Math.PI + 0.5;
  22973. uvBuffer.push( u, 1 - v );
  22974. }
  22975. correctUVs();
  22976. correctSeam();
  22977. }
  22978. function correctSeam() {
  22979. // handle case when face straddles the seam, see #3269
  22980. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22981. // uv data of a single face
  22982. const x0 = uvBuffer[ i + 0 ];
  22983. const x1 = uvBuffer[ i + 2 ];
  22984. const x2 = uvBuffer[ i + 4 ];
  22985. const max = Math.max( x0, x1, x2 );
  22986. const min = Math.min( x0, x1, x2 );
  22987. // 0.9 is somewhat arbitrary
  22988. if ( max > 0.9 && min < 0.1 ) {
  22989. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22990. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22991. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22992. }
  22993. }
  22994. }
  22995. function pushVertex( vertex ) {
  22996. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22997. }
  22998. function getVertexByIndex( index, vertex ) {
  22999. const stride = index * 3;
  23000. vertex.x = vertices[ stride + 0 ];
  23001. vertex.y = vertices[ stride + 1 ];
  23002. vertex.z = vertices[ stride + 2 ];
  23003. }
  23004. function correctUVs() {
  23005. const a = new Vector3();
  23006. const b = new Vector3();
  23007. const c = new Vector3();
  23008. const centroid = new Vector3();
  23009. const uvA = new Vector2();
  23010. const uvB = new Vector2();
  23011. const uvC = new Vector2();
  23012. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23013. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23014. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23015. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23016. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23017. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23018. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23019. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23020. const azi = azimuth( centroid );
  23021. correctUV( uvA, j + 0, a, azi );
  23022. correctUV( uvB, j + 2, b, azi );
  23023. correctUV( uvC, j + 4, c, azi );
  23024. }
  23025. }
  23026. function correctUV( uv, stride, vector, azimuth ) {
  23027. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23028. uvBuffer[ stride ] = uv.x - 1;
  23029. }
  23030. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23031. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23032. }
  23033. }
  23034. // Angle around the Y axis, counter-clockwise when looking from above.
  23035. function azimuth( vector ) {
  23036. return Math.atan2( vector.z, - vector.x );
  23037. }
  23038. // Angle above the XZ plane.
  23039. function inclination( vector ) {
  23040. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23041. }
  23042. }
  23043. copy( source ) {
  23044. super.copy( source );
  23045. this.parameters = Object.assign( {}, source.parameters );
  23046. return this;
  23047. }
  23048. /**
  23049. * Factory method for creating an instance of this class from the given
  23050. * JSON object.
  23051. *
  23052. * @param {Object} data - A JSON object representing the serialized geometry.
  23053. * @return {PolyhedronGeometry} A new instance.
  23054. */
  23055. static fromJSON( data ) {
  23056. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.detail );
  23057. }
  23058. }
  23059. /**
  23060. * A geometry class for representing a dodecahedron.
  23061. *
  23062. * ```js
  23063. * const geometry = new THREE.DodecahedronGeometry();
  23064. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23065. * const dodecahedron = new THREE.Mesh( geometry, material );
  23066. * scene.add( dodecahedron );
  23067. * ```
  23068. *
  23069. * @augments PolyhedronGeometry
  23070. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23071. */
  23072. class DodecahedronGeometry extends PolyhedronGeometry {
  23073. /**
  23074. * Constructs a new dodecahedron geometry.
  23075. *
  23076. * @param {number} [radius=1] - Radius of the dodecahedron.
  23077. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23078. */
  23079. constructor( radius = 1, detail = 0 ) {
  23080. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23081. const r = 1 / t;
  23082. const vertices = [
  23083. // (±1, ±1, ±1)
  23084. -1, -1, -1, -1, -1, 1,
  23085. -1, 1, -1, -1, 1, 1,
  23086. 1, -1, -1, 1, -1, 1,
  23087. 1, 1, -1, 1, 1, 1,
  23088. // (0, ±1/φ, ±φ)
  23089. 0, - r, - t, 0, - r, t,
  23090. 0, r, - t, 0, r, t,
  23091. // (±1/φ, ±φ, 0)
  23092. - r, - t, 0, - r, t, 0,
  23093. r, - t, 0, r, t, 0,
  23094. // (±φ, 0, ±1/φ)
  23095. - t, 0, - r, t, 0, - r,
  23096. - t, 0, r, t, 0, r
  23097. ];
  23098. const indices = [
  23099. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23100. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23101. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23102. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23103. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23104. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23105. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23106. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23107. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23108. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23109. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23110. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23111. ];
  23112. super( vertices, indices, radius, detail );
  23113. this.type = 'DodecahedronGeometry';
  23114. /**
  23115. * Holds the constructor parameters that have been
  23116. * used to generate the geometry. Any modification
  23117. * after instantiation does not change the geometry.
  23118. *
  23119. * @type {Object}
  23120. */
  23121. this.parameters = {
  23122. radius: radius,
  23123. detail: detail
  23124. };
  23125. }
  23126. /**
  23127. * Factory method for creating an instance of this class from the given
  23128. * JSON object.
  23129. *
  23130. * @param {Object} data - A JSON object representing the serialized geometry.
  23131. * @return {DodecahedronGeometry} A new instance.
  23132. */
  23133. static fromJSON( data ) {
  23134. return new DodecahedronGeometry( data.radius, data.detail );
  23135. }
  23136. }
  23137. const _v0$1 = /*@__PURE__*/ new Vector3();
  23138. const _v1$1 = /*@__PURE__*/ new Vector3();
  23139. const _normal = /*@__PURE__*/ new Vector3();
  23140. const _triangle = /*@__PURE__*/ new Triangle();
  23141. /**
  23142. * Can be used as a helper object to view the edges of a geometry.
  23143. *
  23144. * ```js
  23145. * const geometry = new THREE.BoxGeometry();
  23146. * const edges = new THREE.EdgesGeometry( geometry );
  23147. * const line = new THREE.LineSegments( edges );
  23148. * scene.add( line );
  23149. * ```
  23150. *
  23151. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23152. *
  23153. * @augments BufferGeometry
  23154. */
  23155. class EdgesGeometry extends BufferGeometry {
  23156. /**
  23157. * Constructs a new edges geometry.
  23158. *
  23159. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23160. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23161. * between the face normals of the adjoining faces exceeds this value.
  23162. */
  23163. constructor( geometry = null, thresholdAngle = 1 ) {
  23164. super();
  23165. this.type = 'EdgesGeometry';
  23166. /**
  23167. * Holds the constructor parameters that have been
  23168. * used to generate the geometry. Any modification
  23169. * after instantiation does not change the geometry.
  23170. *
  23171. * @type {Object}
  23172. */
  23173. this.parameters = {
  23174. geometry: geometry,
  23175. thresholdAngle: thresholdAngle
  23176. };
  23177. if ( geometry !== null ) {
  23178. const precisionPoints = 4;
  23179. const precision = Math.pow( 10, precisionPoints );
  23180. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23181. const indexAttr = geometry.getIndex();
  23182. const positionAttr = geometry.getAttribute( 'position' );
  23183. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23184. const indexArr = [ 0, 0, 0 ];
  23185. const vertKeys = [ 'a', 'b', 'c' ];
  23186. const hashes = new Array( 3 );
  23187. const edgeData = {};
  23188. const vertices = [];
  23189. for ( let i = 0; i < indexCount; i += 3 ) {
  23190. if ( indexAttr ) {
  23191. indexArr[ 0 ] = indexAttr.getX( i );
  23192. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23193. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23194. } else {
  23195. indexArr[ 0 ] = i;
  23196. indexArr[ 1 ] = i + 1;
  23197. indexArr[ 2 ] = i + 2;
  23198. }
  23199. const { a, b, c } = _triangle;
  23200. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23201. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23202. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23203. _triangle.getNormal( _normal );
  23204. // create hashes for the edge from the vertices
  23205. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23206. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23207. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23208. // skip degenerate triangles
  23209. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23210. continue;
  23211. }
  23212. // iterate over every edge
  23213. for ( let j = 0; j < 3; j ++ ) {
  23214. // get the first and next vertex making up the edge
  23215. const jNext = ( j + 1 ) % 3;
  23216. const vecHash0 = hashes[ j ];
  23217. const vecHash1 = hashes[ jNext ];
  23218. const v0 = _triangle[ vertKeys[ j ] ];
  23219. const v1 = _triangle[ vertKeys[ jNext ] ];
  23220. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23221. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23222. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23223. // if we found a sibling edge add it into the vertex array if
  23224. // it meets the angle threshold and delete the edge from the map.
  23225. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23226. vertices.push( v0.x, v0.y, v0.z );
  23227. vertices.push( v1.x, v1.y, v1.z );
  23228. }
  23229. edgeData[ reverseHash ] = null;
  23230. } else if ( ! ( hash in edgeData ) ) {
  23231. // if we've already got an edge here then skip adding a new one
  23232. edgeData[ hash ] = {
  23233. index0: indexArr[ j ],
  23234. index1: indexArr[ jNext ],
  23235. normal: _normal.clone(),
  23236. };
  23237. }
  23238. }
  23239. }
  23240. // iterate over all remaining, unmatched edges and add them to the vertex array
  23241. for ( const key in edgeData ) {
  23242. if ( edgeData[ key ] ) {
  23243. const { index0, index1 } = edgeData[ key ];
  23244. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23245. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23246. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23247. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23248. }
  23249. }
  23250. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23251. }
  23252. }
  23253. copy( source ) {
  23254. super.copy( source );
  23255. this.parameters = Object.assign( {}, source.parameters );
  23256. return this;
  23257. }
  23258. }
  23259. /**
  23260. * An abstract base class for creating an analytic curve object that contains methods
  23261. * for interpolation.
  23262. *
  23263. * @abstract
  23264. */
  23265. class Curve {
  23266. /**
  23267. * Constructs a new curve.
  23268. */
  23269. constructor() {
  23270. /**
  23271. * The type property is used for detecting the object type
  23272. * in context of serialization/deserialization.
  23273. *
  23274. * @type {string}
  23275. * @readonly
  23276. */
  23277. this.type = 'Curve';
  23278. /**
  23279. * This value determines the amount of divisions when calculating the
  23280. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23281. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23282. * recommended to increase the value of this property if the curve is very large.
  23283. *
  23284. * @type {number}
  23285. * @default 200
  23286. */
  23287. this.arcLengthDivisions = 200;
  23288. /**
  23289. * Must be set to `true` if the curve parameters have changed.
  23290. *
  23291. * @type {boolean}
  23292. * @default false
  23293. */
  23294. this.needsUpdate = false;
  23295. /**
  23296. * An internal cache that holds precomputed curve length values.
  23297. *
  23298. * @private
  23299. * @type {?Array<number>}
  23300. * @default null
  23301. */
  23302. this.cacheArcLengths = null;
  23303. }
  23304. /**
  23305. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23306. * for the given interpolation factor.
  23307. *
  23308. * @abstract
  23309. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23310. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23311. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23312. */
  23313. getPoint( /* t, optionalTarget */ ) {
  23314. warn( 'Curve: .getPoint() not implemented.' );
  23315. }
  23316. /**
  23317. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23318. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23319. * of the curve which equidistant samples.
  23320. *
  23321. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23322. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23323. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23324. */
  23325. getPointAt( u, optionalTarget ) {
  23326. const t = this.getUtoTmapping( u );
  23327. return this.getPoint( t, optionalTarget );
  23328. }
  23329. /**
  23330. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23331. * the curve shape.
  23332. *
  23333. * @param {number} [divisions=5] - The number of divisions.
  23334. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23335. */
  23336. getPoints( divisions = 5 ) {
  23337. const points = [];
  23338. for ( let d = 0; d <= divisions; d ++ ) {
  23339. points.push( this.getPoint( d / divisions ) );
  23340. }
  23341. return points;
  23342. }
  23343. // Get sequence of points using getPointAt( u )
  23344. /**
  23345. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23346. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23347. * curve.
  23348. *
  23349. * @param {number} [divisions=5] - The number of divisions.
  23350. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23351. */
  23352. getSpacedPoints( divisions = 5 ) {
  23353. const points = [];
  23354. for ( let d = 0; d <= divisions; d ++ ) {
  23355. points.push( this.getPointAt( d / divisions ) );
  23356. }
  23357. return points;
  23358. }
  23359. /**
  23360. * Returns the total arc length of the curve.
  23361. *
  23362. * @return {number} The length of the curve.
  23363. */
  23364. getLength() {
  23365. const lengths = this.getLengths();
  23366. return lengths[ lengths.length - 1 ];
  23367. }
  23368. /**
  23369. * Returns an array of cumulative segment lengths of the curve.
  23370. *
  23371. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23372. * @return {Array<number>} An array holding the cumulative segment lengths.
  23373. */
  23374. getLengths( divisions = this.arcLengthDivisions ) {
  23375. if ( this.cacheArcLengths &&
  23376. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23377. ! this.needsUpdate ) {
  23378. return this.cacheArcLengths;
  23379. }
  23380. this.needsUpdate = false;
  23381. const cache = [];
  23382. let current, last = this.getPoint( 0 );
  23383. let sum = 0;
  23384. cache.push( 0 );
  23385. for ( let p = 1; p <= divisions; p ++ ) {
  23386. current = this.getPoint( p / divisions );
  23387. sum += current.distanceTo( last );
  23388. cache.push( sum );
  23389. last = current;
  23390. }
  23391. this.cacheArcLengths = cache;
  23392. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23393. }
  23394. /**
  23395. * Update the cumulative segment distance cache. The method must be called
  23396. * every time curve parameters are changed. If an updated curve is part of a
  23397. * composed curve like {@link CurvePath}, this method must be called on the
  23398. * composed curve, too.
  23399. */
  23400. updateArcLengths() {
  23401. this.needsUpdate = true;
  23402. this.getLengths();
  23403. }
  23404. /**
  23405. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23406. * interpolation factor in the same range that can be ued to sample equidistant points
  23407. * from a curve.
  23408. *
  23409. * @param {number} u - The interpolation factor.
  23410. * @param {?number} distance - An optional distance on the curve.
  23411. * @return {number} The updated interpolation factor.
  23412. */
  23413. getUtoTmapping( u, distance = null ) {
  23414. const arcLengths = this.getLengths();
  23415. let i = 0;
  23416. const il = arcLengths.length;
  23417. let targetArcLength; // The targeted u distance value to get
  23418. if ( distance ) {
  23419. targetArcLength = distance;
  23420. } else {
  23421. targetArcLength = u * arcLengths[ il - 1 ];
  23422. }
  23423. // binary search for the index with largest value smaller than target u distance
  23424. let low = 0, high = il - 1, comparison;
  23425. while ( low <= high ) {
  23426. 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
  23427. comparison = arcLengths[ i ] - targetArcLength;
  23428. if ( comparison < 0 ) {
  23429. low = i + 1;
  23430. } else if ( comparison > 0 ) {
  23431. high = i - 1;
  23432. } else {
  23433. high = i;
  23434. break;
  23435. // DONE
  23436. }
  23437. }
  23438. i = high;
  23439. if ( arcLengths[ i ] === targetArcLength ) {
  23440. return i / ( il - 1 );
  23441. }
  23442. // we could get finer grain at lengths, or use simple interpolation between two points
  23443. const lengthBefore = arcLengths[ i ];
  23444. const lengthAfter = arcLengths[ i + 1 ];
  23445. const segmentLength = lengthAfter - lengthBefore;
  23446. // determine where we are between the 'before' and 'after' points
  23447. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23448. // add that fractional amount to t
  23449. const t = ( i + segmentFraction ) / ( il - 1 );
  23450. return t;
  23451. }
  23452. /**
  23453. * Returns a unit vector tangent for the given interpolation factor.
  23454. * If the derived curve does not implement its tangent derivation,
  23455. * two points a small delta apart will be used to find its gradient
  23456. * which seems to give a reasonable approximation.
  23457. *
  23458. * @param {number} t - The interpolation factor.
  23459. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23460. * @return {(Vector2|Vector3)} The tangent vector.
  23461. */
  23462. getTangent( t, optionalTarget ) {
  23463. const delta = 0.0001;
  23464. let t1 = t - delta;
  23465. let t2 = t + delta;
  23466. // Capping in case of danger
  23467. if ( t1 < 0 ) t1 = 0;
  23468. if ( t2 > 1 ) t2 = 1;
  23469. const pt1 = this.getPoint( t1 );
  23470. const pt2 = this.getPoint( t2 );
  23471. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23472. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23473. return tangent;
  23474. }
  23475. /**
  23476. * Same as {@link Curve#getTangent} but with equidistant samples.
  23477. *
  23478. * @param {number} u - The interpolation factor.
  23479. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23480. * @return {(Vector2|Vector3)} The tangent vector.
  23481. * @see {@link Curve#getPointAt}
  23482. */
  23483. getTangentAt( u, optionalTarget ) {
  23484. const t = this.getUtoTmapping( u );
  23485. return this.getTangent( t, optionalTarget );
  23486. }
  23487. /**
  23488. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23489. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23490. *
  23491. * @param {number} segments - The number of segments.
  23492. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23493. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23494. */
  23495. computeFrenetFrames( segments, closed = false ) {
  23496. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23497. const normal = new Vector3();
  23498. const tangents = [];
  23499. const normals = [];
  23500. const binormals = [];
  23501. const vec = new Vector3();
  23502. const mat = new Matrix4();
  23503. // compute the tangent vectors for each segment on the curve
  23504. for ( let i = 0; i <= segments; i ++ ) {
  23505. const u = i / segments;
  23506. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23507. }
  23508. // select an initial normal vector perpendicular to the first tangent vector,
  23509. // and in the direction of the minimum tangent xyz component
  23510. normals[ 0 ] = new Vector3();
  23511. binormals[ 0 ] = new Vector3();
  23512. let min = Number.MAX_VALUE;
  23513. const tx = Math.abs( tangents[ 0 ].x );
  23514. const ty = Math.abs( tangents[ 0 ].y );
  23515. const tz = Math.abs( tangents[ 0 ].z );
  23516. if ( tx <= min ) {
  23517. min = tx;
  23518. normal.set( 1, 0, 0 );
  23519. }
  23520. if ( ty <= min ) {
  23521. min = ty;
  23522. normal.set( 0, 1, 0 );
  23523. }
  23524. if ( tz <= min ) {
  23525. normal.set( 0, 0, 1 );
  23526. }
  23527. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23528. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23529. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23530. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23531. for ( let i = 1; i <= segments; i ++ ) {
  23532. normals[ i ] = normals[ i - 1 ].clone();
  23533. binormals[ i ] = binormals[ i - 1 ].clone();
  23534. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23535. if ( vec.length() > Number.EPSILON ) {
  23536. vec.normalize();
  23537. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23538. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23539. }
  23540. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23541. }
  23542. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23543. if ( closed === true ) {
  23544. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23545. theta /= segments;
  23546. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23547. theta = - theta;
  23548. }
  23549. for ( let i = 1; i <= segments; i ++ ) {
  23550. // twist a little...
  23551. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23552. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23553. }
  23554. }
  23555. return {
  23556. tangents: tangents,
  23557. normals: normals,
  23558. binormals: binormals
  23559. };
  23560. }
  23561. /**
  23562. * Returns a new curve with copied values from this instance.
  23563. *
  23564. * @return {Curve} A clone of this instance.
  23565. */
  23566. clone() {
  23567. return new this.constructor().copy( this );
  23568. }
  23569. /**
  23570. * Copies the values of the given curve to this instance.
  23571. *
  23572. * @param {Curve} source - The curve to copy.
  23573. * @return {Curve} A reference to this curve.
  23574. */
  23575. copy( source ) {
  23576. this.arcLengthDivisions = source.arcLengthDivisions;
  23577. return this;
  23578. }
  23579. /**
  23580. * Serializes the curve into JSON.
  23581. *
  23582. * @return {Object} A JSON object representing the serialized curve.
  23583. * @see {@link ObjectLoader#parse}
  23584. */
  23585. toJSON() {
  23586. const data = {
  23587. metadata: {
  23588. version: 4.7,
  23589. type: 'Curve',
  23590. generator: 'Curve.toJSON'
  23591. }
  23592. };
  23593. data.arcLengthDivisions = this.arcLengthDivisions;
  23594. data.type = this.type;
  23595. return data;
  23596. }
  23597. /**
  23598. * Deserializes the curve from the given JSON.
  23599. *
  23600. * @param {Object} json - The JSON holding the serialized curve.
  23601. * @return {Curve} A reference to this curve.
  23602. */
  23603. fromJSON( json ) {
  23604. this.arcLengthDivisions = json.arcLengthDivisions;
  23605. return this;
  23606. }
  23607. }
  23608. /**
  23609. * A curve representing an ellipse.
  23610. *
  23611. * ```js
  23612. * const curve = new THREE.EllipseCurve(
  23613. * 0, 0,
  23614. * 10, 10,
  23615. * 0, 2 * Math.PI,
  23616. * false,
  23617. * 0
  23618. * );
  23619. *
  23620. * const points = curve.getPoints( 50 );
  23621. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23622. *
  23623. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23624. *
  23625. * // Create the final object to add to the scene
  23626. * const ellipse = new THREE.Line( geometry, material );
  23627. * ```
  23628. *
  23629. * @augments Curve
  23630. */
  23631. class EllipseCurve extends Curve {
  23632. /**
  23633. * Constructs a new ellipse curve.
  23634. *
  23635. * @param {number} [aX=0] - The X center of the ellipse.
  23636. * @param {number} [aY=0] - The Y center of the ellipse.
  23637. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23638. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23639. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23640. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23641. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23642. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23643. */
  23644. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23645. super();
  23646. /**
  23647. * This flag can be used for type testing.
  23648. *
  23649. * @type {boolean}
  23650. * @readonly
  23651. * @default true
  23652. */
  23653. this.isEllipseCurve = true;
  23654. this.type = 'EllipseCurve';
  23655. /**
  23656. * The X center of the ellipse.
  23657. *
  23658. * @type {number}
  23659. * @default 0
  23660. */
  23661. this.aX = aX;
  23662. /**
  23663. * The Y center of the ellipse.
  23664. *
  23665. * @type {number}
  23666. * @default 0
  23667. */
  23668. this.aY = aY;
  23669. /**
  23670. * The radius of the ellipse in the x direction.
  23671. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23672. *
  23673. * @type {number}
  23674. * @default 1
  23675. */
  23676. this.xRadius = xRadius;
  23677. /**
  23678. * The radius of the ellipse in the y direction.
  23679. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23680. *
  23681. * @type {number}
  23682. * @default 1
  23683. */
  23684. this.yRadius = yRadius;
  23685. /**
  23686. * The start angle of the curve in radians starting from the positive X axis.
  23687. *
  23688. * @type {number}
  23689. * @default 0
  23690. */
  23691. this.aStartAngle = aStartAngle;
  23692. /**
  23693. * The end angle of the curve in radians starting from the positive X axis.
  23694. *
  23695. * @type {number}
  23696. * @default Math.PI*2
  23697. */
  23698. this.aEndAngle = aEndAngle;
  23699. /**
  23700. * Whether the ellipse is drawn clockwise or not.
  23701. *
  23702. * @type {boolean}
  23703. * @default false
  23704. */
  23705. this.aClockwise = aClockwise;
  23706. /**
  23707. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23708. *
  23709. * @type {number}
  23710. * @default 0
  23711. */
  23712. this.aRotation = aRotation;
  23713. }
  23714. /**
  23715. * Returns a point on the curve.
  23716. *
  23717. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23718. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23719. * @return {Vector2} The position on the curve.
  23720. */
  23721. getPoint( t, optionalTarget = new Vector2() ) {
  23722. const point = optionalTarget;
  23723. const twoPi = Math.PI * 2;
  23724. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23725. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23726. // ensures that deltaAngle is 0 .. 2 PI
  23727. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23728. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23729. if ( deltaAngle < Number.EPSILON ) {
  23730. if ( samePoints ) {
  23731. deltaAngle = 0;
  23732. } else {
  23733. deltaAngle = twoPi;
  23734. }
  23735. }
  23736. if ( this.aClockwise === true && ! samePoints ) {
  23737. if ( deltaAngle === twoPi ) {
  23738. deltaAngle = - twoPi;
  23739. } else {
  23740. deltaAngle = deltaAngle - twoPi;
  23741. }
  23742. }
  23743. const angle = this.aStartAngle + t * deltaAngle;
  23744. let x = this.aX + this.xRadius * Math.cos( angle );
  23745. let y = this.aY + this.yRadius * Math.sin( angle );
  23746. if ( this.aRotation !== 0 ) {
  23747. const cos = Math.cos( this.aRotation );
  23748. const sin = Math.sin( this.aRotation );
  23749. const tx = x - this.aX;
  23750. const ty = y - this.aY;
  23751. // Rotate the point about the center of the ellipse.
  23752. x = tx * cos - ty * sin + this.aX;
  23753. y = tx * sin + ty * cos + this.aY;
  23754. }
  23755. return point.set( x, y );
  23756. }
  23757. copy( source ) {
  23758. super.copy( source );
  23759. this.aX = source.aX;
  23760. this.aY = source.aY;
  23761. this.xRadius = source.xRadius;
  23762. this.yRadius = source.yRadius;
  23763. this.aStartAngle = source.aStartAngle;
  23764. this.aEndAngle = source.aEndAngle;
  23765. this.aClockwise = source.aClockwise;
  23766. this.aRotation = source.aRotation;
  23767. return this;
  23768. }
  23769. toJSON() {
  23770. const data = super.toJSON();
  23771. data.aX = this.aX;
  23772. data.aY = this.aY;
  23773. data.xRadius = this.xRadius;
  23774. data.yRadius = this.yRadius;
  23775. data.aStartAngle = this.aStartAngle;
  23776. data.aEndAngle = this.aEndAngle;
  23777. data.aClockwise = this.aClockwise;
  23778. data.aRotation = this.aRotation;
  23779. return data;
  23780. }
  23781. fromJSON( json ) {
  23782. super.fromJSON( json );
  23783. this.aX = json.aX;
  23784. this.aY = json.aY;
  23785. this.xRadius = json.xRadius;
  23786. this.yRadius = json.yRadius;
  23787. this.aStartAngle = json.aStartAngle;
  23788. this.aEndAngle = json.aEndAngle;
  23789. this.aClockwise = json.aClockwise;
  23790. this.aRotation = json.aRotation;
  23791. return this;
  23792. }
  23793. }
  23794. /**
  23795. * A curve representing an arc.
  23796. *
  23797. * @augments EllipseCurve
  23798. */
  23799. class ArcCurve extends EllipseCurve {
  23800. /**
  23801. * Constructs a new arc curve.
  23802. *
  23803. * @param {number} [aX=0] - The X center of the ellipse.
  23804. * @param {number} [aY=0] - The Y center of the ellipse.
  23805. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23806. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23807. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23808. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23809. */
  23810. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23811. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23812. /**
  23813. * This flag can be used for type testing.
  23814. *
  23815. * @type {boolean}
  23816. * @readonly
  23817. * @default true
  23818. */
  23819. this.isArcCurve = true;
  23820. this.type = 'ArcCurve';
  23821. }
  23822. }
  23823. function CubicPoly() {
  23824. /**
  23825. * Centripetal CatmullRom Curve - which is useful for avoiding
  23826. * cusps and self-intersections in non-uniform catmull rom curves.
  23827. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23828. *
  23829. * curve.type accepts centripetal(default), chordal and catmullrom
  23830. * curve.tension is used for catmullrom which defaults to 0.5
  23831. */
  23832. /*
  23833. Based on an optimized c++ solution in
  23834. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23835. - http://ideone.com/NoEbVM
  23836. This CubicPoly class could be used for reusing some variables and calculations,
  23837. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23838. which can be placed in CurveUtils.
  23839. */
  23840. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23841. /*
  23842. * Compute coefficients for a cubic polynomial
  23843. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23844. * such that
  23845. * p(0) = x0, p(1) = x1
  23846. * and
  23847. * p'(0) = t0, p'(1) = t1.
  23848. */
  23849. function init( x0, x1, t0, t1 ) {
  23850. c0 = x0;
  23851. c1 = t0;
  23852. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23853. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23854. }
  23855. return {
  23856. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23857. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23858. },
  23859. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23860. // compute tangents when parameterized in [t1,t2]
  23861. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23862. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23863. // rescale tangents for parametrization in [0,1]
  23864. t1 *= dt1;
  23865. t2 *= dt1;
  23866. init( x1, x2, t1, t2 );
  23867. },
  23868. calc: function ( t ) {
  23869. const t2 = t * t;
  23870. const t3 = t2 * t;
  23871. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23872. }
  23873. };
  23874. }
  23875. //
  23876. const tmp = /*@__PURE__*/ new Vector3();
  23877. const px = /*@__PURE__*/ new CubicPoly();
  23878. const py = /*@__PURE__*/ new CubicPoly();
  23879. const pz = /*@__PURE__*/ new CubicPoly();
  23880. /**
  23881. * A curve representing a Catmull-Rom spline.
  23882. *
  23883. * ```js
  23884. * //Create a closed wavey loop
  23885. * const curve = new THREE.CatmullRomCurve3( [
  23886. * new THREE.Vector3( -10, 0, 10 ),
  23887. * new THREE.Vector3( -5, 5, 5 ),
  23888. * new THREE.Vector3( 0, 0, 0 ),
  23889. * new THREE.Vector3( 5, -5, 5 ),
  23890. * new THREE.Vector3( 10, 0, 10 )
  23891. * ] );
  23892. *
  23893. * const points = curve.getPoints( 50 );
  23894. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23895. *
  23896. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23897. *
  23898. * // Create the final object to add to the scene
  23899. * const curveObject = new THREE.Line( geometry, material );
  23900. * ```
  23901. *
  23902. * @augments Curve
  23903. */
  23904. class CatmullRomCurve3 extends Curve {
  23905. /**
  23906. * Constructs a new Catmull-Rom curve.
  23907. *
  23908. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23909. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23910. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23911. * @param {number} [tension=0.5] - Tension of the curve.
  23912. */
  23913. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23914. super();
  23915. /**
  23916. * This flag can be used for type testing.
  23917. *
  23918. * @type {boolean}
  23919. * @readonly
  23920. * @default true
  23921. */
  23922. this.isCatmullRomCurve3 = true;
  23923. this.type = 'CatmullRomCurve3';
  23924. /**
  23925. * An array of 3D points defining the curve.
  23926. *
  23927. * @type {Array<Vector3>}
  23928. */
  23929. this.points = points;
  23930. /**
  23931. * Whether the curve is closed or not.
  23932. *
  23933. * @type {boolean}
  23934. * @default false
  23935. */
  23936. this.closed = closed;
  23937. /**
  23938. * The curve type.
  23939. *
  23940. * @type {('centripetal'|'chordal'|'catmullrom')}
  23941. * @default 'centripetal'
  23942. */
  23943. this.curveType = curveType;
  23944. /**
  23945. * Tension of the curve.
  23946. *
  23947. * @type {number}
  23948. * @default 0.5
  23949. */
  23950. this.tension = tension;
  23951. }
  23952. /**
  23953. * Returns a point on the curve.
  23954. *
  23955. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23956. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23957. * @return {Vector3} The position on the curve.
  23958. */
  23959. getPoint( t, optionalTarget = new Vector3() ) {
  23960. const point = optionalTarget;
  23961. const points = this.points;
  23962. const l = points.length;
  23963. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23964. let intPoint = Math.floor( p );
  23965. let weight = p - intPoint;
  23966. if ( this.closed ) {
  23967. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23968. } else if ( weight === 0 && intPoint === l - 1 ) {
  23969. intPoint = l - 2;
  23970. weight = 1;
  23971. }
  23972. let p0, p3; // 4 points (p1 & p2 defined below)
  23973. if ( this.closed || intPoint > 0 ) {
  23974. p0 = points[ ( intPoint - 1 ) % l ];
  23975. } else {
  23976. // extrapolate first point
  23977. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23978. p0 = tmp;
  23979. }
  23980. const p1 = points[ intPoint % l ];
  23981. const p2 = points[ ( intPoint + 1 ) % l ];
  23982. if ( this.closed || intPoint + 2 < l ) {
  23983. p3 = points[ ( intPoint + 2 ) % l ];
  23984. } else {
  23985. // extrapolate last point
  23986. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23987. p3 = tmp;
  23988. }
  23989. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23990. // init Centripetal / Chordal Catmull-Rom
  23991. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23992. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23993. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23994. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23995. // safety check for repeated points
  23996. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23997. if ( dt0 < 1e-4 ) dt0 = dt1;
  23998. if ( dt2 < 1e-4 ) dt2 = dt1;
  23999. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  24000. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  24001. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  24002. } else if ( this.curveType === 'catmullrom' ) {
  24003. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  24004. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  24005. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  24006. }
  24007. point.set(
  24008. px.calc( weight ),
  24009. py.calc( weight ),
  24010. pz.calc( weight )
  24011. );
  24012. return point;
  24013. }
  24014. copy( source ) {
  24015. super.copy( source );
  24016. this.points = [];
  24017. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24018. const point = source.points[ i ];
  24019. this.points.push( point.clone() );
  24020. }
  24021. this.closed = source.closed;
  24022. this.curveType = source.curveType;
  24023. this.tension = source.tension;
  24024. return this;
  24025. }
  24026. toJSON() {
  24027. const data = super.toJSON();
  24028. data.points = [];
  24029. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24030. const point = this.points[ i ];
  24031. data.points.push( point.toArray() );
  24032. }
  24033. data.closed = this.closed;
  24034. data.curveType = this.curveType;
  24035. data.tension = this.tension;
  24036. return data;
  24037. }
  24038. fromJSON( json ) {
  24039. super.fromJSON( json );
  24040. this.points = [];
  24041. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24042. const point = json.points[ i ];
  24043. this.points.push( new Vector3().fromArray( point ) );
  24044. }
  24045. this.closed = json.closed;
  24046. this.curveType = json.curveType;
  24047. this.tension = json.tension;
  24048. return this;
  24049. }
  24050. }
  24051. /**
  24052. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24053. *
  24054. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24055. *
  24056. * @module Interpolations
  24057. */
  24058. /**
  24059. * Computes a point on a Catmull-Rom spline.
  24060. *
  24061. * @param {number} t - The interpolation factor.
  24062. * @param {number} p0 - The first control point.
  24063. * @param {number} p1 - The second control point.
  24064. * @param {number} p2 - The third control point.
  24065. * @param {number} p3 - The fourth control point.
  24066. * @return {number} The calculated point on a Catmull-Rom spline.
  24067. */
  24068. function CatmullRom( t, p0, p1, p2, p3 ) {
  24069. const v0 = ( p2 - p0 ) * 0.5;
  24070. const v1 = ( p3 - p1 ) * 0.5;
  24071. const t2 = t * t;
  24072. const t3 = t * t2;
  24073. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24074. }
  24075. //
  24076. function QuadraticBezierP0( t, p ) {
  24077. const k = 1 - t;
  24078. return k * k * p;
  24079. }
  24080. function QuadraticBezierP1( t, p ) {
  24081. return 2 * ( 1 - t ) * t * p;
  24082. }
  24083. function QuadraticBezierP2( t, p ) {
  24084. return t * t * p;
  24085. }
  24086. /**
  24087. * Computes a point on a Quadratic Bezier curve.
  24088. *
  24089. * @param {number} t - The interpolation factor.
  24090. * @param {number} p0 - The first control point.
  24091. * @param {number} p1 - The second control point.
  24092. * @param {number} p2 - The third control point.
  24093. * @return {number} The calculated point on a Quadratic Bezier curve.
  24094. */
  24095. function QuadraticBezier( t, p0, p1, p2 ) {
  24096. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24097. QuadraticBezierP2( t, p2 );
  24098. }
  24099. //
  24100. function CubicBezierP0( t, p ) {
  24101. const k = 1 - t;
  24102. return k * k * k * p;
  24103. }
  24104. function CubicBezierP1( t, p ) {
  24105. const k = 1 - t;
  24106. return 3 * k * k * t * p;
  24107. }
  24108. function CubicBezierP2( t, p ) {
  24109. return 3 * ( 1 - t ) * t * t * p;
  24110. }
  24111. function CubicBezierP3( t, p ) {
  24112. return t * t * t * p;
  24113. }
  24114. /**
  24115. * Computes a point on a Cubic Bezier curve.
  24116. *
  24117. * @param {number} t - The interpolation factor.
  24118. * @param {number} p0 - The first control point.
  24119. * @param {number} p1 - The second control point.
  24120. * @param {number} p2 - The third control point.
  24121. * @param {number} p3 - The fourth control point.
  24122. * @return {number} The calculated point on a Cubic Bezier curve.
  24123. */
  24124. function CubicBezier( t, p0, p1, p2, p3 ) {
  24125. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24126. CubicBezierP3( t, p3 );
  24127. }
  24128. /**
  24129. * A curve representing a 2D Cubic Bezier curve.
  24130. *
  24131. * ```js
  24132. * const curve = new THREE.CubicBezierCurve(
  24133. * new THREE.Vector2( - 0, 0 ),
  24134. * new THREE.Vector2( - 5, 15 ),
  24135. * new THREE.Vector2( 20, 15 ),
  24136. * new THREE.Vector2( 10, 0 )
  24137. * );
  24138. *
  24139. * const points = curve.getPoints( 50 );
  24140. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24141. *
  24142. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24143. *
  24144. * // Create the final object to add to the scene
  24145. * const curveObject = new THREE.Line( geometry, material );
  24146. * ```
  24147. *
  24148. * @augments Curve
  24149. */
  24150. class CubicBezierCurve extends Curve {
  24151. /**
  24152. * Constructs a new Cubic Bezier curve.
  24153. *
  24154. * @param {Vector2} [v0] - The start point.
  24155. * @param {Vector2} [v1] - The first control point.
  24156. * @param {Vector2} [v2] - The second control point.
  24157. * @param {Vector2} [v3] - The end point.
  24158. */
  24159. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24160. super();
  24161. /**
  24162. * This flag can be used for type testing.
  24163. *
  24164. * @type {boolean}
  24165. * @readonly
  24166. * @default true
  24167. */
  24168. this.isCubicBezierCurve = true;
  24169. this.type = 'CubicBezierCurve';
  24170. /**
  24171. * The start point.
  24172. *
  24173. * @type {Vector2}
  24174. */
  24175. this.v0 = v0;
  24176. /**
  24177. * The first control point.
  24178. *
  24179. * @type {Vector2}
  24180. */
  24181. this.v1 = v1;
  24182. /**
  24183. * The second control point.
  24184. *
  24185. * @type {Vector2}
  24186. */
  24187. this.v2 = v2;
  24188. /**
  24189. * The end point.
  24190. *
  24191. * @type {Vector2}
  24192. */
  24193. this.v3 = v3;
  24194. }
  24195. /**
  24196. * Returns a point on the curve.
  24197. *
  24198. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24199. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24200. * @return {Vector2} The position on the curve.
  24201. */
  24202. getPoint( t, optionalTarget = new Vector2() ) {
  24203. const point = optionalTarget;
  24204. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24205. point.set(
  24206. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24207. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24208. );
  24209. return point;
  24210. }
  24211. copy( source ) {
  24212. super.copy( source );
  24213. this.v0.copy( source.v0 );
  24214. this.v1.copy( source.v1 );
  24215. this.v2.copy( source.v2 );
  24216. this.v3.copy( source.v3 );
  24217. return this;
  24218. }
  24219. toJSON() {
  24220. const data = super.toJSON();
  24221. data.v0 = this.v0.toArray();
  24222. data.v1 = this.v1.toArray();
  24223. data.v2 = this.v2.toArray();
  24224. data.v3 = this.v3.toArray();
  24225. return data;
  24226. }
  24227. fromJSON( json ) {
  24228. super.fromJSON( json );
  24229. this.v0.fromArray( json.v0 );
  24230. this.v1.fromArray( json.v1 );
  24231. this.v2.fromArray( json.v2 );
  24232. this.v3.fromArray( json.v3 );
  24233. return this;
  24234. }
  24235. }
  24236. /**
  24237. * A curve representing a 3D Cubic Bezier curve.
  24238. *
  24239. * @augments Curve
  24240. */
  24241. class CubicBezierCurve3 extends Curve {
  24242. /**
  24243. * Constructs a new Cubic Bezier curve.
  24244. *
  24245. * @param {Vector3} [v0] - The start point.
  24246. * @param {Vector3} [v1] - The first control point.
  24247. * @param {Vector3} [v2] - The second control point.
  24248. * @param {Vector3} [v3] - The end point.
  24249. */
  24250. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24251. super();
  24252. /**
  24253. * This flag can be used for type testing.
  24254. *
  24255. * @type {boolean}
  24256. * @readonly
  24257. * @default true
  24258. */
  24259. this.isCubicBezierCurve3 = true;
  24260. this.type = 'CubicBezierCurve3';
  24261. /**
  24262. * The start point.
  24263. *
  24264. * @type {Vector3}
  24265. */
  24266. this.v0 = v0;
  24267. /**
  24268. * The first control point.
  24269. *
  24270. * @type {Vector3}
  24271. */
  24272. this.v1 = v1;
  24273. /**
  24274. * The second control point.
  24275. *
  24276. * @type {Vector3}
  24277. */
  24278. this.v2 = v2;
  24279. /**
  24280. * The end point.
  24281. *
  24282. * @type {Vector3}
  24283. */
  24284. this.v3 = v3;
  24285. }
  24286. /**
  24287. * Returns a point on the curve.
  24288. *
  24289. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24290. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24291. * @return {Vector3} The position on the curve.
  24292. */
  24293. getPoint( t, optionalTarget = new Vector3() ) {
  24294. const point = optionalTarget;
  24295. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24296. point.set(
  24297. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24298. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24299. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24300. );
  24301. return point;
  24302. }
  24303. copy( source ) {
  24304. super.copy( source );
  24305. this.v0.copy( source.v0 );
  24306. this.v1.copy( source.v1 );
  24307. this.v2.copy( source.v2 );
  24308. this.v3.copy( source.v3 );
  24309. return this;
  24310. }
  24311. toJSON() {
  24312. const data = super.toJSON();
  24313. data.v0 = this.v0.toArray();
  24314. data.v1 = this.v1.toArray();
  24315. data.v2 = this.v2.toArray();
  24316. data.v3 = this.v3.toArray();
  24317. return data;
  24318. }
  24319. fromJSON( json ) {
  24320. super.fromJSON( json );
  24321. this.v0.fromArray( json.v0 );
  24322. this.v1.fromArray( json.v1 );
  24323. this.v2.fromArray( json.v2 );
  24324. this.v3.fromArray( json.v3 );
  24325. return this;
  24326. }
  24327. }
  24328. /**
  24329. * A curve representing a 2D line segment.
  24330. *
  24331. * @augments Curve
  24332. */
  24333. class LineCurve extends Curve {
  24334. /**
  24335. * Constructs a new line curve.
  24336. *
  24337. * @param {Vector2} [v1] - The start point.
  24338. * @param {Vector2} [v2] - The end point.
  24339. */
  24340. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24341. super();
  24342. /**
  24343. * This flag can be used for type testing.
  24344. *
  24345. * @type {boolean}
  24346. * @readonly
  24347. * @default true
  24348. */
  24349. this.isLineCurve = true;
  24350. this.type = 'LineCurve';
  24351. /**
  24352. * The start point.
  24353. *
  24354. * @type {Vector2}
  24355. */
  24356. this.v1 = v1;
  24357. /**
  24358. * The end point.
  24359. *
  24360. * @type {Vector2}
  24361. */
  24362. this.v2 = v2;
  24363. }
  24364. /**
  24365. * Returns a point on the line.
  24366. *
  24367. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24368. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24369. * @return {Vector2} The position on the line.
  24370. */
  24371. getPoint( t, optionalTarget = new Vector2() ) {
  24372. const point = optionalTarget;
  24373. if ( t === 1 ) {
  24374. point.copy( this.v2 );
  24375. } else {
  24376. point.copy( this.v2 ).sub( this.v1 );
  24377. point.multiplyScalar( t ).add( this.v1 );
  24378. }
  24379. return point;
  24380. }
  24381. // Line curve is linear, so we can overwrite default getPointAt
  24382. getPointAt( u, optionalTarget ) {
  24383. return this.getPoint( u, optionalTarget );
  24384. }
  24385. getTangent( t, optionalTarget = new Vector2() ) {
  24386. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24387. }
  24388. getTangentAt( u, optionalTarget ) {
  24389. return this.getTangent( u, optionalTarget );
  24390. }
  24391. copy( source ) {
  24392. super.copy( source );
  24393. this.v1.copy( source.v1 );
  24394. this.v2.copy( source.v2 );
  24395. return this;
  24396. }
  24397. toJSON() {
  24398. const data = super.toJSON();
  24399. data.v1 = this.v1.toArray();
  24400. data.v2 = this.v2.toArray();
  24401. return data;
  24402. }
  24403. fromJSON( json ) {
  24404. super.fromJSON( json );
  24405. this.v1.fromArray( json.v1 );
  24406. this.v2.fromArray( json.v2 );
  24407. return this;
  24408. }
  24409. }
  24410. /**
  24411. * A curve representing a 3D line segment.
  24412. *
  24413. * @augments Curve
  24414. */
  24415. class LineCurve3 extends Curve {
  24416. /**
  24417. * Constructs a new line curve.
  24418. *
  24419. * @param {Vector3} [v1] - The start point.
  24420. * @param {Vector3} [v2] - The end point.
  24421. */
  24422. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24423. super();
  24424. /**
  24425. * This flag can be used for type testing.
  24426. *
  24427. * @type {boolean}
  24428. * @readonly
  24429. * @default true
  24430. */
  24431. this.isLineCurve3 = true;
  24432. this.type = 'LineCurve3';
  24433. /**
  24434. * The start point.
  24435. *
  24436. * @type {Vector3}
  24437. */
  24438. this.v1 = v1;
  24439. /**
  24440. * The end point.
  24441. *
  24442. * @type {Vector2}
  24443. */
  24444. this.v2 = v2;
  24445. }
  24446. /**
  24447. * Returns a point on the line.
  24448. *
  24449. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24450. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24451. * @return {Vector3} The position on the line.
  24452. */
  24453. getPoint( t, optionalTarget = new Vector3() ) {
  24454. const point = optionalTarget;
  24455. if ( t === 1 ) {
  24456. point.copy( this.v2 );
  24457. } else {
  24458. point.copy( this.v2 ).sub( this.v1 );
  24459. point.multiplyScalar( t ).add( this.v1 );
  24460. }
  24461. return point;
  24462. }
  24463. // Line curve is linear, so we can overwrite default getPointAt
  24464. getPointAt( u, optionalTarget ) {
  24465. return this.getPoint( u, optionalTarget );
  24466. }
  24467. getTangent( t, optionalTarget = new Vector3() ) {
  24468. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24469. }
  24470. getTangentAt( u, optionalTarget ) {
  24471. return this.getTangent( u, optionalTarget );
  24472. }
  24473. copy( source ) {
  24474. super.copy( source );
  24475. this.v1.copy( source.v1 );
  24476. this.v2.copy( source.v2 );
  24477. return this;
  24478. }
  24479. toJSON() {
  24480. const data = super.toJSON();
  24481. data.v1 = this.v1.toArray();
  24482. data.v2 = this.v2.toArray();
  24483. return data;
  24484. }
  24485. fromJSON( json ) {
  24486. super.fromJSON( json );
  24487. this.v1.fromArray( json.v1 );
  24488. this.v2.fromArray( json.v2 );
  24489. return this;
  24490. }
  24491. }
  24492. /**
  24493. * A curve representing a 2D Quadratic Bezier curve.
  24494. *
  24495. * ```js
  24496. * const curve = new THREE.QuadraticBezierCurve(
  24497. * new THREE.Vector2( - 10, 0 ),
  24498. * new THREE.Vector2( 20, 15 ),
  24499. * new THREE.Vector2( 10, 0 )
  24500. * )
  24501. *
  24502. * const points = curve.getPoints( 50 );
  24503. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24504. *
  24505. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24506. *
  24507. * // Create the final object to add to the scene
  24508. * const curveObject = new THREE.Line( geometry, material );
  24509. * ```
  24510. *
  24511. * @augments Curve
  24512. */
  24513. class QuadraticBezierCurve extends Curve {
  24514. /**
  24515. * Constructs a new Quadratic Bezier curve.
  24516. *
  24517. * @param {Vector2} [v0] - The start point.
  24518. * @param {Vector2} [v1] - The control point.
  24519. * @param {Vector2} [v2] - The end point.
  24520. */
  24521. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24522. super();
  24523. /**
  24524. * This flag can be used for type testing.
  24525. *
  24526. * @type {boolean}
  24527. * @readonly
  24528. * @default true
  24529. */
  24530. this.isQuadraticBezierCurve = true;
  24531. this.type = 'QuadraticBezierCurve';
  24532. /**
  24533. * The start point.
  24534. *
  24535. * @type {Vector2}
  24536. */
  24537. this.v0 = v0;
  24538. /**
  24539. * The control point.
  24540. *
  24541. * @type {Vector2}
  24542. */
  24543. this.v1 = v1;
  24544. /**
  24545. * The end point.
  24546. *
  24547. * @type {Vector2}
  24548. */
  24549. this.v2 = v2;
  24550. }
  24551. /**
  24552. * Returns a point on the curve.
  24553. *
  24554. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24555. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24556. * @return {Vector2} The position on the curve.
  24557. */
  24558. getPoint( t, optionalTarget = new Vector2() ) {
  24559. const point = optionalTarget;
  24560. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24561. point.set(
  24562. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24563. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24564. );
  24565. return point;
  24566. }
  24567. copy( source ) {
  24568. super.copy( source );
  24569. this.v0.copy( source.v0 );
  24570. this.v1.copy( source.v1 );
  24571. this.v2.copy( source.v2 );
  24572. return this;
  24573. }
  24574. toJSON() {
  24575. const data = super.toJSON();
  24576. data.v0 = this.v0.toArray();
  24577. data.v1 = this.v1.toArray();
  24578. data.v2 = this.v2.toArray();
  24579. return data;
  24580. }
  24581. fromJSON( json ) {
  24582. super.fromJSON( json );
  24583. this.v0.fromArray( json.v0 );
  24584. this.v1.fromArray( json.v1 );
  24585. this.v2.fromArray( json.v2 );
  24586. return this;
  24587. }
  24588. }
  24589. /**
  24590. * A curve representing a 3D Quadratic Bezier curve.
  24591. *
  24592. * @augments Curve
  24593. */
  24594. class QuadraticBezierCurve3 extends Curve {
  24595. /**
  24596. * Constructs a new Quadratic Bezier curve.
  24597. *
  24598. * @param {Vector3} [v0] - The start point.
  24599. * @param {Vector3} [v1] - The control point.
  24600. * @param {Vector3} [v2] - The end point.
  24601. */
  24602. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24603. super();
  24604. /**
  24605. * This flag can be used for type testing.
  24606. *
  24607. * @type {boolean}
  24608. * @readonly
  24609. * @default true
  24610. */
  24611. this.isQuadraticBezierCurve3 = true;
  24612. this.type = 'QuadraticBezierCurve3';
  24613. /**
  24614. * The start point.
  24615. *
  24616. * @type {Vector3}
  24617. */
  24618. this.v0 = v0;
  24619. /**
  24620. * The control point.
  24621. *
  24622. * @type {Vector3}
  24623. */
  24624. this.v1 = v1;
  24625. /**
  24626. * The end point.
  24627. *
  24628. * @type {Vector3}
  24629. */
  24630. this.v2 = v2;
  24631. }
  24632. /**
  24633. * Returns a point on the curve.
  24634. *
  24635. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24636. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24637. * @return {Vector3} The position on the curve.
  24638. */
  24639. getPoint( t, optionalTarget = new Vector3() ) {
  24640. const point = optionalTarget;
  24641. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24642. point.set(
  24643. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24644. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24645. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24646. );
  24647. return point;
  24648. }
  24649. copy( source ) {
  24650. super.copy( source );
  24651. this.v0.copy( source.v0 );
  24652. this.v1.copy( source.v1 );
  24653. this.v2.copy( source.v2 );
  24654. return this;
  24655. }
  24656. toJSON() {
  24657. const data = super.toJSON();
  24658. data.v0 = this.v0.toArray();
  24659. data.v1 = this.v1.toArray();
  24660. data.v2 = this.v2.toArray();
  24661. return data;
  24662. }
  24663. fromJSON( json ) {
  24664. super.fromJSON( json );
  24665. this.v0.fromArray( json.v0 );
  24666. this.v1.fromArray( json.v1 );
  24667. this.v2.fromArray( json.v2 );
  24668. return this;
  24669. }
  24670. }
  24671. /**
  24672. * A curve representing a 2D spline curve.
  24673. *
  24674. * ```js
  24675. * // Create a sine-like wave
  24676. * const curve = new THREE.SplineCurve( [
  24677. * new THREE.Vector2( -10, 0 ),
  24678. * new THREE.Vector2( -5, 5 ),
  24679. * new THREE.Vector2( 0, 0 ),
  24680. * new THREE.Vector2( 5, -5 ),
  24681. * new THREE.Vector2( 10, 0 )
  24682. * ] );
  24683. *
  24684. * const points = curve.getPoints( 50 );
  24685. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24686. *
  24687. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24688. *
  24689. * // Create the final object to add to the scene
  24690. * const splineObject = new THREE.Line( geometry, material );
  24691. * ```
  24692. *
  24693. * @augments Curve
  24694. */
  24695. class SplineCurve extends Curve {
  24696. /**
  24697. * Constructs a new 2D spline curve.
  24698. *
  24699. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24700. */
  24701. constructor( points = [] ) {
  24702. super();
  24703. /**
  24704. * This flag can be used for type testing.
  24705. *
  24706. * @type {boolean}
  24707. * @readonly
  24708. * @default true
  24709. */
  24710. this.isSplineCurve = true;
  24711. this.type = 'SplineCurve';
  24712. /**
  24713. * An array of 2D points defining the curve.
  24714. *
  24715. * @type {Array<Vector2>}
  24716. */
  24717. this.points = points;
  24718. }
  24719. /**
  24720. * Returns a point on the curve.
  24721. *
  24722. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24723. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24724. * @return {Vector2} The position on the curve.
  24725. */
  24726. getPoint( t, optionalTarget = new Vector2() ) {
  24727. const point = optionalTarget;
  24728. const points = this.points;
  24729. const p = ( points.length - 1 ) * t;
  24730. const intPoint = Math.floor( p );
  24731. const weight = p - intPoint;
  24732. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24733. const p1 = points[ intPoint ];
  24734. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24735. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24736. point.set(
  24737. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24738. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24739. );
  24740. return point;
  24741. }
  24742. copy( source ) {
  24743. super.copy( source );
  24744. this.points = [];
  24745. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24746. const point = source.points[ i ];
  24747. this.points.push( point.clone() );
  24748. }
  24749. return this;
  24750. }
  24751. toJSON() {
  24752. const data = super.toJSON();
  24753. data.points = [];
  24754. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24755. const point = this.points[ i ];
  24756. data.points.push( point.toArray() );
  24757. }
  24758. return data;
  24759. }
  24760. fromJSON( json ) {
  24761. super.fromJSON( json );
  24762. this.points = [];
  24763. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24764. const point = json.points[ i ];
  24765. this.points.push( new Vector2().fromArray( point ) );
  24766. }
  24767. return this;
  24768. }
  24769. }
  24770. var Curves = /*#__PURE__*/Object.freeze({
  24771. __proto__: null,
  24772. ArcCurve: ArcCurve,
  24773. CatmullRomCurve3: CatmullRomCurve3,
  24774. CubicBezierCurve: CubicBezierCurve,
  24775. CubicBezierCurve3: CubicBezierCurve3,
  24776. EllipseCurve: EllipseCurve,
  24777. LineCurve: LineCurve,
  24778. LineCurve3: LineCurve3,
  24779. QuadraticBezierCurve: QuadraticBezierCurve,
  24780. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24781. SplineCurve: SplineCurve
  24782. });
  24783. /**
  24784. * A base class extending {@link Curve}. `CurvePath` is simply an
  24785. * array of connected curves, but retains the API of a curve.
  24786. *
  24787. * @augments Curve
  24788. */
  24789. class CurvePath extends Curve {
  24790. /**
  24791. * Constructs a new curve path.
  24792. */
  24793. constructor() {
  24794. super();
  24795. this.type = 'CurvePath';
  24796. /**
  24797. * An array of curves defining the
  24798. * path.
  24799. *
  24800. * @type {Array<Curve>}
  24801. */
  24802. this.curves = [];
  24803. /**
  24804. * Whether the path should automatically be closed
  24805. * by a line curve.
  24806. *
  24807. * @type {boolean}
  24808. * @default false
  24809. */
  24810. this.autoClose = false;
  24811. }
  24812. /**
  24813. * Adds a curve to this curve path.
  24814. *
  24815. * @param {Curve} curve - The curve to add.
  24816. */
  24817. add( curve ) {
  24818. this.curves.push( curve );
  24819. }
  24820. /**
  24821. * Adds a line curve to close the path.
  24822. *
  24823. * @return {CurvePath} A reference to this curve path.
  24824. */
  24825. closePath() {
  24826. // Add a line curve if start and end of lines are not connected
  24827. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24828. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24829. if ( ! startPoint.equals( endPoint ) ) {
  24830. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24831. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24832. }
  24833. return this;
  24834. }
  24835. /**
  24836. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24837. * for the given interpolation factor.
  24838. *
  24839. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24840. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24841. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24842. */
  24843. getPoint( t, optionalTarget ) {
  24844. // To get accurate point with reference to
  24845. // entire path distance at time t,
  24846. // following has to be done:
  24847. // 1. Length of each sub path have to be known
  24848. // 2. Locate and identify type of curve
  24849. // 3. Get t for the curve
  24850. // 4. Return curve.getPointAt(t')
  24851. const d = t * this.getLength();
  24852. const curveLengths = this.getCurveLengths();
  24853. let i = 0;
  24854. // To think about boundaries points.
  24855. while ( i < curveLengths.length ) {
  24856. if ( curveLengths[ i ] >= d ) {
  24857. const diff = curveLengths[ i ] - d;
  24858. const curve = this.curves[ i ];
  24859. const segmentLength = curve.getLength();
  24860. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24861. return curve.getPointAt( u, optionalTarget );
  24862. }
  24863. i ++;
  24864. }
  24865. return null;
  24866. // loop where sum != 0, sum > d , sum+1 <d
  24867. }
  24868. getLength() {
  24869. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24870. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24871. // getPoint() depends on getLength
  24872. const lens = this.getCurveLengths();
  24873. return lens[ lens.length - 1 ];
  24874. }
  24875. updateArcLengths() {
  24876. // cacheLengths must be recalculated.
  24877. this.needsUpdate = true;
  24878. this.cacheLengths = null;
  24879. this.getCurveLengths();
  24880. }
  24881. /**
  24882. * Returns list of cumulative curve lengths of the defined curves.
  24883. *
  24884. * @return {Array<number>} The curve lengths.
  24885. */
  24886. getCurveLengths() {
  24887. // Compute lengths and cache them
  24888. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24889. // We use cache values if curves and cache array are same length
  24890. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24891. return this.cacheLengths;
  24892. }
  24893. // Get length of sub-curve
  24894. // Push sums into cached array
  24895. const lengths = [];
  24896. let sums = 0;
  24897. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24898. sums += this.curves[ i ].getLength();
  24899. lengths.push( sums );
  24900. }
  24901. this.cacheLengths = lengths;
  24902. return lengths;
  24903. }
  24904. getSpacedPoints( divisions = 40 ) {
  24905. const points = [];
  24906. for ( let i = 0; i <= divisions; i ++ ) {
  24907. points.push( this.getPoint( i / divisions ) );
  24908. }
  24909. if ( this.autoClose ) {
  24910. points.push( points[ 0 ] );
  24911. }
  24912. return points;
  24913. }
  24914. getPoints( divisions = 12 ) {
  24915. const points = [];
  24916. let last;
  24917. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24918. const curve = curves[ i ];
  24919. const resolution = curve.isEllipseCurve ? divisions * 2
  24920. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24921. : curve.isSplineCurve ? divisions * curve.points.length
  24922. : divisions;
  24923. const pts = curve.getPoints( resolution );
  24924. for ( let j = 0; j < pts.length; j ++ ) {
  24925. const point = pts[ j ];
  24926. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24927. points.push( point );
  24928. last = point;
  24929. }
  24930. }
  24931. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24932. points.push( points[ 0 ] );
  24933. }
  24934. return points;
  24935. }
  24936. copy( source ) {
  24937. super.copy( source );
  24938. this.curves = [];
  24939. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24940. const curve = source.curves[ i ];
  24941. this.curves.push( curve.clone() );
  24942. }
  24943. this.autoClose = source.autoClose;
  24944. return this;
  24945. }
  24946. toJSON() {
  24947. const data = super.toJSON();
  24948. data.autoClose = this.autoClose;
  24949. data.curves = [];
  24950. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24951. const curve = this.curves[ i ];
  24952. data.curves.push( curve.toJSON() );
  24953. }
  24954. return data;
  24955. }
  24956. fromJSON( json ) {
  24957. super.fromJSON( json );
  24958. this.autoClose = json.autoClose;
  24959. this.curves = [];
  24960. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24961. const curve = json.curves[ i ];
  24962. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24963. }
  24964. return this;
  24965. }
  24966. }
  24967. /**
  24968. * A 2D path representation. The class provides methods for creating paths
  24969. * and contours of 2D shapes similar to the 2D Canvas API.
  24970. *
  24971. * ```js
  24972. * const path = new THREE.Path();
  24973. *
  24974. * path.lineTo( 0, 0.8 );
  24975. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24976. * path.lineTo( 1, 1 );
  24977. *
  24978. * const points = path.getPoints();
  24979. *
  24980. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24981. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24982. *
  24983. * const line = new THREE.Line( geometry, material );
  24984. * scene.add( line );
  24985. * ```
  24986. *
  24987. * @augments CurvePath
  24988. */
  24989. class Path extends CurvePath {
  24990. /**
  24991. * Constructs a new path.
  24992. *
  24993. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24994. */
  24995. constructor( points ) {
  24996. super();
  24997. this.type = 'Path';
  24998. /**
  24999. * The current offset of the path. Any new curve added will start here.
  25000. *
  25001. * @type {Vector2}
  25002. */
  25003. this.currentPoint = new Vector2();
  25004. if ( points ) {
  25005. this.setFromPoints( points );
  25006. }
  25007. }
  25008. /**
  25009. * Creates a path from the given list of points. The points are added
  25010. * to the path as instances of {@link LineCurve}.
  25011. *
  25012. * @param {Array<Vector2>} points - An array of 2D points.
  25013. * @return {Path} A reference to this path.
  25014. */
  25015. setFromPoints( points ) {
  25016. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25017. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25018. this.lineTo( points[ i ].x, points[ i ].y );
  25019. }
  25020. return this;
  25021. }
  25022. /**
  25023. * Moves {@link Path#currentPoint} to the given point.
  25024. *
  25025. * @param {number} x - The x coordinate.
  25026. * @param {number} y - The y coordinate.
  25027. * @return {Path} A reference to this path.
  25028. */
  25029. moveTo( x, y ) {
  25030. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25031. return this;
  25032. }
  25033. /**
  25034. * Adds an instance of {@link LineCurve} to the path by connecting
  25035. * the current point with the given one.
  25036. *
  25037. * @param {number} x - The x coordinate of the end point.
  25038. * @param {number} y - The y coordinate of the end point.
  25039. * @return {Path} A reference to this path.
  25040. */
  25041. lineTo( x, y ) {
  25042. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25043. this.curves.push( curve );
  25044. this.currentPoint.set( x, y );
  25045. return this;
  25046. }
  25047. /**
  25048. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25049. * the current point with the given one.
  25050. *
  25051. * @param {number} aCPx - The x coordinate of the control point.
  25052. * @param {number} aCPy - The y coordinate of the control point.
  25053. * @param {number} aX - The x coordinate of the end point.
  25054. * @param {number} aY - The y coordinate of the end point.
  25055. * @return {Path} A reference to this path.
  25056. */
  25057. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25058. const curve = new QuadraticBezierCurve(
  25059. this.currentPoint.clone(),
  25060. new Vector2( aCPx, aCPy ),
  25061. new Vector2( aX, aY )
  25062. );
  25063. this.curves.push( curve );
  25064. this.currentPoint.set( aX, aY );
  25065. return this;
  25066. }
  25067. /**
  25068. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25069. * the current point with the given one.
  25070. *
  25071. * @param {number} aCP1x - The x coordinate of the first control point.
  25072. * @param {number} aCP1y - The y coordinate of the first control point.
  25073. * @param {number} aCP2x - The x coordinate of the second control point.
  25074. * @param {number} aCP2y - The y coordinate of the second control point.
  25075. * @param {number} aX - The x coordinate of the end point.
  25076. * @param {number} aY - The y coordinate of the end point.
  25077. * @return {Path} A reference to this path.
  25078. */
  25079. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25080. const curve = new CubicBezierCurve(
  25081. this.currentPoint.clone(),
  25082. new Vector2( aCP1x, aCP1y ),
  25083. new Vector2( aCP2x, aCP2y ),
  25084. new Vector2( aX, aY )
  25085. );
  25086. this.curves.push( curve );
  25087. this.currentPoint.set( aX, aY );
  25088. return this;
  25089. }
  25090. /**
  25091. * Adds an instance of {@link SplineCurve} to the path by connecting
  25092. * the current point with the given list of points.
  25093. *
  25094. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25095. * @return {Path} A reference to this path.
  25096. */
  25097. splineThru( pts ) {
  25098. const npts = [ this.currentPoint.clone() ].concat( pts );
  25099. const curve = new SplineCurve( npts );
  25100. this.curves.push( curve );
  25101. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25102. return this;
  25103. }
  25104. /**
  25105. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25106. * to the current point.
  25107. *
  25108. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25109. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25110. * @param {number} [aRadius=1] - The radius of the arc.
  25111. * @param {number} [aStartAngle=0] - The start angle in radians.
  25112. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25113. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25114. * @return {Path} A reference to this path.
  25115. */
  25116. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25117. const x0 = this.currentPoint.x;
  25118. const y0 = this.currentPoint.y;
  25119. this.absarc( aX + x0, aY + y0, aRadius,
  25120. aStartAngle, aEndAngle, aClockwise );
  25121. return this;
  25122. }
  25123. /**
  25124. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25125. *
  25126. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25127. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25128. * @param {number} [aRadius=1] - The radius of the arc.
  25129. * @param {number} [aStartAngle=0] - The start angle in radians.
  25130. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25131. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25132. * @return {Path} A reference to this path.
  25133. */
  25134. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25135. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25136. return this;
  25137. }
  25138. /**
  25139. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25140. * to the current point
  25141. *
  25142. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25143. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25144. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25145. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25146. * @param {number} [aStartAngle=0] - The start angle in radians.
  25147. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25148. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25149. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25150. * @return {Path} A reference to this path.
  25151. */
  25152. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25153. const x0 = this.currentPoint.x;
  25154. const y0 = this.currentPoint.y;
  25155. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25156. return this;
  25157. }
  25158. /**
  25159. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25160. *
  25161. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25162. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25163. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25164. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25165. * @param {number} [aStartAngle=0] - The start angle in radians.
  25166. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25167. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25168. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25169. * @return {Path} A reference to this path.
  25170. */
  25171. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25172. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25173. if ( this.curves.length > 0 ) {
  25174. // if a previous curve is present, attempt to join
  25175. const firstPoint = curve.getPoint( 0 );
  25176. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25177. this.lineTo( firstPoint.x, firstPoint.y );
  25178. }
  25179. }
  25180. this.curves.push( curve );
  25181. const lastPoint = curve.getPoint( 1 );
  25182. this.currentPoint.copy( lastPoint );
  25183. return this;
  25184. }
  25185. copy( source ) {
  25186. super.copy( source );
  25187. this.currentPoint.copy( source.currentPoint );
  25188. return this;
  25189. }
  25190. toJSON() {
  25191. const data = super.toJSON();
  25192. data.currentPoint = this.currentPoint.toArray();
  25193. return data;
  25194. }
  25195. fromJSON( json ) {
  25196. super.fromJSON( json );
  25197. this.currentPoint.fromArray( json.currentPoint );
  25198. return this;
  25199. }
  25200. }
  25201. /**
  25202. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25203. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25204. * points, or to get triangulated faces.
  25205. *
  25206. * ```js
  25207. * const heartShape = new THREE.Shape();
  25208. *
  25209. * heartShape.moveTo( 25, 25 );
  25210. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25211. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25212. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25213. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25214. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25215. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25216. *
  25217. * const extrudeSettings = {
  25218. * depth: 8,
  25219. * bevelEnabled: true,
  25220. * bevelSegments: 2,
  25221. * steps: 2,
  25222. * bevelSize: 1,
  25223. * bevelThickness: 1
  25224. * };
  25225. *
  25226. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25227. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25228. * ```
  25229. *
  25230. * @augments Path
  25231. */
  25232. class Shape extends Path {
  25233. /**
  25234. * Constructs a new shape.
  25235. *
  25236. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25237. */
  25238. constructor( points ) {
  25239. super( points );
  25240. /**
  25241. * The UUID of the shape.
  25242. *
  25243. * @type {string}
  25244. * @readonly
  25245. */
  25246. this.uuid = generateUUID();
  25247. this.type = 'Shape';
  25248. /**
  25249. * Defines the holes in the shape. Hole definitions must use the
  25250. * opposite winding order (CW/CCW) than the outer shape.
  25251. *
  25252. * @type {Array<Path>}
  25253. * @readonly
  25254. */
  25255. this.holes = [];
  25256. }
  25257. /**
  25258. * Returns an array representing each contour of the holes
  25259. * as a list of 2D points.
  25260. *
  25261. * @param {number} divisions - The fineness of the result.
  25262. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25263. */
  25264. getPointsHoles( divisions ) {
  25265. const holesPts = [];
  25266. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25267. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25268. }
  25269. return holesPts;
  25270. }
  25271. // get points of shape and holes (keypoints based on segments parameter)
  25272. /**
  25273. * Returns an object that holds contour data for the shape and its holes as
  25274. * arrays of 2D points.
  25275. *
  25276. * @param {number} divisions - The fineness of the result.
  25277. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25278. */
  25279. extractPoints( divisions ) {
  25280. return {
  25281. shape: this.getPoints( divisions ),
  25282. holes: this.getPointsHoles( divisions )
  25283. };
  25284. }
  25285. copy( source ) {
  25286. super.copy( source );
  25287. this.holes = [];
  25288. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25289. const hole = source.holes[ i ];
  25290. this.holes.push( hole.clone() );
  25291. }
  25292. return this;
  25293. }
  25294. toJSON() {
  25295. const data = super.toJSON();
  25296. data.uuid = this.uuid;
  25297. data.holes = [];
  25298. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25299. const hole = this.holes[ i ];
  25300. data.holes.push( hole.toJSON() );
  25301. }
  25302. return data;
  25303. }
  25304. fromJSON( json ) {
  25305. super.fromJSON( json );
  25306. this.uuid = json.uuid;
  25307. this.holes = [];
  25308. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25309. const hole = json.holes[ i ];
  25310. this.holes.push( new Path().fromJSON( hole ) );
  25311. }
  25312. return this;
  25313. }
  25314. }
  25315. /* eslint-disable */
  25316. // copy of mapbox/earcut version 3.0.2
  25317. // https://github.com/mapbox/earcut/tree/v3.0.2
  25318. function earcut(data, holeIndices, dim = 2) {
  25319. const hasHoles = holeIndices && holeIndices.length;
  25320. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25321. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25322. const triangles = [];
  25323. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25324. let minX, minY, invSize;
  25325. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25326. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25327. if (data.length > 80 * dim) {
  25328. minX = data[0];
  25329. minY = data[1];
  25330. let maxX = minX;
  25331. let maxY = minY;
  25332. for (let i = dim; i < outerLen; i += dim) {
  25333. const x = data[i];
  25334. const y = data[i + 1];
  25335. if (x < minX) minX = x;
  25336. if (y < minY) minY = y;
  25337. if (x > maxX) maxX = x;
  25338. if (y > maxY) maxY = y;
  25339. }
  25340. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25341. invSize = Math.max(maxX - minX, maxY - minY);
  25342. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25343. }
  25344. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25345. return triangles;
  25346. }
  25347. // create a circular doubly linked list from polygon points in the specified winding order
  25348. function linkedList(data, start, end, dim, clockwise) {
  25349. let last;
  25350. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25351. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25352. } else {
  25353. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25354. }
  25355. if (last && equals(last, last.next)) {
  25356. removeNode(last);
  25357. last = last.next;
  25358. }
  25359. return last;
  25360. }
  25361. // eliminate colinear or duplicate points
  25362. function filterPoints(start, end) {
  25363. if (!start) return start;
  25364. if (!end) end = start;
  25365. let p = start,
  25366. again;
  25367. do {
  25368. again = false;
  25369. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25370. removeNode(p);
  25371. p = end = p.prev;
  25372. if (p === p.next) break;
  25373. again = true;
  25374. } else {
  25375. p = p.next;
  25376. }
  25377. } while (again || p !== end);
  25378. return end;
  25379. }
  25380. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25381. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25382. if (!ear) return;
  25383. // interlink polygon nodes in z-order
  25384. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25385. let stop = ear;
  25386. // iterate through ears, slicing them one by one
  25387. while (ear.prev !== ear.next) {
  25388. const prev = ear.prev;
  25389. const next = ear.next;
  25390. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25391. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25392. removeNode(ear);
  25393. // skipping the next vertex leads to less sliver triangles
  25394. ear = next.next;
  25395. stop = next.next;
  25396. continue;
  25397. }
  25398. ear = next;
  25399. // if we looped through the whole remaining polygon and can't find any more ears
  25400. if (ear === stop) {
  25401. // try filtering points and slicing again
  25402. if (!pass) {
  25403. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25404. // if this didn't work, try curing all small self-intersections locally
  25405. } else if (pass === 1) {
  25406. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25407. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25408. // as a last resort, try splitting the remaining polygon into two
  25409. } else if (pass === 2) {
  25410. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25411. }
  25412. break;
  25413. }
  25414. }
  25415. }
  25416. // check whether a polygon node forms a valid ear with adjacent nodes
  25417. function isEar(ear) {
  25418. const a = ear.prev,
  25419. b = ear,
  25420. c = ear.next;
  25421. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25422. // now make sure we don't have other points inside the potential ear
  25423. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25424. // triangle bbox
  25425. const x0 = Math.min(ax, bx, cx),
  25426. y0 = Math.min(ay, by, cy),
  25427. x1 = Math.max(ax, bx, cx),
  25428. y1 = Math.max(ay, by, cy);
  25429. let p = c.next;
  25430. while (p !== a) {
  25431. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25432. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25433. area(p.prev, p, p.next) >= 0) return false;
  25434. p = p.next;
  25435. }
  25436. return true;
  25437. }
  25438. function isEarHashed(ear, minX, minY, invSize) {
  25439. const a = ear.prev,
  25440. b = ear,
  25441. c = ear.next;
  25442. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25443. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25444. // triangle bbox
  25445. const x0 = Math.min(ax, bx, cx),
  25446. y0 = Math.min(ay, by, cy),
  25447. x1 = Math.max(ax, bx, cx),
  25448. y1 = Math.max(ay, by, cy);
  25449. // z-order range for the current triangle bbox;
  25450. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25451. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25452. let p = ear.prevZ,
  25453. n = ear.nextZ;
  25454. // look for points inside the triangle in both directions
  25455. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25456. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25457. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25458. p = p.prevZ;
  25459. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25460. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25461. n = n.nextZ;
  25462. }
  25463. // look for remaining points in decreasing z-order
  25464. while (p && p.z >= minZ) {
  25465. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25466. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25467. p = p.prevZ;
  25468. }
  25469. // look for remaining points in increasing z-order
  25470. while (n && n.z <= maxZ) {
  25471. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25472. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25473. n = n.nextZ;
  25474. }
  25475. return true;
  25476. }
  25477. // go through all polygon nodes and cure small local self-intersections
  25478. function cureLocalIntersections(start, triangles) {
  25479. let p = start;
  25480. do {
  25481. const a = p.prev,
  25482. b = p.next.next;
  25483. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25484. triangles.push(a.i, p.i, b.i);
  25485. // remove two nodes involved
  25486. removeNode(p);
  25487. removeNode(p.next);
  25488. p = start = b;
  25489. }
  25490. p = p.next;
  25491. } while (p !== start);
  25492. return filterPoints(p);
  25493. }
  25494. // try splitting polygon into two and triangulate them independently
  25495. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25496. // look for a valid diagonal that divides the polygon into two
  25497. let a = start;
  25498. do {
  25499. let b = a.next.next;
  25500. while (b !== a.prev) {
  25501. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25502. // split the polygon in two by the diagonal
  25503. let c = splitPolygon(a, b);
  25504. // filter colinear points around the cuts
  25505. a = filterPoints(a, a.next);
  25506. c = filterPoints(c, c.next);
  25507. // run earcut on each half
  25508. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25509. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25510. return;
  25511. }
  25512. b = b.next;
  25513. }
  25514. a = a.next;
  25515. } while (a !== start);
  25516. }
  25517. // link every hole into the outer loop, producing a single-ring polygon without holes
  25518. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25519. const queue = [];
  25520. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25521. const start = holeIndices[i] * dim;
  25522. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25523. const list = linkedList(data, start, end, dim, false);
  25524. if (list === list.next) list.steiner = true;
  25525. queue.push(getLeftmost(list));
  25526. }
  25527. queue.sort(compareXYSlope);
  25528. // process holes from left to right
  25529. for (let i = 0; i < queue.length; i++) {
  25530. outerNode = eliminateHole(queue[i], outerNode);
  25531. }
  25532. return outerNode;
  25533. }
  25534. function compareXYSlope(a, b) {
  25535. let result = a.x - b.x;
  25536. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25537. // the bridge to the outer shell is always the point that they meet at.
  25538. if (result === 0) {
  25539. result = a.y - b.y;
  25540. if (result === 0) {
  25541. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25542. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25543. result = aSlope - bSlope;
  25544. }
  25545. }
  25546. return result;
  25547. }
  25548. // find a bridge between vertices that connects hole with an outer ring and link it
  25549. function eliminateHole(hole, outerNode) {
  25550. const bridge = findHoleBridge(hole, outerNode);
  25551. if (!bridge) {
  25552. return outerNode;
  25553. }
  25554. const bridgeReverse = splitPolygon(bridge, hole);
  25555. // filter collinear points around the cuts
  25556. filterPoints(bridgeReverse, bridgeReverse.next);
  25557. return filterPoints(bridge, bridge.next);
  25558. }
  25559. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25560. function findHoleBridge(hole, outerNode) {
  25561. let p = outerNode;
  25562. const hx = hole.x;
  25563. const hy = hole.y;
  25564. let qx = -Infinity;
  25565. let m;
  25566. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25567. // segment's endpoint with lesser x will be potential connection point
  25568. // unless they intersect at a vertex, then choose the vertex
  25569. if (equals(hole, p)) return p;
  25570. do {
  25571. if (equals(hole, p.next)) return p.next;
  25572. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25573. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25574. if (x <= hx && x > qx) {
  25575. qx = x;
  25576. m = p.x < p.next.x ? p : p.next;
  25577. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25578. }
  25579. }
  25580. p = p.next;
  25581. } while (p !== outerNode);
  25582. if (!m) return null;
  25583. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25584. // if there are no points found, we have a valid connection;
  25585. // otherwise choose the point of the minimum angle with the ray as connection point
  25586. const stop = m;
  25587. const mx = m.x;
  25588. const my = m.y;
  25589. let tanMin = Infinity;
  25590. p = m;
  25591. do {
  25592. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25593. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25594. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25595. if (locallyInside(p, hole) &&
  25596. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25597. m = p;
  25598. tanMin = tan;
  25599. }
  25600. }
  25601. p = p.next;
  25602. } while (p !== stop);
  25603. return m;
  25604. }
  25605. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25606. function sectorContainsSector(m, p) {
  25607. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25608. }
  25609. // interlink polygon nodes in z-order
  25610. function indexCurve(start, minX, minY, invSize) {
  25611. let p = start;
  25612. do {
  25613. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25614. p.prevZ = p.prev;
  25615. p.nextZ = p.next;
  25616. p = p.next;
  25617. } while (p !== start);
  25618. p.prevZ.nextZ = null;
  25619. p.prevZ = null;
  25620. sortLinked(p);
  25621. }
  25622. // Simon Tatham's linked list merge sort algorithm
  25623. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25624. function sortLinked(list) {
  25625. let numMerges;
  25626. let inSize = 1;
  25627. do {
  25628. let p = list;
  25629. let e;
  25630. list = null;
  25631. let tail = null;
  25632. numMerges = 0;
  25633. while (p) {
  25634. numMerges++;
  25635. let q = p;
  25636. let pSize = 0;
  25637. for (let i = 0; i < inSize; i++) {
  25638. pSize++;
  25639. q = q.nextZ;
  25640. if (!q) break;
  25641. }
  25642. let qSize = inSize;
  25643. while (pSize > 0 || (qSize > 0 && q)) {
  25644. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25645. e = p;
  25646. p = p.nextZ;
  25647. pSize--;
  25648. } else {
  25649. e = q;
  25650. q = q.nextZ;
  25651. qSize--;
  25652. }
  25653. if (tail) tail.nextZ = e;
  25654. else list = e;
  25655. e.prevZ = tail;
  25656. tail = e;
  25657. }
  25658. p = q;
  25659. }
  25660. tail.nextZ = null;
  25661. inSize *= 2;
  25662. } while (numMerges > 1);
  25663. return list;
  25664. }
  25665. // z-order of a point given coords and inverse of the longer side of data bbox
  25666. function zOrder(x, y, minX, minY, invSize) {
  25667. // coords are transformed into non-negative 15-bit integer range
  25668. x = (x - minX) * invSize | 0;
  25669. y = (y - minY) * invSize | 0;
  25670. x = (x | (x << 8)) & 0x00FF00FF;
  25671. x = (x | (x << 4)) & 0x0F0F0F0F;
  25672. x = (x | (x << 2)) & 0x33333333;
  25673. x = (x | (x << 1)) & 0x55555555;
  25674. y = (y | (y << 8)) & 0x00FF00FF;
  25675. y = (y | (y << 4)) & 0x0F0F0F0F;
  25676. y = (y | (y << 2)) & 0x33333333;
  25677. y = (y | (y << 1)) & 0x55555555;
  25678. return x | (y << 1);
  25679. }
  25680. // find the leftmost node of a polygon ring
  25681. function getLeftmost(start) {
  25682. let p = start,
  25683. leftmost = start;
  25684. do {
  25685. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25686. p = p.next;
  25687. } while (p !== start);
  25688. return leftmost;
  25689. }
  25690. // check if a point lies within a convex triangle
  25691. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25692. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25693. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25694. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25695. }
  25696. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25697. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25698. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25699. }
  25700. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25701. function isValidDiagonal(a, b) {
  25702. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25703. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25704. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25705. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25706. }
  25707. // signed area of a triangle
  25708. function area(p, q, r) {
  25709. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25710. }
  25711. // check if two points are equal
  25712. function equals(p1, p2) {
  25713. return p1.x === p2.x && p1.y === p2.y;
  25714. }
  25715. // check if two segments intersect
  25716. function intersects(p1, q1, p2, q2) {
  25717. const o1 = sign(area(p1, q1, p2));
  25718. const o2 = sign(area(p1, q1, q2));
  25719. const o3 = sign(area(p2, q2, p1));
  25720. const o4 = sign(area(p2, q2, q1));
  25721. if (o1 !== o2 && o3 !== o4) return true; // general case
  25722. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25723. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25724. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25725. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25726. return false;
  25727. }
  25728. // for collinear points p, q, r, check if point q lies on segment pr
  25729. function onSegment(p, q, r) {
  25730. 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);
  25731. }
  25732. function sign(num) {
  25733. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25734. }
  25735. // check if a polygon diagonal intersects any polygon segments
  25736. function intersectsPolygon(a, b) {
  25737. let p = a;
  25738. do {
  25739. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25740. intersects(p, p.next, a, b)) return true;
  25741. p = p.next;
  25742. } while (p !== a);
  25743. return false;
  25744. }
  25745. // check if a polygon diagonal is locally inside the polygon
  25746. function locallyInside(a, b) {
  25747. return area(a.prev, a, a.next) < 0 ?
  25748. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25749. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25750. }
  25751. // check if the middle point of a polygon diagonal is inside the polygon
  25752. function middleInside(a, b) {
  25753. let p = a;
  25754. let inside = false;
  25755. const px = (a.x + b.x) / 2;
  25756. const py = (a.y + b.y) / 2;
  25757. do {
  25758. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25759. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25760. inside = !inside;
  25761. p = p.next;
  25762. } while (p !== a);
  25763. return inside;
  25764. }
  25765. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25766. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25767. function splitPolygon(a, b) {
  25768. const a2 = createNode(a.i, a.x, a.y),
  25769. b2 = createNode(b.i, b.x, b.y),
  25770. an = a.next,
  25771. bp = b.prev;
  25772. a.next = b;
  25773. b.prev = a;
  25774. a2.next = an;
  25775. an.prev = a2;
  25776. b2.next = a2;
  25777. a2.prev = b2;
  25778. bp.next = b2;
  25779. b2.prev = bp;
  25780. return b2;
  25781. }
  25782. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25783. function insertNode(i, x, y, last) {
  25784. const p = createNode(i, x, y);
  25785. if (!last) {
  25786. p.prev = p;
  25787. p.next = p;
  25788. } else {
  25789. p.next = last.next;
  25790. p.prev = last;
  25791. last.next.prev = p;
  25792. last.next = p;
  25793. }
  25794. return p;
  25795. }
  25796. function removeNode(p) {
  25797. p.next.prev = p.prev;
  25798. p.prev.next = p.next;
  25799. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25800. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25801. }
  25802. function createNode(i, x, y) {
  25803. return {
  25804. i, // vertex index in coordinates array
  25805. x, y, // vertex coordinates
  25806. prev: null, // previous and next vertex nodes in a polygon ring
  25807. next: null,
  25808. z: 0, // z-order curve value
  25809. prevZ: null, // previous and next nodes in z-order
  25810. nextZ: null,
  25811. steiner: false // indicates whether this is a steiner point
  25812. };
  25813. }
  25814. function signedArea(data, start, end, dim) {
  25815. let sum = 0;
  25816. for (let i = start, j = end - dim; i < end; i += dim) {
  25817. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25818. j = i;
  25819. }
  25820. return sum;
  25821. }
  25822. /**
  25823. * An implementation of the earcut polygon triangulation algorithm.
  25824. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25825. *
  25826. * @see https://github.com/mapbox/earcut
  25827. */
  25828. class Earcut {
  25829. /**
  25830. * Triangulates the given shape definition by returning an array of triangles.
  25831. *
  25832. * @param {Array<number>} data - An array with 2D points.
  25833. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25834. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25835. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25836. * representing vertex indices.
  25837. */
  25838. static triangulate( data, holeIndices, dim = 2 ) {
  25839. return earcut( data, holeIndices, dim );
  25840. }
  25841. }
  25842. /**
  25843. * A class containing utility functions for shapes.
  25844. *
  25845. * @hideconstructor
  25846. */
  25847. class ShapeUtils {
  25848. /**
  25849. * Calculate area of a ( 2D ) contour polygon.
  25850. *
  25851. * @param {Array<Vector2>} contour - An array of 2D points.
  25852. * @return {number} The area.
  25853. */
  25854. static area( contour ) {
  25855. const n = contour.length;
  25856. let a = 0.0;
  25857. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25858. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25859. }
  25860. return a * 0.5;
  25861. }
  25862. /**
  25863. * Returns `true` if the given contour uses a clockwise winding order.
  25864. *
  25865. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25866. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25867. */
  25868. static isClockWise( pts ) {
  25869. return ShapeUtils.area( pts ) < 0;
  25870. }
  25871. /**
  25872. * Triangulates the given shape definition.
  25873. *
  25874. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25875. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25876. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25877. */
  25878. static triangulateShape( contour, holes ) {
  25879. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25880. const holeIndices = []; // array of hole indices
  25881. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25882. removeDupEndPts( contour );
  25883. addContour( vertices, contour );
  25884. //
  25885. let holeIndex = contour.length;
  25886. holes.forEach( removeDupEndPts );
  25887. for ( let i = 0; i < holes.length; i ++ ) {
  25888. holeIndices.push( holeIndex );
  25889. holeIndex += holes[ i ].length;
  25890. addContour( vertices, holes[ i ] );
  25891. }
  25892. //
  25893. const triangles = Earcut.triangulate( vertices, holeIndices );
  25894. //
  25895. for ( let i = 0; i < triangles.length; i += 3 ) {
  25896. faces.push( triangles.slice( i, i + 3 ) );
  25897. }
  25898. return faces;
  25899. }
  25900. }
  25901. function removeDupEndPts( points ) {
  25902. const l = points.length;
  25903. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25904. points.pop();
  25905. }
  25906. }
  25907. function addContour( vertices, contour ) {
  25908. for ( let i = 0; i < contour.length; i ++ ) {
  25909. vertices.push( contour[ i ].x );
  25910. vertices.push( contour[ i ].y );
  25911. }
  25912. }
  25913. /**
  25914. * Creates extruded geometry from a path shape.
  25915. *
  25916. * ```js
  25917. * const length = 12, width = 8;
  25918. *
  25919. * const shape = new THREE.Shape();
  25920. * shape.moveTo( 0,0 );
  25921. * shape.lineTo( 0, width );
  25922. * shape.lineTo( length, width );
  25923. * shape.lineTo( length, 0 );
  25924. * shape.lineTo( 0, 0 );
  25925. *
  25926. * const geometry = new THREE.ExtrudeGeometry( shape );
  25927. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25928. * const mesh = new THREE.Mesh( geometry, material ) ;
  25929. * scene.add( mesh );
  25930. * ```
  25931. *
  25932. * @augments BufferGeometry
  25933. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25934. */
  25935. class ExtrudeGeometry extends BufferGeometry {
  25936. /**
  25937. * Constructs a new extrude geometry.
  25938. *
  25939. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25940. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25941. */
  25942. 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 = {} ) {
  25943. super();
  25944. this.type = 'ExtrudeGeometry';
  25945. /**
  25946. * Holds the constructor parameters that have been
  25947. * used to generate the geometry. Any modification
  25948. * after instantiation does not change the geometry.
  25949. *
  25950. * @type {Object}
  25951. */
  25952. this.parameters = {
  25953. shapes: shapes,
  25954. options: options
  25955. };
  25956. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25957. const scope = this;
  25958. const verticesArray = [];
  25959. const uvArray = [];
  25960. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25961. const shape = shapes[ i ];
  25962. addShape( shape );
  25963. }
  25964. // build geometry
  25965. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25966. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25967. this.computeVertexNormals();
  25968. // functions
  25969. function addShape( shape ) {
  25970. const placeholder = [];
  25971. // options
  25972. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25973. const steps = options.steps !== undefined ? options.steps : 1;
  25974. const depth = options.depth !== undefined ? options.depth : 1;
  25975. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25976. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25977. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25978. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25979. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25980. const extrudePath = options.extrudePath;
  25981. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25982. //
  25983. let extrudePts, extrudeByPath = false;
  25984. let splineTube, binormal, normal, position2;
  25985. if ( extrudePath ) {
  25986. extrudePts = extrudePath.getSpacedPoints( steps );
  25987. extrudeByPath = true;
  25988. bevelEnabled = false; // bevels not supported for path extrusion
  25989. // SETUP TNB variables
  25990. const isClosed = extrudePath.isCatmullRomCurve3 ? extrudePath.closed : false;
  25991. splineTube = extrudePath.computeFrenetFrames( steps, isClosed );
  25992. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25993. binormal = new Vector3();
  25994. normal = new Vector3();
  25995. position2 = new Vector3();
  25996. }
  25997. // Safeguards if bevels are not enabled
  25998. if ( ! bevelEnabled ) {
  25999. bevelSegments = 0;
  26000. bevelThickness = 0;
  26001. bevelSize = 0;
  26002. bevelOffset = 0;
  26003. }
  26004. // Variables initialization
  26005. const shapePoints = shape.extractPoints( curveSegments );
  26006. let vertices = shapePoints.shape;
  26007. const holes = shapePoints.holes;
  26008. const reverse = ! ShapeUtils.isClockWise( vertices );
  26009. if ( reverse ) {
  26010. vertices = vertices.reverse();
  26011. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26012. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26013. const ahole = holes[ h ];
  26014. if ( ShapeUtils.isClockWise( ahole ) ) {
  26015. holes[ h ] = ahole.reverse();
  26016. }
  26017. }
  26018. }
  26019. /**Merges index-adjacent points that are within a threshold distance of each other. Array is modified in-place. Threshold distance is empirical, and scaled based on the magnitude of point coordinates.
  26020. * @param {Array<Vector2>} points
  26021. */
  26022. function mergeOverlappingPoints( points ) {
  26023. const THRESHOLD = 1e-10;
  26024. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26025. let prevPos = points[ 0 ];
  26026. for ( let i = 1; i <= points.length; i ++ ) {
  26027. const currentIndex = i % points.length;
  26028. const currentPos = points[ currentIndex ];
  26029. const dx = currentPos.x - prevPos.x;
  26030. const dy = currentPos.y - prevPos.y;
  26031. const distSq = dx * dx + dy * dy;
  26032. const scalingFactorSqrt = Math.max(
  26033. Math.abs( currentPos.x ),
  26034. Math.abs( currentPos.y ),
  26035. Math.abs( prevPos.x ),
  26036. Math.abs( prevPos.y )
  26037. );
  26038. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26039. if ( distSq <= thresholdSqScaled ) {
  26040. points.splice( currentIndex, 1 );
  26041. i --;
  26042. continue;
  26043. }
  26044. prevPos = currentPos;
  26045. }
  26046. }
  26047. mergeOverlappingPoints( vertices );
  26048. holes.forEach( mergeOverlappingPoints );
  26049. const numHoles = holes.length;
  26050. /* Vertices */
  26051. const contour = vertices; // vertices has all points but contour has only points of circumference
  26052. for ( let h = 0; h < numHoles; h ++ ) {
  26053. const ahole = holes[ h ];
  26054. vertices = vertices.concat( ahole );
  26055. }
  26056. function scalePt2( pt, vec, size ) {
  26057. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26058. return pt.clone().addScaledVector( vec, size );
  26059. }
  26060. const vlen = vertices.length;
  26061. // Find directions for point movement
  26062. function getBevelVec( inPt, inPrev, inNext ) {
  26063. // computes for inPt the corresponding point inPt' on a new contour
  26064. // shifted by 1 unit (length of normalized vector) to the left
  26065. // if we walk along contour clockwise, this new contour is outside the old one
  26066. //
  26067. // inPt' is the intersection of the two lines parallel to the two
  26068. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26069. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26070. // good reading for geometry algorithms (here: line-line intersection)
  26071. // http://geomalgorithms.com/a05-_intersect-1.html
  26072. const v_prev_x = inPt.x - inPrev.x,
  26073. v_prev_y = inPt.y - inPrev.y;
  26074. const v_next_x = inNext.x - inPt.x,
  26075. v_next_y = inNext.y - inPt.y;
  26076. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26077. // check for collinear edges
  26078. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26079. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26080. // not collinear
  26081. // length of vectors for normalizing
  26082. const v_prev_len = Math.sqrt( v_prev_lensq );
  26083. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26084. // shift adjacent points by unit vectors to the left
  26085. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26086. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26087. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26088. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26089. // scaling factor for v_prev to intersection point
  26090. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26091. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26092. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26093. // vector from inPt to intersection point
  26094. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26095. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26096. // Don't normalize!, otherwise sharp corners become ugly
  26097. // but prevent crazy spikes
  26098. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26099. if ( v_trans_lensq <= 2 ) {
  26100. return new Vector2( v_trans_x, v_trans_y );
  26101. } else {
  26102. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26103. }
  26104. } else {
  26105. // handle special case of collinear edges
  26106. let direction_eq = false; // assumes: opposite
  26107. if ( v_prev_x > Number.EPSILON ) {
  26108. if ( v_next_x > Number.EPSILON ) {
  26109. direction_eq = true;
  26110. }
  26111. } else {
  26112. if ( v_prev_x < - Number.EPSILON ) {
  26113. if ( v_next_x < - Number.EPSILON ) {
  26114. direction_eq = true;
  26115. }
  26116. } else {
  26117. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26118. direction_eq = true;
  26119. }
  26120. }
  26121. }
  26122. if ( direction_eq ) {
  26123. // log("Warning: lines are a straight sequence");
  26124. v_trans_x = - v_prev_y;
  26125. v_trans_y = v_prev_x;
  26126. shrink_by = Math.sqrt( v_prev_lensq );
  26127. } else {
  26128. // log("Warning: lines are a straight spike");
  26129. v_trans_x = v_prev_x;
  26130. v_trans_y = v_prev_y;
  26131. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26132. }
  26133. }
  26134. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26135. }
  26136. const contourMovements = [];
  26137. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26138. if ( j === il ) j = 0;
  26139. if ( k === il ) k = 0;
  26140. // (j)---(i)---(k)
  26141. // log('i,j,k', i, j , k)
  26142. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26143. }
  26144. const holesMovements = [];
  26145. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26146. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26147. const ahole = holes[ h ];
  26148. oneHoleMovements = [];
  26149. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26150. if ( j === il ) j = 0;
  26151. if ( k === il ) k = 0;
  26152. // (j)---(i)---(k)
  26153. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26154. }
  26155. holesMovements.push( oneHoleMovements );
  26156. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26157. }
  26158. let faces;
  26159. if ( bevelSegments === 0 ) {
  26160. faces = ShapeUtils.triangulateShape( contour, holes );
  26161. } else {
  26162. const contractedContourVertices = [];
  26163. const expandedHoleVertices = [];
  26164. // Loop bevelSegments, 1 for the front, 1 for the back
  26165. for ( let b = 0; b < bevelSegments; b ++ ) {
  26166. //for ( b = bevelSegments; b > 0; b -- ) {
  26167. const t = b / bevelSegments;
  26168. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26169. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26170. // contract shape
  26171. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26172. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26173. v( vert.x, vert.y, - z );
  26174. if ( t === 0 ) contractedContourVertices.push( vert );
  26175. }
  26176. // expand holes
  26177. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26178. const ahole = holes[ h ];
  26179. oneHoleMovements = holesMovements[ h ];
  26180. const oneHoleVertices = [];
  26181. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26182. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26183. v( vert.x, vert.y, - z );
  26184. if ( t === 0 ) oneHoleVertices.push( vert );
  26185. }
  26186. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26187. }
  26188. }
  26189. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26190. }
  26191. const flen = faces.length;
  26192. const bs = bevelSize + bevelOffset;
  26193. // Back facing vertices
  26194. for ( let i = 0; i < vlen; i ++ ) {
  26195. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26196. if ( ! extrudeByPath ) {
  26197. v( vert.x, vert.y, 0 );
  26198. } else {
  26199. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26200. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26201. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26202. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26203. v( position2.x, position2.y, position2.z );
  26204. }
  26205. }
  26206. // Add stepped vertices...
  26207. // Including front facing vertices
  26208. for ( let s = 1; s <= steps; s ++ ) {
  26209. for ( let i = 0; i < vlen; i ++ ) {
  26210. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26211. if ( ! extrudeByPath ) {
  26212. v( vert.x, vert.y, depth / steps * s );
  26213. } else {
  26214. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26215. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26216. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26217. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26218. v( position2.x, position2.y, position2.z );
  26219. }
  26220. }
  26221. }
  26222. // Add bevel segments planes
  26223. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26224. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26225. const t = b / bevelSegments;
  26226. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26227. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26228. // contract shape
  26229. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26230. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26231. v( vert.x, vert.y, depth + z );
  26232. }
  26233. // expand holes
  26234. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26235. const ahole = holes[ h ];
  26236. oneHoleMovements = holesMovements[ h ];
  26237. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26238. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26239. if ( ! extrudeByPath ) {
  26240. v( vert.x, vert.y, depth + z );
  26241. } else {
  26242. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26243. }
  26244. }
  26245. }
  26246. }
  26247. /* Faces */
  26248. // Top and bottom faces
  26249. buildLidFaces();
  26250. // Sides faces
  26251. buildSideFaces();
  26252. ///// Internal functions
  26253. function buildLidFaces() {
  26254. const start = verticesArray.length / 3;
  26255. if ( bevelEnabled ) {
  26256. let layer = 0; // steps + 1
  26257. let offset = vlen * layer;
  26258. // Bottom faces
  26259. for ( let i = 0; i < flen; i ++ ) {
  26260. const face = faces[ i ];
  26261. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26262. }
  26263. layer = steps + bevelSegments * 2;
  26264. offset = vlen * layer;
  26265. // Top faces
  26266. for ( let i = 0; i < flen; i ++ ) {
  26267. const face = faces[ i ];
  26268. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26269. }
  26270. } else {
  26271. // Bottom faces
  26272. for ( let i = 0; i < flen; i ++ ) {
  26273. const face = faces[ i ];
  26274. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26275. }
  26276. // Top faces
  26277. for ( let i = 0; i < flen; i ++ ) {
  26278. const face = faces[ i ];
  26279. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26280. }
  26281. }
  26282. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26283. }
  26284. // Create faces for the z-sides of the shape
  26285. function buildSideFaces() {
  26286. const start = verticesArray.length / 3;
  26287. let layeroffset = 0;
  26288. sidewalls( contour, layeroffset );
  26289. layeroffset += contour.length;
  26290. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26291. const ahole = holes[ h ];
  26292. sidewalls( ahole, layeroffset );
  26293. //, true
  26294. layeroffset += ahole.length;
  26295. }
  26296. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26297. }
  26298. function sidewalls( contour, layeroffset ) {
  26299. let i = contour.length;
  26300. while ( -- i >= 0 ) {
  26301. const j = i;
  26302. let k = i - 1;
  26303. if ( k < 0 ) k = contour.length - 1;
  26304. //log('b', i,j, i-1, k,vertices.length);
  26305. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26306. const slen1 = vlen * s;
  26307. const slen2 = vlen * ( s + 1 );
  26308. const a = layeroffset + j + slen1,
  26309. b = layeroffset + k + slen1,
  26310. c = layeroffset + k + slen2,
  26311. d = layeroffset + j + slen2;
  26312. f4( a, b, c, d );
  26313. }
  26314. }
  26315. }
  26316. function v( x, y, z ) {
  26317. placeholder.push( x );
  26318. placeholder.push( y );
  26319. placeholder.push( z );
  26320. }
  26321. function f3( a, b, c ) {
  26322. addVertex( a );
  26323. addVertex( b );
  26324. addVertex( c );
  26325. const nextIndex = verticesArray.length / 3;
  26326. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26327. addUV( uvs[ 0 ] );
  26328. addUV( uvs[ 1 ] );
  26329. addUV( uvs[ 2 ] );
  26330. }
  26331. function f4( a, b, c, d ) {
  26332. addVertex( a );
  26333. addVertex( b );
  26334. addVertex( d );
  26335. addVertex( b );
  26336. addVertex( c );
  26337. addVertex( d );
  26338. const nextIndex = verticesArray.length / 3;
  26339. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26340. addUV( uvs[ 0 ] );
  26341. addUV( uvs[ 1 ] );
  26342. addUV( uvs[ 3 ] );
  26343. addUV( uvs[ 1 ] );
  26344. addUV( uvs[ 2 ] );
  26345. addUV( uvs[ 3 ] );
  26346. }
  26347. function addVertex( index ) {
  26348. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26349. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26350. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26351. }
  26352. function addUV( vector2 ) {
  26353. uvArray.push( vector2.x );
  26354. uvArray.push( vector2.y );
  26355. }
  26356. }
  26357. }
  26358. copy( source ) {
  26359. super.copy( source );
  26360. this.parameters = Object.assign( {}, source.parameters );
  26361. return this;
  26362. }
  26363. toJSON() {
  26364. const data = super.toJSON();
  26365. const shapes = this.parameters.shapes;
  26366. const options = this.parameters.options;
  26367. return toJSON$1( shapes, options, data );
  26368. }
  26369. /**
  26370. * Factory method for creating an instance of this class from the given
  26371. * JSON object.
  26372. *
  26373. * @param {Object} data - A JSON object representing the serialized geometry.
  26374. * @param {Array<Shape>} shapes - An array of shapes.
  26375. * @return {ExtrudeGeometry} A new instance.
  26376. */
  26377. static fromJSON( data, shapes ) {
  26378. const geometryShapes = [];
  26379. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26380. const shape = shapes[ data.shapes[ j ] ];
  26381. geometryShapes.push( shape );
  26382. }
  26383. const extrudePath = data.options.extrudePath;
  26384. if ( extrudePath !== undefined ) {
  26385. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26386. }
  26387. return new ExtrudeGeometry( geometryShapes, data.options );
  26388. }
  26389. }
  26390. const WorldUVGenerator = {
  26391. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26392. const a_x = vertices[ indexA * 3 ];
  26393. const a_y = vertices[ indexA * 3 + 1 ];
  26394. const b_x = vertices[ indexB * 3 ];
  26395. const b_y = vertices[ indexB * 3 + 1 ];
  26396. const c_x = vertices[ indexC * 3 ];
  26397. const c_y = vertices[ indexC * 3 + 1 ];
  26398. return [
  26399. new Vector2( a_x, a_y ),
  26400. new Vector2( b_x, b_y ),
  26401. new Vector2( c_x, c_y )
  26402. ];
  26403. },
  26404. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26405. const a_x = vertices[ indexA * 3 ];
  26406. const a_y = vertices[ indexA * 3 + 1 ];
  26407. const a_z = vertices[ indexA * 3 + 2 ];
  26408. const b_x = vertices[ indexB * 3 ];
  26409. const b_y = vertices[ indexB * 3 + 1 ];
  26410. const b_z = vertices[ indexB * 3 + 2 ];
  26411. const c_x = vertices[ indexC * 3 ];
  26412. const c_y = vertices[ indexC * 3 + 1 ];
  26413. const c_z = vertices[ indexC * 3 + 2 ];
  26414. const d_x = vertices[ indexD * 3 ];
  26415. const d_y = vertices[ indexD * 3 + 1 ];
  26416. const d_z = vertices[ indexD * 3 + 2 ];
  26417. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26418. return [
  26419. new Vector2( a_x, 1 - a_z ),
  26420. new Vector2( b_x, 1 - b_z ),
  26421. new Vector2( c_x, 1 - c_z ),
  26422. new Vector2( d_x, 1 - d_z )
  26423. ];
  26424. } else {
  26425. return [
  26426. new Vector2( a_y, 1 - a_z ),
  26427. new Vector2( b_y, 1 - b_z ),
  26428. new Vector2( c_y, 1 - c_z ),
  26429. new Vector2( d_y, 1 - d_z )
  26430. ];
  26431. }
  26432. }
  26433. };
  26434. function toJSON$1( shapes, options, data ) {
  26435. data.shapes = [];
  26436. if ( Array.isArray( shapes ) ) {
  26437. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26438. const shape = shapes[ i ];
  26439. data.shapes.push( shape.uuid );
  26440. }
  26441. } else {
  26442. data.shapes.push( shapes.uuid );
  26443. }
  26444. data.options = Object.assign( {}, options );
  26445. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26446. return data;
  26447. }
  26448. /**
  26449. * A geometry class for representing an icosahedron.
  26450. *
  26451. * ```js
  26452. * const geometry = new THREE.IcosahedronGeometry();
  26453. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26454. * const icosahedron = new THREE.Mesh( geometry, material );
  26455. * scene.add( icosahedron );
  26456. * ```
  26457. *
  26458. * @augments PolyhedronGeometry
  26459. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26460. */
  26461. class IcosahedronGeometry extends PolyhedronGeometry {
  26462. /**
  26463. * Constructs a new icosahedron geometry.
  26464. *
  26465. * @param {number} [radius=1] - Radius of the icosahedron.
  26466. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26467. */
  26468. constructor( radius = 1, detail = 0 ) {
  26469. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26470. const vertices = [
  26471. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26472. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26473. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26474. ];
  26475. const indices = [
  26476. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26477. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26478. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26479. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26480. ];
  26481. super( vertices, indices, radius, detail );
  26482. this.type = 'IcosahedronGeometry';
  26483. /**
  26484. * Holds the constructor parameters that have been
  26485. * used to generate the geometry. Any modification
  26486. * after instantiation does not change the geometry.
  26487. *
  26488. * @type {Object}
  26489. */
  26490. this.parameters = {
  26491. radius: radius,
  26492. detail: detail
  26493. };
  26494. }
  26495. /**
  26496. * Factory method for creating an instance of this class from the given
  26497. * JSON object.
  26498. *
  26499. * @param {Object} data - A JSON object representing the serialized geometry.
  26500. * @return {IcosahedronGeometry} A new instance.
  26501. */
  26502. static fromJSON( data ) {
  26503. return new IcosahedronGeometry( data.radius, data.detail );
  26504. }
  26505. }
  26506. /**
  26507. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26508. *
  26509. * ```js
  26510. * const points = [];
  26511. * for ( let i = 0; i < 10; i ++ ) {
  26512. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26513. * }
  26514. * const geometry = new THREE.LatheGeometry( points );
  26515. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26516. * const lathe = new THREE.Mesh( geometry, material );
  26517. * scene.add( lathe );
  26518. * ```
  26519. *
  26520. * @augments BufferGeometry
  26521. * @demo scenes/geometry-browser.html#LatheGeometry
  26522. */
  26523. class LatheGeometry extends BufferGeometry {
  26524. /**
  26525. * Constructs a new lathe geometry.
  26526. *
  26527. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26528. * must be greater than zero.
  26529. * @param {number} [segments=12] - The number of circumference segments to generate.
  26530. * @param {number} [phiStart=0] - The starting angle in radians.
  26531. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26532. * closed lathe, less than 2PI is a portion.
  26533. */
  26534. 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 ) {
  26535. super();
  26536. this.type = 'LatheGeometry';
  26537. /**
  26538. * Holds the constructor parameters that have been
  26539. * used to generate the geometry. Any modification
  26540. * after instantiation does not change the geometry.
  26541. *
  26542. * @type {Object}
  26543. */
  26544. this.parameters = {
  26545. points: points,
  26546. segments: segments,
  26547. phiStart: phiStart,
  26548. phiLength: phiLength
  26549. };
  26550. segments = Math.floor( segments );
  26551. // clamp phiLength so it's in range of [ 0, 2PI ]
  26552. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26553. // buffers
  26554. const indices = [];
  26555. const vertices = [];
  26556. const uvs = [];
  26557. const initNormals = [];
  26558. const normals = [];
  26559. // helper variables
  26560. const inverseSegments = 1.0 / segments;
  26561. const vertex = new Vector3();
  26562. const uv = new Vector2();
  26563. const normal = new Vector3();
  26564. const curNormal = new Vector3();
  26565. const prevNormal = new Vector3();
  26566. let dx = 0;
  26567. let dy = 0;
  26568. // pre-compute normals for initial "meridian"
  26569. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26570. switch ( j ) {
  26571. case 0: // special handling for 1st vertex on path
  26572. dx = points[ j + 1 ].x - points[ j ].x;
  26573. dy = points[ j + 1 ].y - points[ j ].y;
  26574. normal.x = dy * 1.0;
  26575. normal.y = - dx;
  26576. normal.z = dy * 0.0;
  26577. prevNormal.copy( normal );
  26578. normal.normalize();
  26579. initNormals.push( normal.x, normal.y, normal.z );
  26580. break;
  26581. case ( points.length - 1 ): // special handling for last Vertex on path
  26582. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26583. break;
  26584. default: // default handling for all vertices in between
  26585. dx = points[ j + 1 ].x - points[ j ].x;
  26586. dy = points[ j + 1 ].y - points[ j ].y;
  26587. normal.x = dy * 1.0;
  26588. normal.y = - dx;
  26589. normal.z = dy * 0.0;
  26590. curNormal.copy( normal );
  26591. normal.x += prevNormal.x;
  26592. normal.y += prevNormal.y;
  26593. normal.z += prevNormal.z;
  26594. normal.normalize();
  26595. initNormals.push( normal.x, normal.y, normal.z );
  26596. prevNormal.copy( curNormal );
  26597. }
  26598. }
  26599. // generate vertices, uvs and normals
  26600. for ( let i = 0; i <= segments; i ++ ) {
  26601. const phi = phiStart + i * inverseSegments * phiLength;
  26602. const sin = Math.sin( phi );
  26603. const cos = Math.cos( phi );
  26604. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26605. // vertex
  26606. vertex.x = points[ j ].x * sin;
  26607. vertex.y = points[ j ].y;
  26608. vertex.z = points[ j ].x * cos;
  26609. vertices.push( vertex.x, vertex.y, vertex.z );
  26610. // uv
  26611. uv.x = i / segments;
  26612. uv.y = j / ( points.length - 1 );
  26613. uvs.push( uv.x, uv.y );
  26614. // normal
  26615. const x = initNormals[ 3 * j + 0 ] * sin;
  26616. const y = initNormals[ 3 * j + 1 ];
  26617. const z = initNormals[ 3 * j + 0 ] * cos;
  26618. normals.push( x, y, z );
  26619. }
  26620. }
  26621. // indices
  26622. for ( let i = 0; i < segments; i ++ ) {
  26623. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26624. const base = j + i * points.length;
  26625. const a = base;
  26626. const b = base + points.length;
  26627. const c = base + points.length + 1;
  26628. const d = base + 1;
  26629. // faces
  26630. indices.push( a, b, d );
  26631. indices.push( c, d, b );
  26632. }
  26633. }
  26634. // build geometry
  26635. this.setIndex( indices );
  26636. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26637. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26638. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26639. }
  26640. copy( source ) {
  26641. super.copy( source );
  26642. this.parameters = Object.assign( {}, source.parameters );
  26643. return this;
  26644. }
  26645. /**
  26646. * Factory method for creating an instance of this class from the given
  26647. * JSON object.
  26648. *
  26649. * @param {Object} data - A JSON object representing the serialized geometry.
  26650. * @return {LatheGeometry} A new instance.
  26651. */
  26652. static fromJSON( data ) {
  26653. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26654. }
  26655. }
  26656. /**
  26657. * A geometry class for representing an octahedron.
  26658. *
  26659. * ```js
  26660. * const geometry = new THREE.OctahedronGeometry();
  26661. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26662. * const octahedron = new THREE.Mesh( geometry, material );
  26663. * scene.add( octahedron );
  26664. * ```
  26665. *
  26666. * @augments PolyhedronGeometry
  26667. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26668. */
  26669. class OctahedronGeometry extends PolyhedronGeometry {
  26670. /**
  26671. * Constructs a new octahedron geometry.
  26672. *
  26673. * @param {number} [radius=1] - Radius of the octahedron.
  26674. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26675. */
  26676. constructor( radius = 1, detail = 0 ) {
  26677. const vertices = [
  26678. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26679. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26680. ];
  26681. const indices = [
  26682. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26683. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26684. 1, 3, 4, 1, 4, 2
  26685. ];
  26686. super( vertices, indices, radius, detail );
  26687. this.type = 'OctahedronGeometry';
  26688. /**
  26689. * Holds the constructor parameters that have been
  26690. * used to generate the geometry. Any modification
  26691. * after instantiation does not change the geometry.
  26692. *
  26693. * @type {Object}
  26694. */
  26695. this.parameters = {
  26696. radius: radius,
  26697. detail: detail
  26698. };
  26699. }
  26700. /**
  26701. * Factory method for creating an instance of this class from the given
  26702. * JSON object.
  26703. *
  26704. * @param {Object} data - A JSON object representing the serialized geometry.
  26705. * @return {OctahedronGeometry} A new instance.
  26706. */
  26707. static fromJSON( data ) {
  26708. return new OctahedronGeometry( data.radius, data.detail );
  26709. }
  26710. }
  26711. /**
  26712. * A geometry class for representing a plane.
  26713. *
  26714. * ```js
  26715. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26716. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26717. * const plane = new THREE.Mesh( geometry, material );
  26718. * scene.add( plane );
  26719. * ```
  26720. *
  26721. * @augments BufferGeometry
  26722. * @demo scenes/geometry-browser.html#PlaneGeometry
  26723. */
  26724. class PlaneGeometry extends BufferGeometry {
  26725. /**
  26726. * Constructs a new plane geometry.
  26727. *
  26728. * @param {number} [width=1] - The width along the X axis.
  26729. * @param {number} [height=1] - The height along the Y axis
  26730. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26731. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26732. */
  26733. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26734. super();
  26735. this.type = 'PlaneGeometry';
  26736. /**
  26737. * Holds the constructor parameters that have been
  26738. * used to generate the geometry. Any modification
  26739. * after instantiation does not change the geometry.
  26740. *
  26741. * @type {Object}
  26742. */
  26743. this.parameters = {
  26744. width: width,
  26745. height: height,
  26746. widthSegments: widthSegments,
  26747. heightSegments: heightSegments
  26748. };
  26749. const width_half = width / 2;
  26750. const height_half = height / 2;
  26751. const gridX = Math.floor( widthSegments );
  26752. const gridY = Math.floor( heightSegments );
  26753. const gridX1 = gridX + 1;
  26754. const gridY1 = gridY + 1;
  26755. const segment_width = width / gridX;
  26756. const segment_height = height / gridY;
  26757. //
  26758. const indices = [];
  26759. const vertices = [];
  26760. const normals = [];
  26761. const uvs = [];
  26762. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26763. const y = iy * segment_height - height_half;
  26764. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26765. const x = ix * segment_width - width_half;
  26766. vertices.push( x, - y, 0 );
  26767. normals.push( 0, 0, 1 );
  26768. uvs.push( ix / gridX );
  26769. uvs.push( 1 - ( iy / gridY ) );
  26770. }
  26771. }
  26772. for ( let iy = 0; iy < gridY; iy ++ ) {
  26773. for ( let ix = 0; ix < gridX; ix ++ ) {
  26774. const a = ix + gridX1 * iy;
  26775. const b = ix + gridX1 * ( iy + 1 );
  26776. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26777. const d = ( ix + 1 ) + gridX1 * iy;
  26778. indices.push( a, b, d );
  26779. indices.push( b, c, d );
  26780. }
  26781. }
  26782. this.setIndex( indices );
  26783. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26784. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26785. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26786. }
  26787. copy( source ) {
  26788. super.copy( source );
  26789. this.parameters = Object.assign( {}, source.parameters );
  26790. return this;
  26791. }
  26792. /**
  26793. * Factory method for creating an instance of this class from the given
  26794. * JSON object.
  26795. *
  26796. * @param {Object} data - A JSON object representing the serialized geometry.
  26797. * @return {PlaneGeometry} A new instance.
  26798. */
  26799. static fromJSON( data ) {
  26800. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26801. }
  26802. }
  26803. /**
  26804. * A class for generating a two-dimensional ring geometry.
  26805. *
  26806. * ```js
  26807. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26808. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26809. * const mesh = new THREE.Mesh( geometry, material );
  26810. * scene.add( mesh );
  26811. * ```
  26812. *
  26813. * @augments BufferGeometry
  26814. * @demo scenes/geometry-browser.html#RingGeometry
  26815. */
  26816. class RingGeometry extends BufferGeometry {
  26817. /**
  26818. * Constructs a new ring geometry.
  26819. *
  26820. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26821. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26822. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26823. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26824. * @param {number} [thetaStart=0] - Starting angle in radians.
  26825. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26826. */
  26827. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26828. super();
  26829. this.type = 'RingGeometry';
  26830. /**
  26831. * Holds the constructor parameters that have been
  26832. * used to generate the geometry. Any modification
  26833. * after instantiation does not change the geometry.
  26834. *
  26835. * @type {Object}
  26836. */
  26837. this.parameters = {
  26838. innerRadius: innerRadius,
  26839. outerRadius: outerRadius,
  26840. thetaSegments: thetaSegments,
  26841. phiSegments: phiSegments,
  26842. thetaStart: thetaStart,
  26843. thetaLength: thetaLength
  26844. };
  26845. thetaSegments = Math.max( 3, thetaSegments );
  26846. phiSegments = Math.max( 1, phiSegments );
  26847. // buffers
  26848. const indices = [];
  26849. const vertices = [];
  26850. const normals = [];
  26851. const uvs = [];
  26852. // some helper variables
  26853. let radius = innerRadius;
  26854. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26855. const vertex = new Vector3();
  26856. const uv = new Vector2();
  26857. // generate vertices, normals and uvs
  26858. for ( let j = 0; j <= phiSegments; j ++ ) {
  26859. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26860. // values are generate from the inside of the ring to the outside
  26861. const segment = thetaStart + i / thetaSegments * thetaLength;
  26862. // vertex
  26863. vertex.x = radius * Math.cos( segment );
  26864. vertex.y = radius * Math.sin( segment );
  26865. vertices.push( vertex.x, vertex.y, vertex.z );
  26866. // normal
  26867. normals.push( 0, 0, 1 );
  26868. // uv
  26869. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26870. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26871. uvs.push( uv.x, uv.y );
  26872. }
  26873. // increase the radius for next row of vertices
  26874. radius += radiusStep;
  26875. }
  26876. // indices
  26877. for ( let j = 0; j < phiSegments; j ++ ) {
  26878. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26879. for ( let i = 0; i < thetaSegments; i ++ ) {
  26880. const segment = i + thetaSegmentLevel;
  26881. const a = segment;
  26882. const b = segment + thetaSegments + 1;
  26883. const c = segment + thetaSegments + 2;
  26884. const d = segment + 1;
  26885. // faces
  26886. indices.push( a, b, d );
  26887. indices.push( b, c, d );
  26888. }
  26889. }
  26890. // build geometry
  26891. this.setIndex( indices );
  26892. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26893. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26894. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26895. }
  26896. copy( source ) {
  26897. super.copy( source );
  26898. this.parameters = Object.assign( {}, source.parameters );
  26899. return this;
  26900. }
  26901. /**
  26902. * Factory method for creating an instance of this class from the given
  26903. * JSON object.
  26904. *
  26905. * @param {Object} data - A JSON object representing the serialized geometry.
  26906. * @return {RingGeometry} A new instance.
  26907. */
  26908. static fromJSON( data ) {
  26909. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26910. }
  26911. }
  26912. /**
  26913. * Creates an one-sided polygonal geometry from one or more path shapes.
  26914. *
  26915. * ```js
  26916. * const arcShape = new THREE.Shape()
  26917. * .moveTo( 5, 1 )
  26918. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26919. *
  26920. * const geometry = new THREE.ShapeGeometry( arcShape );
  26921. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26922. * const mesh = new THREE.Mesh( geometry, material ) ;
  26923. * scene.add( mesh );
  26924. * ```
  26925. *
  26926. * @augments BufferGeometry
  26927. * @demo scenes/geometry-browser.html#ShapeGeometry
  26928. */
  26929. class ShapeGeometry extends BufferGeometry {
  26930. /**
  26931. * Constructs a new shape geometry.
  26932. *
  26933. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26934. * @param {number} [curveSegments=12] - Number of segments per shape.
  26935. */
  26936. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26937. super();
  26938. this.type = 'ShapeGeometry';
  26939. /**
  26940. * Holds the constructor parameters that have been
  26941. * used to generate the geometry. Any modification
  26942. * after instantiation does not change the geometry.
  26943. *
  26944. * @type {Object}
  26945. */
  26946. this.parameters = {
  26947. shapes: shapes,
  26948. curveSegments: curveSegments
  26949. };
  26950. // buffers
  26951. const indices = [];
  26952. const vertices = [];
  26953. const normals = [];
  26954. const uvs = [];
  26955. // helper variables
  26956. let groupStart = 0;
  26957. let groupCount = 0;
  26958. // allow single and array values for "shapes" parameter
  26959. if ( Array.isArray( shapes ) === false ) {
  26960. addShape( shapes );
  26961. } else {
  26962. for ( let i = 0; i < shapes.length; i ++ ) {
  26963. addShape( shapes[ i ] );
  26964. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26965. groupStart += groupCount;
  26966. groupCount = 0;
  26967. }
  26968. }
  26969. // build geometry
  26970. this.setIndex( indices );
  26971. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26972. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26973. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26974. // helper functions
  26975. function addShape( shape ) {
  26976. const indexOffset = vertices.length / 3;
  26977. const points = shape.extractPoints( curveSegments );
  26978. let shapeVertices = points.shape;
  26979. const shapeHoles = points.holes;
  26980. // check direction of vertices
  26981. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26982. shapeVertices = shapeVertices.reverse();
  26983. }
  26984. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26985. const shapeHole = shapeHoles[ i ];
  26986. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26987. shapeHoles[ i ] = shapeHole.reverse();
  26988. }
  26989. }
  26990. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26991. // join vertices of inner and outer paths to a single array
  26992. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26993. const shapeHole = shapeHoles[ i ];
  26994. shapeVertices = shapeVertices.concat( shapeHole );
  26995. }
  26996. // vertices, normals, uvs
  26997. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26998. const vertex = shapeVertices[ i ];
  26999. vertices.push( vertex.x, vertex.y, 0 );
  27000. normals.push( 0, 0, 1 );
  27001. uvs.push( vertex.x, vertex.y ); // world uvs
  27002. }
  27003. // indices
  27004. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  27005. const face = faces[ i ];
  27006. const a = face[ 0 ] + indexOffset;
  27007. const b = face[ 1 ] + indexOffset;
  27008. const c = face[ 2 ] + indexOffset;
  27009. indices.push( a, b, c );
  27010. groupCount += 3;
  27011. }
  27012. }
  27013. }
  27014. copy( source ) {
  27015. super.copy( source );
  27016. this.parameters = Object.assign( {}, source.parameters );
  27017. return this;
  27018. }
  27019. toJSON() {
  27020. const data = super.toJSON();
  27021. const shapes = this.parameters.shapes;
  27022. return toJSON( shapes, data );
  27023. }
  27024. /**
  27025. * Factory method for creating an instance of this class from the given
  27026. * JSON object.
  27027. *
  27028. * @param {Object} data - A JSON object representing the serialized geometry.
  27029. * @param {Array<Shape>} shapes - An array of shapes.
  27030. * @return {ShapeGeometry} A new instance.
  27031. */
  27032. static fromJSON( data, shapes ) {
  27033. const geometryShapes = [];
  27034. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27035. const shape = shapes[ data.shapes[ j ] ];
  27036. geometryShapes.push( shape );
  27037. }
  27038. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27039. }
  27040. }
  27041. function toJSON( shapes, data ) {
  27042. data.shapes = [];
  27043. if ( Array.isArray( shapes ) ) {
  27044. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27045. const shape = shapes[ i ];
  27046. data.shapes.push( shape.uuid );
  27047. }
  27048. } else {
  27049. data.shapes.push( shapes.uuid );
  27050. }
  27051. return data;
  27052. }
  27053. /**
  27054. * A class for generating a sphere geometry.
  27055. *
  27056. * ```js
  27057. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27058. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27059. * const sphere = new THREE.Mesh( geometry, material );
  27060. * scene.add( sphere );
  27061. * ```
  27062. *
  27063. * @augments BufferGeometry
  27064. * @demo scenes/geometry-browser.html#SphereGeometry
  27065. */
  27066. class SphereGeometry extends BufferGeometry {
  27067. /**
  27068. * Constructs a new sphere geometry.
  27069. *
  27070. * @param {number} [radius=1] - The sphere radius.
  27071. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27072. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27073. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27074. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27075. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27076. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27077. */
  27078. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27079. super();
  27080. this.type = 'SphereGeometry';
  27081. /**
  27082. * Holds the constructor parameters that have been
  27083. * used to generate the geometry. Any modification
  27084. * after instantiation does not change the geometry.
  27085. *
  27086. * @type {Object}
  27087. */
  27088. this.parameters = {
  27089. radius: radius,
  27090. widthSegments: widthSegments,
  27091. heightSegments: heightSegments,
  27092. phiStart: phiStart,
  27093. phiLength: phiLength,
  27094. thetaStart: thetaStart,
  27095. thetaLength: thetaLength
  27096. };
  27097. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27098. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27099. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27100. let index = 0;
  27101. const grid = [];
  27102. const vertex = new Vector3();
  27103. const normal = new Vector3();
  27104. // buffers
  27105. const indices = [];
  27106. const vertices = [];
  27107. const normals = [];
  27108. const uvs = [];
  27109. // generate vertices, normals and uvs
  27110. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27111. const verticesRow = [];
  27112. const v = iy / heightSegments;
  27113. // special case for the poles
  27114. let uOffset = 0;
  27115. if ( iy === 0 && thetaStart === 0 ) {
  27116. uOffset = 0.5 / widthSegments;
  27117. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27118. uOffset = -0.5 / widthSegments;
  27119. }
  27120. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27121. const u = ix / widthSegments;
  27122. // vertex
  27123. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27124. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27125. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27126. vertices.push( vertex.x, vertex.y, vertex.z );
  27127. // normal
  27128. normal.copy( vertex ).normalize();
  27129. normals.push( normal.x, normal.y, normal.z );
  27130. // uv
  27131. uvs.push( u + uOffset, 1 - v );
  27132. verticesRow.push( index ++ );
  27133. }
  27134. grid.push( verticesRow );
  27135. }
  27136. // indices
  27137. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27138. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27139. const a = grid[ iy ][ ix + 1 ];
  27140. const b = grid[ iy ][ ix ];
  27141. const c = grid[ iy + 1 ][ ix ];
  27142. const d = grid[ iy + 1 ][ ix + 1 ];
  27143. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27144. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27145. }
  27146. }
  27147. // build geometry
  27148. this.setIndex( indices );
  27149. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27150. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27151. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27152. }
  27153. copy( source ) {
  27154. super.copy( source );
  27155. this.parameters = Object.assign( {}, source.parameters );
  27156. return this;
  27157. }
  27158. /**
  27159. * Factory method for creating an instance of this class from the given
  27160. * JSON object.
  27161. *
  27162. * @param {Object} data - A JSON object representing the serialized geometry.
  27163. * @return {SphereGeometry} A new instance.
  27164. */
  27165. static fromJSON( data ) {
  27166. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27167. }
  27168. }
  27169. /**
  27170. * A geometry class for representing an tetrahedron.
  27171. *
  27172. * ```js
  27173. * const geometry = new THREE.TetrahedronGeometry();
  27174. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27175. * const tetrahedron = new THREE.Mesh( geometry, material );
  27176. * scene.add( tetrahedron );
  27177. * ```
  27178. *
  27179. * @augments PolyhedronGeometry
  27180. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27181. */
  27182. class TetrahedronGeometry extends PolyhedronGeometry {
  27183. /**
  27184. * Constructs a new tetrahedron geometry.
  27185. *
  27186. * @param {number} [radius=1] - Radius of the tetrahedron.
  27187. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27188. */
  27189. constructor( radius = 1, detail = 0 ) {
  27190. const vertices = [
  27191. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27192. ];
  27193. const indices = [
  27194. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27195. ];
  27196. super( vertices, indices, radius, detail );
  27197. this.type = 'TetrahedronGeometry';
  27198. /**
  27199. * Holds the constructor parameters that have been
  27200. * used to generate the geometry. Any modification
  27201. * after instantiation does not change the geometry.
  27202. *
  27203. * @type {Object}
  27204. */
  27205. this.parameters = {
  27206. radius: radius,
  27207. detail: detail
  27208. };
  27209. }
  27210. /**
  27211. * Factory method for creating an instance of this class from the given
  27212. * JSON object.
  27213. *
  27214. * @param {Object} data - A JSON object representing the serialized geometry.
  27215. * @return {TetrahedronGeometry} A new instance.
  27216. */
  27217. static fromJSON( data ) {
  27218. return new TetrahedronGeometry( data.radius, data.detail );
  27219. }
  27220. }
  27221. /**
  27222. * A geometry class for representing an torus.
  27223. *
  27224. * ```js
  27225. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27226. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27227. * const torus = new THREE.Mesh( geometry, material );
  27228. * scene.add( torus );
  27229. * ```
  27230. *
  27231. * @augments BufferGeometry
  27232. * @demo scenes/geometry-browser.html#TorusGeometry
  27233. */
  27234. class TorusGeometry extends BufferGeometry {
  27235. /**
  27236. * Constructs a new torus geometry.
  27237. *
  27238. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27239. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27240. * @param {number} [radialSegments=12] - The number of radial segments.
  27241. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27242. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27243. */
  27244. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27245. super();
  27246. this.type = 'TorusGeometry';
  27247. /**
  27248. * Holds the constructor parameters that have been
  27249. * used to generate the geometry. Any modification
  27250. * after instantiation does not change the geometry.
  27251. *
  27252. * @type {Object}
  27253. */
  27254. this.parameters = {
  27255. radius: radius,
  27256. tube: tube,
  27257. radialSegments: radialSegments,
  27258. tubularSegments: tubularSegments,
  27259. arc: arc
  27260. };
  27261. radialSegments = Math.floor( radialSegments );
  27262. tubularSegments = Math.floor( tubularSegments );
  27263. // buffers
  27264. const indices = [];
  27265. const vertices = [];
  27266. const normals = [];
  27267. const uvs = [];
  27268. // helper variables
  27269. const center = new Vector3();
  27270. const vertex = new Vector3();
  27271. const normal = new Vector3();
  27272. // generate vertices, normals and uvs
  27273. for ( let j = 0; j <= radialSegments; j ++ ) {
  27274. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27275. const u = i / tubularSegments * arc;
  27276. const v = j / radialSegments * Math.PI * 2;
  27277. // vertex
  27278. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27279. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27280. vertex.z = tube * Math.sin( v );
  27281. vertices.push( vertex.x, vertex.y, vertex.z );
  27282. // normal
  27283. center.x = radius * Math.cos( u );
  27284. center.y = radius * Math.sin( u );
  27285. normal.subVectors( vertex, center ).normalize();
  27286. normals.push( normal.x, normal.y, normal.z );
  27287. // uv
  27288. uvs.push( i / tubularSegments );
  27289. uvs.push( j / radialSegments );
  27290. }
  27291. }
  27292. // generate indices
  27293. for ( let j = 1; j <= radialSegments; j ++ ) {
  27294. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27295. // indices
  27296. const a = ( tubularSegments + 1 ) * j + i - 1;
  27297. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27298. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27299. const d = ( tubularSegments + 1 ) * j + i;
  27300. // faces
  27301. indices.push( a, b, d );
  27302. indices.push( b, c, d );
  27303. }
  27304. }
  27305. // build geometry
  27306. this.setIndex( indices );
  27307. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27308. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27309. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27310. }
  27311. copy( source ) {
  27312. super.copy( source );
  27313. this.parameters = Object.assign( {}, source.parameters );
  27314. return this;
  27315. }
  27316. /**
  27317. * Factory method for creating an instance of this class from the given
  27318. * JSON object.
  27319. *
  27320. * @param {Object} data - A JSON object representing the serialized geometry.
  27321. * @return {TorusGeometry} A new instance.
  27322. */
  27323. static fromJSON( data ) {
  27324. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27325. }
  27326. }
  27327. /**
  27328. * Creates a torus knot, the particular shape of which is defined by a pair
  27329. * of coprime integers, p and q. If p and q are not coprime, the result will
  27330. * be a torus link.
  27331. *
  27332. * ```js
  27333. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27334. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27335. * const torusKnot = new THREE.Mesh( geometry, material );
  27336. * scene.add( torusKnot );
  27337. * ```
  27338. *
  27339. * @augments BufferGeometry
  27340. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27341. */
  27342. class TorusKnotGeometry extends BufferGeometry {
  27343. /**
  27344. * Constructs a new torus knot geometry.
  27345. *
  27346. * @param {number} [radius=1] - Radius of the torus knot.
  27347. * @param {number} [tube=0.4] - Radius of the tube.
  27348. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27349. * @param {number} [radialSegments=8] - The number of radial segments.
  27350. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27351. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27352. */
  27353. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27354. super();
  27355. this.type = 'TorusKnotGeometry';
  27356. /**
  27357. * Holds the constructor parameters that have been
  27358. * used to generate the geometry. Any modification
  27359. * after instantiation does not change the geometry.
  27360. *
  27361. * @type {Object}
  27362. */
  27363. this.parameters = {
  27364. radius: radius,
  27365. tube: tube,
  27366. tubularSegments: tubularSegments,
  27367. radialSegments: radialSegments,
  27368. p: p,
  27369. q: q
  27370. };
  27371. tubularSegments = Math.floor( tubularSegments );
  27372. radialSegments = Math.floor( radialSegments );
  27373. // buffers
  27374. const indices = [];
  27375. const vertices = [];
  27376. const normals = [];
  27377. const uvs = [];
  27378. // helper variables
  27379. const vertex = new Vector3();
  27380. const normal = new Vector3();
  27381. const P1 = new Vector3();
  27382. const P2 = new Vector3();
  27383. const B = new Vector3();
  27384. const T = new Vector3();
  27385. const N = new Vector3();
  27386. // generate vertices, normals and uvs
  27387. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27388. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27389. const u = i / tubularSegments * p * Math.PI * 2;
  27390. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27391. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27392. calculatePositionOnCurve( u, p, q, radius, P1 );
  27393. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27394. // calculate orthonormal basis
  27395. T.subVectors( P2, P1 );
  27396. N.addVectors( P2, P1 );
  27397. B.crossVectors( T, N );
  27398. N.crossVectors( B, T );
  27399. // normalize B, N. T can be ignored, we don't use it
  27400. B.normalize();
  27401. N.normalize();
  27402. for ( let j = 0; j <= radialSegments; ++ j ) {
  27403. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27404. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27405. const v = j / radialSegments * Math.PI * 2;
  27406. const cx = - tube * Math.cos( v );
  27407. const cy = tube * Math.sin( v );
  27408. // now calculate the final vertex position.
  27409. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27410. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27411. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27412. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27413. vertices.push( vertex.x, vertex.y, vertex.z );
  27414. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27415. normal.subVectors( vertex, P1 ).normalize();
  27416. normals.push( normal.x, normal.y, normal.z );
  27417. // uv
  27418. uvs.push( i / tubularSegments );
  27419. uvs.push( j / radialSegments );
  27420. }
  27421. }
  27422. // generate indices
  27423. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27424. for ( let i = 1; i <= radialSegments; i ++ ) {
  27425. // indices
  27426. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27427. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27428. const c = ( radialSegments + 1 ) * j + i;
  27429. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27430. // faces
  27431. indices.push( a, b, d );
  27432. indices.push( b, c, d );
  27433. }
  27434. }
  27435. // build geometry
  27436. this.setIndex( indices );
  27437. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27438. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27439. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27440. // this function calculates the current position on the torus curve
  27441. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27442. const cu = Math.cos( u );
  27443. const su = Math.sin( u );
  27444. const quOverP = q / p * u;
  27445. const cs = Math.cos( quOverP );
  27446. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27447. position.y = radius * ( 2 + cs ) * su * 0.5;
  27448. position.z = radius * Math.sin( quOverP ) * 0.5;
  27449. }
  27450. }
  27451. copy( source ) {
  27452. super.copy( source );
  27453. this.parameters = Object.assign( {}, source.parameters );
  27454. return this;
  27455. }
  27456. /**
  27457. * Factory method for creating an instance of this class from the given
  27458. * JSON object.
  27459. *
  27460. * @param {Object} data - A JSON object representing the serialized geometry.
  27461. * @return {TorusKnotGeometry} A new instance.
  27462. */
  27463. static fromJSON( data ) {
  27464. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27465. }
  27466. }
  27467. /**
  27468. * Creates a tube that extrudes along a 3D curve.
  27469. *
  27470. * ```js
  27471. * class CustomSinCurve extends THREE.Curve {
  27472. *
  27473. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27474. *
  27475. * const tx = t * 3 - 1.5;
  27476. * const ty = Math.sin( 2 * Math.PI * t );
  27477. * const tz = 0;
  27478. *
  27479. * return optionalTarget.set( tx, ty, tz );
  27480. * }
  27481. *
  27482. * }
  27483. *
  27484. * const path = new CustomSinCurve( 10 );
  27485. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27486. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27487. * const mesh = new THREE.Mesh( geometry, material );
  27488. * scene.add( mesh );
  27489. * ```
  27490. *
  27491. * @augments BufferGeometry
  27492. * @demo scenes/geometry-browser.html#TubeGeometry
  27493. */
  27494. class TubeGeometry extends BufferGeometry {
  27495. /**
  27496. * Constructs a new tube geometry.
  27497. *
  27498. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27499. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27500. * @param {number} [radius=1] -The radius of the tube.
  27501. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27502. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27503. */
  27504. 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 ) {
  27505. super();
  27506. this.type = 'TubeGeometry';
  27507. /**
  27508. * Holds the constructor parameters that have been
  27509. * used to generate the geometry. Any modification
  27510. * after instantiation does not change the geometry.
  27511. *
  27512. * @type {Object}
  27513. */
  27514. this.parameters = {
  27515. path: path,
  27516. tubularSegments: tubularSegments,
  27517. radius: radius,
  27518. radialSegments: radialSegments,
  27519. closed: closed
  27520. };
  27521. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27522. // expose internals
  27523. this.tangents = frames.tangents;
  27524. this.normals = frames.normals;
  27525. this.binormals = frames.binormals;
  27526. // helper variables
  27527. const vertex = new Vector3();
  27528. const normal = new Vector3();
  27529. const uv = new Vector2();
  27530. let P = new Vector3();
  27531. // buffer
  27532. const vertices = [];
  27533. const normals = [];
  27534. const uvs = [];
  27535. const indices = [];
  27536. // create buffer data
  27537. generateBufferData();
  27538. // build geometry
  27539. this.setIndex( indices );
  27540. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27541. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27542. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27543. // functions
  27544. function generateBufferData() {
  27545. for ( let i = 0; i < tubularSegments; i ++ ) {
  27546. generateSegment( i );
  27547. }
  27548. // if the geometry is not closed, generate the last row of vertices and normals
  27549. // at the regular position on the given path
  27550. //
  27551. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27552. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27553. // uvs are generated in a separate function.
  27554. // this makes it easy compute correct values for closed geometries
  27555. generateUVs();
  27556. // finally create faces
  27557. generateIndices();
  27558. }
  27559. function generateSegment( i ) {
  27560. // we use getPointAt to sample evenly distributed points from the given path
  27561. P = path.getPointAt( i / tubularSegments, P );
  27562. // retrieve corresponding normal and binormal
  27563. const N = frames.normals[ i ];
  27564. const B = frames.binormals[ i ];
  27565. // generate normals and vertices for the current segment
  27566. for ( let j = 0; j <= radialSegments; j ++ ) {
  27567. const v = j / radialSegments * Math.PI * 2;
  27568. const sin = Math.sin( v );
  27569. const cos = - Math.cos( v );
  27570. // normal
  27571. normal.x = ( cos * N.x + sin * B.x );
  27572. normal.y = ( cos * N.y + sin * B.y );
  27573. normal.z = ( cos * N.z + sin * B.z );
  27574. normal.normalize();
  27575. normals.push( normal.x, normal.y, normal.z );
  27576. // vertex
  27577. vertex.x = P.x + radius * normal.x;
  27578. vertex.y = P.y + radius * normal.y;
  27579. vertex.z = P.z + radius * normal.z;
  27580. vertices.push( vertex.x, vertex.y, vertex.z );
  27581. }
  27582. }
  27583. function generateIndices() {
  27584. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27585. for ( let i = 1; i <= radialSegments; i ++ ) {
  27586. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27587. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27588. const c = ( radialSegments + 1 ) * j + i;
  27589. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27590. // faces
  27591. indices.push( a, b, d );
  27592. indices.push( b, c, d );
  27593. }
  27594. }
  27595. }
  27596. function generateUVs() {
  27597. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27598. for ( let j = 0; j <= radialSegments; j ++ ) {
  27599. uv.x = i / tubularSegments;
  27600. uv.y = j / radialSegments;
  27601. uvs.push( uv.x, uv.y );
  27602. }
  27603. }
  27604. }
  27605. }
  27606. copy( source ) {
  27607. super.copy( source );
  27608. this.parameters = Object.assign( {}, source.parameters );
  27609. return this;
  27610. }
  27611. toJSON() {
  27612. const data = super.toJSON();
  27613. data.path = this.parameters.path.toJSON();
  27614. return data;
  27615. }
  27616. /**
  27617. * Factory method for creating an instance of this class from the given
  27618. * JSON object.
  27619. *
  27620. * @param {Object} data - A JSON object representing the serialized geometry.
  27621. * @return {TubeGeometry} A new instance.
  27622. */
  27623. static fromJSON( data ) {
  27624. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27625. // User defined curves or instances of CurvePath will not be deserialized.
  27626. return new TubeGeometry(
  27627. new Curves[ data.path.type ]().fromJSON( data.path ),
  27628. data.tubularSegments,
  27629. data.radius,
  27630. data.radialSegments,
  27631. data.closed
  27632. );
  27633. }
  27634. }
  27635. /**
  27636. * Can be used as a helper object to visualize a geometry as a wireframe.
  27637. *
  27638. * ```js
  27639. * const geometry = new THREE.SphereGeometry();
  27640. *
  27641. * const wireframe = new THREE.WireframeGeometry( geometry );
  27642. *
  27643. * const line = new THREE.LineSegments( wireframe );
  27644. * line.material.depthWrite = false;
  27645. * line.material.opacity = 0.25;
  27646. * line.material.transparent = true;
  27647. *
  27648. * scene.add( line );
  27649. * ```
  27650. *
  27651. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27652. *
  27653. * @augments BufferGeometry
  27654. */
  27655. class WireframeGeometry extends BufferGeometry {
  27656. /**
  27657. * Constructs a new wireframe geometry.
  27658. *
  27659. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27660. */
  27661. constructor( geometry = null ) {
  27662. super();
  27663. this.type = 'WireframeGeometry';
  27664. /**
  27665. * Holds the constructor parameters that have been
  27666. * used to generate the geometry. Any modification
  27667. * after instantiation does not change the geometry.
  27668. *
  27669. * @type {Object}
  27670. */
  27671. this.parameters = {
  27672. geometry: geometry
  27673. };
  27674. if ( geometry !== null ) {
  27675. // buffer
  27676. const vertices = [];
  27677. const edges = new Set();
  27678. // helper variables
  27679. const start = new Vector3();
  27680. const end = new Vector3();
  27681. if ( geometry.index !== null ) {
  27682. // indexed BufferGeometry
  27683. const position = geometry.attributes.position;
  27684. const indices = geometry.index;
  27685. let groups = geometry.groups;
  27686. if ( groups.length === 0 ) {
  27687. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27688. }
  27689. // create a data structure that contains all edges without duplicates
  27690. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27691. const group = groups[ o ];
  27692. const groupStart = group.start;
  27693. const groupCount = group.count;
  27694. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27695. for ( let j = 0; j < 3; j ++ ) {
  27696. const index1 = indices.getX( i + j );
  27697. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27698. start.fromBufferAttribute( position, index1 );
  27699. end.fromBufferAttribute( position, index2 );
  27700. if ( isUniqueEdge( start, end, edges ) === true ) {
  27701. vertices.push( start.x, start.y, start.z );
  27702. vertices.push( end.x, end.y, end.z );
  27703. }
  27704. }
  27705. }
  27706. }
  27707. } else {
  27708. // non-indexed BufferGeometry
  27709. const position = geometry.attributes.position;
  27710. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27711. for ( let j = 0; j < 3; j ++ ) {
  27712. // three edges per triangle, an edge is represented as (index1, index2)
  27713. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27714. const index1 = 3 * i + j;
  27715. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27716. start.fromBufferAttribute( position, index1 );
  27717. end.fromBufferAttribute( position, index2 );
  27718. if ( isUniqueEdge( start, end, edges ) === true ) {
  27719. vertices.push( start.x, start.y, start.z );
  27720. vertices.push( end.x, end.y, end.z );
  27721. }
  27722. }
  27723. }
  27724. }
  27725. // build geometry
  27726. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27727. }
  27728. }
  27729. copy( source ) {
  27730. super.copy( source );
  27731. this.parameters = Object.assign( {}, source.parameters );
  27732. return this;
  27733. }
  27734. }
  27735. function isUniqueEdge( start, end, edges ) {
  27736. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27737. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27738. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27739. return false;
  27740. } else {
  27741. edges.add( hash1 );
  27742. edges.add( hash2 );
  27743. return true;
  27744. }
  27745. }
  27746. var Geometries = /*#__PURE__*/Object.freeze({
  27747. __proto__: null,
  27748. BoxGeometry: BoxGeometry,
  27749. CapsuleGeometry: CapsuleGeometry,
  27750. CircleGeometry: CircleGeometry,
  27751. ConeGeometry: ConeGeometry,
  27752. CylinderGeometry: CylinderGeometry,
  27753. DodecahedronGeometry: DodecahedronGeometry,
  27754. EdgesGeometry: EdgesGeometry,
  27755. ExtrudeGeometry: ExtrudeGeometry,
  27756. IcosahedronGeometry: IcosahedronGeometry,
  27757. LatheGeometry: LatheGeometry,
  27758. OctahedronGeometry: OctahedronGeometry,
  27759. PlaneGeometry: PlaneGeometry,
  27760. PolyhedronGeometry: PolyhedronGeometry,
  27761. RingGeometry: RingGeometry,
  27762. ShapeGeometry: ShapeGeometry,
  27763. SphereGeometry: SphereGeometry,
  27764. TetrahedronGeometry: TetrahedronGeometry,
  27765. TorusGeometry: TorusGeometry,
  27766. TorusKnotGeometry: TorusKnotGeometry,
  27767. TubeGeometry: TubeGeometry,
  27768. WireframeGeometry: WireframeGeometry
  27769. });
  27770. /**
  27771. * This material can receive shadows, but otherwise is completely transparent.
  27772. *
  27773. * ```js
  27774. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27775. * geometry.rotateX( - Math.PI / 2 );
  27776. *
  27777. * const material = new THREE.ShadowMaterial();
  27778. * material.opacity = 0.2;
  27779. *
  27780. * const plane = new THREE.Mesh( geometry, material );
  27781. * plane.position.y = -200;
  27782. * plane.receiveShadow = true;
  27783. * scene.add( plane );
  27784. * ```
  27785. *
  27786. * @augments Material
  27787. */
  27788. class ShadowMaterial extends Material {
  27789. /**
  27790. * Constructs a new shadow material.
  27791. *
  27792. * @param {Object} [parameters] - An object with one or more properties
  27793. * defining the material's appearance. Any property of the material
  27794. * (including any property from inherited materials) can be passed
  27795. * in here. Color values can be passed any type of value accepted
  27796. * by {@link Color#set}.
  27797. */
  27798. constructor( parameters ) {
  27799. super();
  27800. /**
  27801. * This flag can be used for type testing.
  27802. *
  27803. * @type {boolean}
  27804. * @readonly
  27805. * @default true
  27806. */
  27807. this.isShadowMaterial = true;
  27808. this.type = 'ShadowMaterial';
  27809. /**
  27810. * Color of the material.
  27811. *
  27812. * @type {Color}
  27813. * @default (0,0,0)
  27814. */
  27815. this.color = new Color( 0x000000 );
  27816. /**
  27817. * Overwritten since shadow materials are transparent
  27818. * by default.
  27819. *
  27820. * @type {boolean}
  27821. * @default true
  27822. */
  27823. this.transparent = true;
  27824. /**
  27825. * Whether the material is affected by fog or not.
  27826. *
  27827. * @type {boolean}
  27828. * @default true
  27829. */
  27830. this.fog = true;
  27831. this.setValues( parameters );
  27832. }
  27833. copy( source ) {
  27834. super.copy( source );
  27835. this.color.copy( source.color );
  27836. this.fog = source.fog;
  27837. return this;
  27838. }
  27839. }
  27840. /**
  27841. * This class works just like {@link ShaderMaterial}, except that definitions
  27842. * of built-in uniforms and attributes are not automatically prepended to the
  27843. * GLSL shader code.
  27844. *
  27845. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27846. *
  27847. * @augments ShaderMaterial
  27848. */
  27849. class RawShaderMaterial extends ShaderMaterial {
  27850. /**
  27851. * Constructs a new raw shader material.
  27852. *
  27853. * @param {Object} [parameters] - An object with one or more properties
  27854. * defining the material's appearance. Any property of the material
  27855. * (including any property from inherited materials) can be passed
  27856. * in here. Color values can be passed any type of value accepted
  27857. * by {@link Color#set}.
  27858. */
  27859. constructor( parameters ) {
  27860. super( parameters );
  27861. /**
  27862. * This flag can be used for type testing.
  27863. *
  27864. * @type {boolean}
  27865. * @readonly
  27866. * @default true
  27867. */
  27868. this.isRawShaderMaterial = true;
  27869. this.type = 'RawShaderMaterial';
  27870. }
  27871. }
  27872. /**
  27873. * A standard physically based material, using Metallic-Roughness workflow.
  27874. *
  27875. * Physically based rendering (PBR) has recently become the standard in many
  27876. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27877. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27878. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27879. *
  27880. * This approach differs from older approaches in that instead of using
  27881. * approximations for the way in which light interacts with a surface, a
  27882. * physically correct model is used. The idea is that, instead of tweaking
  27883. * materials to look good under specific lighting, a material can be created
  27884. * that will react 'correctly' under all lighting scenarios.
  27885. *
  27886. * In practice this gives a more accurate and realistic looking result than
  27887. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27888. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27889. * shading.
  27890. *
  27891. * Note that for best results you should always specify an environment map when using this material.
  27892. *
  27893. * For a non-technical introduction to the concept of PBR and how to set up a
  27894. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27895. *
  27896. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27897. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27898. *
  27899. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27900. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27901. * (pdf), by Brent Burley.
  27902. *
  27903. * @augments Material
  27904. * @demo scenes/material-browser.html#MeshStandardMaterial
  27905. */
  27906. class MeshStandardMaterial extends Material {
  27907. /**
  27908. * Constructs a new mesh standard material.
  27909. *
  27910. * @param {Object} [parameters] - An object with one or more properties
  27911. * defining the material's appearance. Any property of the material
  27912. * (including any property from inherited materials) can be passed
  27913. * in here. Color values can be passed any type of value accepted
  27914. * by {@link Color#set}.
  27915. */
  27916. constructor( parameters ) {
  27917. super();
  27918. /**
  27919. * This flag can be used for type testing.
  27920. *
  27921. * @type {boolean}
  27922. * @readonly
  27923. * @default true
  27924. */
  27925. this.isMeshStandardMaterial = true;
  27926. this.type = 'MeshStandardMaterial';
  27927. this.defines = { 'STANDARD': '' };
  27928. /**
  27929. * Color of the material.
  27930. *
  27931. * @type {Color}
  27932. * @default (1,1,1)
  27933. */
  27934. this.color = new Color( 0xffffff ); // diffuse
  27935. /**
  27936. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27937. * means fully diffuse. If `roughnessMap` is also provided,
  27938. * both values are multiplied.
  27939. *
  27940. * @type {number}
  27941. * @default 1
  27942. */
  27943. this.roughness = 1.0;
  27944. /**
  27945. * How much the material is like a metal. Non-metallic materials such as wood
  27946. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27947. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27948. * If `metalnessMap` is also provided, both values are multiplied.
  27949. *
  27950. * @type {number}
  27951. * @default 0
  27952. */
  27953. this.metalness = 0.0;
  27954. /**
  27955. * The color map. May optionally include an alpha channel, typically combined
  27956. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27957. * color is modulated by the diffuse `color`.
  27958. *
  27959. * @type {?Texture}
  27960. * @default null
  27961. */
  27962. this.map = null;
  27963. /**
  27964. * The light map. Requires a second set of UVs.
  27965. *
  27966. * @type {?Texture}
  27967. * @default null
  27968. */
  27969. this.lightMap = null;
  27970. /**
  27971. * Intensity of the baked light.
  27972. *
  27973. * @type {number}
  27974. * @default 1
  27975. */
  27976. this.lightMapIntensity = 1.0;
  27977. /**
  27978. * The red channel of this texture is used as the ambient occlusion map.
  27979. * Requires a second set of UVs.
  27980. *
  27981. * @type {?Texture}
  27982. * @default null
  27983. */
  27984. this.aoMap = null;
  27985. /**
  27986. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27987. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27988. * red channel is also `1`, ambient light is fully occluded on a surface.
  27989. *
  27990. * @type {number}
  27991. * @default 1
  27992. */
  27993. this.aoMapIntensity = 1.0;
  27994. /**
  27995. * Emissive (light) color of the material, essentially a solid color
  27996. * unaffected by other lighting.
  27997. *
  27998. * @type {Color}
  27999. * @default (0,0,0)
  28000. */
  28001. this.emissive = new Color( 0x000000 );
  28002. /**
  28003. * Intensity of the emissive light. Modulates the emissive color.
  28004. *
  28005. * @type {number}
  28006. * @default 1
  28007. */
  28008. this.emissiveIntensity = 1.0;
  28009. /**
  28010. * Set emissive (glow) map. The emissive map color is modulated by the
  28011. * emissive color and the emissive intensity. If you have an emissive map,
  28012. * be sure to set the emissive color to something other than black.
  28013. *
  28014. * @type {?Texture}
  28015. * @default null
  28016. */
  28017. this.emissiveMap = null;
  28018. /**
  28019. * The texture to create a bump map. The black and white values map to the
  28020. * perceived depth in relation to the lights. Bump doesn't actually affect
  28021. * the geometry of the object, only the lighting. If a normal map is defined
  28022. * this will be ignored.
  28023. *
  28024. * @type {?Texture}
  28025. * @default null
  28026. */
  28027. this.bumpMap = null;
  28028. /**
  28029. * How much the bump map affects the material. Typical range is `[0,1]`.
  28030. *
  28031. * @type {number}
  28032. * @default 1
  28033. */
  28034. this.bumpScale = 1;
  28035. /**
  28036. * The texture to create a normal map. The RGB values affect the surface
  28037. * normal for each pixel fragment and change the way the color is lit. Normal
  28038. * maps do not change the actual shape of the surface, only the lighting. In
  28039. * case the material has a normal map authored using the left handed
  28040. * convention, the `y` component of `normalScale` should be negated to compensate
  28041. * for the different handedness.
  28042. *
  28043. * @type {?Texture}
  28044. * @default null
  28045. */
  28046. this.normalMap = null;
  28047. /**
  28048. * The type of normal map.
  28049. *
  28050. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28051. * @default TangentSpaceNormalMap
  28052. */
  28053. this.normalMapType = TangentSpaceNormalMap;
  28054. /**
  28055. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28056. *
  28057. * @type {Vector2}
  28058. * @default (1,1)
  28059. */
  28060. this.normalScale = new Vector2( 1, 1 );
  28061. /**
  28062. * The displacement map affects the position of the mesh's vertices. Unlike
  28063. * other maps which only affect the light and shade of the material the
  28064. * displaced vertices can cast shadows, block other objects, and otherwise
  28065. * act as real geometry. The displacement texture is an image where the value
  28066. * of each pixel (white being the highest) is mapped against, and
  28067. * repositions, the vertices of the mesh.
  28068. *
  28069. * @type {?Texture}
  28070. * @default null
  28071. */
  28072. this.displacementMap = null;
  28073. /**
  28074. * How much the displacement map affects the mesh (where black is no
  28075. * displacement, and white is maximum displacement). Without a displacement
  28076. * map set, this value is not applied.
  28077. *
  28078. * @type {number}
  28079. * @default 0
  28080. */
  28081. this.displacementScale = 1;
  28082. /**
  28083. * The offset of the displacement map's values on the mesh's vertices.
  28084. * The bias is added to the scaled sample of the displacement map.
  28085. * Without a displacement map set, this value is not applied.
  28086. *
  28087. * @type {number}
  28088. * @default 0
  28089. */
  28090. this.displacementBias = 0;
  28091. /**
  28092. * The green channel of this texture is used to alter the roughness of the
  28093. * material.
  28094. *
  28095. * @type {?Texture}
  28096. * @default null
  28097. */
  28098. this.roughnessMap = null;
  28099. /**
  28100. * The blue channel of this texture is used to alter the metalness of the
  28101. * material.
  28102. *
  28103. * @type {?Texture}
  28104. * @default null
  28105. */
  28106. this.metalnessMap = null;
  28107. /**
  28108. * The alpha map is a grayscale texture that controls the opacity across the
  28109. * surface (black: fully transparent; white: fully opaque).
  28110. *
  28111. * Only the color of the texture is used, ignoring the alpha channel if one
  28112. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28113. * when sampling this texture due to the extra bit of precision provided for
  28114. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28115. * luminance/alpha textures will also still work as expected.
  28116. *
  28117. * @type {?Texture}
  28118. * @default null
  28119. */
  28120. this.alphaMap = null;
  28121. /**
  28122. * The environment map. To ensure a physically correct rendering, environment maps
  28123. * are internally pre-processed with {@link PMREMGenerator}.
  28124. *
  28125. * @type {?Texture}
  28126. * @default null
  28127. */
  28128. this.envMap = null;
  28129. /**
  28130. * The rotation of the environment map in radians.
  28131. *
  28132. * @type {Euler}
  28133. * @default (0,0,0)
  28134. */
  28135. this.envMapRotation = new Euler();
  28136. /**
  28137. * Scales the effect of the environment map by multiplying its color.
  28138. *
  28139. * @type {number}
  28140. * @default 1
  28141. */
  28142. this.envMapIntensity = 1.0;
  28143. /**
  28144. * Renders the geometry as a wireframe.
  28145. *
  28146. * @type {boolean}
  28147. * @default false
  28148. */
  28149. this.wireframe = false;
  28150. /**
  28151. * Controls the thickness of the wireframe.
  28152. *
  28153. * Can only be used with {@link SVGRenderer}.
  28154. *
  28155. * @type {number}
  28156. * @default 1
  28157. */
  28158. this.wireframeLinewidth = 1;
  28159. /**
  28160. * Defines appearance of wireframe ends.
  28161. *
  28162. * Can only be used with {@link SVGRenderer}.
  28163. *
  28164. * @type {('round'|'bevel'|'miter')}
  28165. * @default 'round'
  28166. */
  28167. this.wireframeLinecap = 'round';
  28168. /**
  28169. * Defines appearance of wireframe joints.
  28170. *
  28171. * Can only be used with {@link SVGRenderer}.
  28172. *
  28173. * @type {('round'|'bevel'|'miter')}
  28174. * @default 'round'
  28175. */
  28176. this.wireframeLinejoin = 'round';
  28177. /**
  28178. * Whether the material is rendered with flat shading or not.
  28179. *
  28180. * @type {boolean}
  28181. * @default false
  28182. */
  28183. this.flatShading = false;
  28184. /**
  28185. * Whether the material is affected by fog or not.
  28186. *
  28187. * @type {boolean}
  28188. * @default true
  28189. */
  28190. this.fog = true;
  28191. this.setValues( parameters );
  28192. }
  28193. copy( source ) {
  28194. super.copy( source );
  28195. this.defines = { 'STANDARD': '' };
  28196. this.color.copy( source.color );
  28197. this.roughness = source.roughness;
  28198. this.metalness = source.metalness;
  28199. this.map = source.map;
  28200. this.lightMap = source.lightMap;
  28201. this.lightMapIntensity = source.lightMapIntensity;
  28202. this.aoMap = source.aoMap;
  28203. this.aoMapIntensity = source.aoMapIntensity;
  28204. this.emissive.copy( source.emissive );
  28205. this.emissiveMap = source.emissiveMap;
  28206. this.emissiveIntensity = source.emissiveIntensity;
  28207. this.bumpMap = source.bumpMap;
  28208. this.bumpScale = source.bumpScale;
  28209. this.normalMap = source.normalMap;
  28210. this.normalMapType = source.normalMapType;
  28211. this.normalScale.copy( source.normalScale );
  28212. this.displacementMap = source.displacementMap;
  28213. this.displacementScale = source.displacementScale;
  28214. this.displacementBias = source.displacementBias;
  28215. this.roughnessMap = source.roughnessMap;
  28216. this.metalnessMap = source.metalnessMap;
  28217. this.alphaMap = source.alphaMap;
  28218. this.envMap = source.envMap;
  28219. this.envMapRotation.copy( source.envMapRotation );
  28220. this.envMapIntensity = source.envMapIntensity;
  28221. this.wireframe = source.wireframe;
  28222. this.wireframeLinewidth = source.wireframeLinewidth;
  28223. this.wireframeLinecap = source.wireframeLinecap;
  28224. this.wireframeLinejoin = source.wireframeLinejoin;
  28225. this.flatShading = source.flatShading;
  28226. this.fog = source.fog;
  28227. return this;
  28228. }
  28229. }
  28230. /**
  28231. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28232. * physically-based rendering properties:
  28233. *
  28234. * - Anisotropy: Ability to represent the anisotropic property of materials
  28235. * as observable with brushed metals.
  28236. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28237. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28238. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28239. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28240. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28241. * wings of many insects.
  28242. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28243. * transparent materials are less reflective. Physically-based transmission provides a more
  28244. * realistic option for thin, transparent surfaces like glass.
  28245. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28246. * - Sheen: Can be used for representing cloth and fabric materials.
  28247. *
  28248. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28249. * higher performance cost, per pixel, than other three.js materials. Most
  28250. * effects are disabled by default, and add cost as they are enabled. For
  28251. * best results, always specify an environment map when using this material.
  28252. *
  28253. * @augments MeshStandardMaterial
  28254. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28255. */
  28256. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28257. /**
  28258. * Constructs a new mesh physical material.
  28259. *
  28260. * @param {Object} [parameters] - An object with one or more properties
  28261. * defining the material's appearance. Any property of the material
  28262. * (including any property from inherited materials) can be passed
  28263. * in here. Color values can be passed any type of value accepted
  28264. * by {@link Color#set}.
  28265. */
  28266. constructor( parameters ) {
  28267. super();
  28268. /**
  28269. * This flag can be used for type testing.
  28270. *
  28271. * @type {boolean}
  28272. * @readonly
  28273. * @default true
  28274. */
  28275. this.isMeshPhysicalMaterial = true;
  28276. this.defines = {
  28277. 'STANDARD': '',
  28278. 'PHYSICAL': ''
  28279. };
  28280. this.type = 'MeshPhysicalMaterial';
  28281. /**
  28282. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28283. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28284. * property provides additional rotation to the vectors in the texture.
  28285. *
  28286. * @type {number}
  28287. * @default 1
  28288. */
  28289. this.anisotropyRotation = 0;
  28290. /**
  28291. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28292. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28293. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28294. *
  28295. * @type {?Texture}
  28296. * @default null
  28297. */
  28298. this.anisotropyMap = null;
  28299. /**
  28300. * The red channel of this texture is multiplied against `clearcoat`,
  28301. * for per-pixel control over a coating's intensity.
  28302. *
  28303. * @type {?Texture}
  28304. * @default null
  28305. */
  28306. this.clearcoatMap = null;
  28307. /**
  28308. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28309. *
  28310. * @type {number}
  28311. * @default 0
  28312. */
  28313. this.clearcoatRoughness = 0.0;
  28314. /**
  28315. * The green channel of this texture is multiplied against
  28316. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28317. *
  28318. * @type {?Texture}
  28319. * @default null
  28320. */
  28321. this.clearcoatRoughnessMap = null;
  28322. /**
  28323. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28324. * `(0,0)` to `(1,1)`.
  28325. *
  28326. * @type {Vector2}
  28327. * @default (1,1)
  28328. */
  28329. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28330. /**
  28331. * Can be used to enable independent normals for the clear coat layer.
  28332. *
  28333. * @type {?Texture}
  28334. * @default null
  28335. */
  28336. this.clearcoatNormalMap = null;
  28337. /**
  28338. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28339. *
  28340. * @type {number}
  28341. * @default 1.5
  28342. */
  28343. this.ior = 1.5;
  28344. /**
  28345. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28346. * corresponds to an index-of-refraction of `1.5`.
  28347. *
  28348. * This models the reflectivity of non-metallic materials. It has no effect
  28349. * when `metalness` is `1.0`
  28350. *
  28351. * @name MeshPhysicalMaterial#reflectivity
  28352. * @type {number}
  28353. * @default 0.5
  28354. */
  28355. Object.defineProperty( this, 'reflectivity', {
  28356. get: function () {
  28357. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28358. },
  28359. set: function ( reflectivity ) {
  28360. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28361. }
  28362. } );
  28363. /**
  28364. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28365. * control over iridescence.
  28366. *
  28367. * @type {?Texture}
  28368. * @default null
  28369. */
  28370. this.iridescenceMap = null;
  28371. /**
  28372. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28373. * Between `1.0` to `2.333`.
  28374. *
  28375. * @type {number}
  28376. * @default 1.3
  28377. */
  28378. this.iridescenceIOR = 1.3;
  28379. /**
  28380. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28381. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28382. *
  28383. * @type {Array<number,number>}
  28384. * @default [100,400]
  28385. */
  28386. this.iridescenceThicknessRange = [ 100, 400 ];
  28387. /**
  28388. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28389. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28390. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28391. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28392. * - Values in-between will linearly interpolate between the elements of the array.
  28393. *
  28394. * @type {?Texture}
  28395. * @default null
  28396. */
  28397. this.iridescenceThicknessMap = null;
  28398. /**
  28399. * The sheen tint.
  28400. *
  28401. * @type {Color}
  28402. * @default (0,0,0)
  28403. */
  28404. this.sheenColor = new Color( 0x000000 );
  28405. /**
  28406. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28407. * over sheen tint.
  28408. *
  28409. * @type {?Texture}
  28410. * @default null
  28411. */
  28412. this.sheenColorMap = null;
  28413. /**
  28414. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28415. *
  28416. * @type {number}
  28417. * @default 1
  28418. */
  28419. this.sheenRoughness = 1.0;
  28420. /**
  28421. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28422. * over sheen roughness.
  28423. *
  28424. * @type {?Texture}
  28425. * @default null
  28426. */
  28427. this.sheenRoughnessMap = null;
  28428. /**
  28429. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28430. * optical transparency.
  28431. *
  28432. * @type {?Texture}
  28433. * @default null
  28434. */
  28435. this.transmissionMap = null;
  28436. /**
  28437. * The thickness of the volume beneath the surface. The value is given in the
  28438. * coordinate space of the mesh. If the value is `0` the material is
  28439. * thin-walled. Otherwise the material is a volume boundary.
  28440. *
  28441. * @type {number}
  28442. * @default 0
  28443. */
  28444. this.thickness = 0;
  28445. /**
  28446. * A texture that defines the thickness, stored in the green channel. This will
  28447. * be multiplied by `thickness`.
  28448. *
  28449. * @type {?Texture}
  28450. * @default null
  28451. */
  28452. this.thicknessMap = null;
  28453. /**
  28454. * Density of the medium given as the average distance that light travels in
  28455. * the medium before interacting with a particle. The value is given in world
  28456. * space units, and must be greater than zero.
  28457. *
  28458. * @type {number}
  28459. * @default Infinity
  28460. */
  28461. this.attenuationDistance = Infinity;
  28462. /**
  28463. * The color that white light turns into due to absorption when reaching the
  28464. * attenuation distance.
  28465. *
  28466. * @type {Color}
  28467. * @default (1,1,1)
  28468. */
  28469. this.attenuationColor = new Color( 1, 1, 1 );
  28470. /**
  28471. * A float that scales the amount of specular reflection for non-metals only.
  28472. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28473. *
  28474. * @type {number}
  28475. * @default 1
  28476. */
  28477. this.specularIntensity = 1.0;
  28478. /**
  28479. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28480. * for per-pixel control over specular intensity.
  28481. *
  28482. * @type {?Texture}
  28483. * @default null
  28484. */
  28485. this.specularIntensityMap = null;
  28486. /**
  28487. * Tints the specular reflection at normal incidence for non-metals only.
  28488. *
  28489. * @type {Color}
  28490. * @default (1,1,1)
  28491. */
  28492. this.specularColor = new Color( 1, 1, 1 );
  28493. /**
  28494. * The RGB channels of this texture are multiplied against `specularColor`,
  28495. * for per-pixel control over specular color.
  28496. *
  28497. * @type {?Texture}
  28498. * @default null
  28499. */
  28500. this.specularColorMap = null;
  28501. this._anisotropy = 0;
  28502. this._clearcoat = 0;
  28503. this._dispersion = 0;
  28504. this._iridescence = 0;
  28505. this._sheen = 0.0;
  28506. this._transmission = 0;
  28507. this.setValues( parameters );
  28508. }
  28509. /**
  28510. * The anisotropy strength, from `0.0` to `1.0`.
  28511. *
  28512. * @type {number}
  28513. * @default 0
  28514. */
  28515. get anisotropy() {
  28516. return this._anisotropy;
  28517. }
  28518. set anisotropy( value ) {
  28519. if ( this._anisotropy > 0 !== value > 0 ) {
  28520. this.version ++;
  28521. }
  28522. this._anisotropy = value;
  28523. }
  28524. /**
  28525. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28526. * clear coat related properties to enable multilayer materials that have a
  28527. * thin translucent layer over the base layer.
  28528. *
  28529. * @type {number}
  28530. * @default 0
  28531. */
  28532. get clearcoat() {
  28533. return this._clearcoat;
  28534. }
  28535. set clearcoat( value ) {
  28536. if ( this._clearcoat > 0 !== value > 0 ) {
  28537. this.version ++;
  28538. }
  28539. this._clearcoat = value;
  28540. }
  28541. /**
  28542. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28543. * the surface and the viewer, from `0.0` to `1.0`.
  28544. *
  28545. * @type {number}
  28546. * @default 0
  28547. */
  28548. get iridescence() {
  28549. return this._iridescence;
  28550. }
  28551. set iridescence( value ) {
  28552. if ( this._iridescence > 0 !== value > 0 ) {
  28553. this.version ++;
  28554. }
  28555. this._iridescence = value;
  28556. }
  28557. /**
  28558. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28559. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28560. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28561. *
  28562. * @type {number}
  28563. * @default 0
  28564. */
  28565. get dispersion() {
  28566. return this._dispersion;
  28567. }
  28568. set dispersion( value ) {
  28569. if ( this._dispersion > 0 !== value > 0 ) {
  28570. this.version ++;
  28571. }
  28572. this._dispersion = value;
  28573. }
  28574. /**
  28575. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28576. *
  28577. * @type {number}
  28578. * @default 0
  28579. */
  28580. get sheen() {
  28581. return this._sheen;
  28582. }
  28583. set sheen( value ) {
  28584. if ( this._sheen > 0 !== value > 0 ) {
  28585. this.version ++;
  28586. }
  28587. this._sheen = value;
  28588. }
  28589. /**
  28590. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28591. *
  28592. * Thin, transparent or semitransparent, plastic or glass materials remain
  28593. * largely reflective even if they are fully transmissive. The transmission
  28594. * property can be used to model these materials.
  28595. *
  28596. * When transmission is non-zero, `opacity` should be set to `1`.
  28597. *
  28598. * @type {number}
  28599. * @default 0
  28600. */
  28601. get transmission() {
  28602. return this._transmission;
  28603. }
  28604. set transmission( value ) {
  28605. if ( this._transmission > 0 !== value > 0 ) {
  28606. this.version ++;
  28607. }
  28608. this._transmission = value;
  28609. }
  28610. copy( source ) {
  28611. super.copy( source );
  28612. this.defines = {
  28613. 'STANDARD': '',
  28614. 'PHYSICAL': ''
  28615. };
  28616. this.anisotropy = source.anisotropy;
  28617. this.anisotropyRotation = source.anisotropyRotation;
  28618. this.anisotropyMap = source.anisotropyMap;
  28619. this.clearcoat = source.clearcoat;
  28620. this.clearcoatMap = source.clearcoatMap;
  28621. this.clearcoatRoughness = source.clearcoatRoughness;
  28622. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28623. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28624. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28625. this.dispersion = source.dispersion;
  28626. this.ior = source.ior;
  28627. this.iridescence = source.iridescence;
  28628. this.iridescenceMap = source.iridescenceMap;
  28629. this.iridescenceIOR = source.iridescenceIOR;
  28630. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28631. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28632. this.sheen = source.sheen;
  28633. this.sheenColor.copy( source.sheenColor );
  28634. this.sheenColorMap = source.sheenColorMap;
  28635. this.sheenRoughness = source.sheenRoughness;
  28636. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28637. this.transmission = source.transmission;
  28638. this.transmissionMap = source.transmissionMap;
  28639. this.thickness = source.thickness;
  28640. this.thicknessMap = source.thicknessMap;
  28641. this.attenuationDistance = source.attenuationDistance;
  28642. this.attenuationColor.copy( source.attenuationColor );
  28643. this.specularIntensity = source.specularIntensity;
  28644. this.specularIntensityMap = source.specularIntensityMap;
  28645. this.specularColor.copy( source.specularColor );
  28646. this.specularColorMap = source.specularColorMap;
  28647. return this;
  28648. }
  28649. }
  28650. /**
  28651. * A material for shiny surfaces with specular highlights.
  28652. *
  28653. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28654. * model for calculating reflectance. Unlike the Lambertian model used in the
  28655. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28656. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28657. *
  28658. * Performance will generally be greater when using this material over the
  28659. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28660. * some graphical accuracy.
  28661. *
  28662. * @augments Material
  28663. * @demo scenes/material-browser.html#MeshPhongMaterial
  28664. */
  28665. class MeshPhongMaterial extends Material {
  28666. /**
  28667. * Constructs a new mesh phong material.
  28668. *
  28669. * @param {Object} [parameters] - An object with one or more properties
  28670. * defining the material's appearance. Any property of the material
  28671. * (including any property from inherited materials) can be passed
  28672. * in here. Color values can be passed any type of value accepted
  28673. * by {@link Color#set}.
  28674. */
  28675. constructor( parameters ) {
  28676. super();
  28677. /**
  28678. * This flag can be used for type testing.
  28679. *
  28680. * @type {boolean}
  28681. * @readonly
  28682. * @default true
  28683. */
  28684. this.isMeshPhongMaterial = true;
  28685. this.type = 'MeshPhongMaterial';
  28686. /**
  28687. * Color of the material.
  28688. *
  28689. * @type {Color}
  28690. * @default (1,1,1)
  28691. */
  28692. this.color = new Color( 0xffffff ); // diffuse
  28693. /**
  28694. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28695. *
  28696. * This defines how shiny the material is and the color of its shine.
  28697. *
  28698. * @type {Color}
  28699. */
  28700. this.specular = new Color( 0x111111 );
  28701. /**
  28702. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28703. *
  28704. * @type {number}
  28705. * @default 30
  28706. */
  28707. this.shininess = 30;
  28708. /**
  28709. * The color map. May optionally include an alpha channel, typically combined
  28710. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28711. * color is modulated by the diffuse `color`.
  28712. *
  28713. * @type {?Texture}
  28714. * @default null
  28715. */
  28716. this.map = null;
  28717. /**
  28718. * The light map. Requires a second set of UVs.
  28719. *
  28720. * @type {?Texture}
  28721. * @default null
  28722. */
  28723. this.lightMap = null;
  28724. /**
  28725. * Intensity of the baked light.
  28726. *
  28727. * @type {number}
  28728. * @default 1
  28729. */
  28730. this.lightMapIntensity = 1.0;
  28731. /**
  28732. * The red channel of this texture is used as the ambient occlusion map.
  28733. * Requires a second set of UVs.
  28734. *
  28735. * @type {?Texture}
  28736. * @default null
  28737. */
  28738. this.aoMap = null;
  28739. /**
  28740. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28741. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28742. * red channel is also `1`, ambient light is fully occluded on a surface.
  28743. *
  28744. * @type {number}
  28745. * @default 1
  28746. */
  28747. this.aoMapIntensity = 1.0;
  28748. /**
  28749. * Emissive (light) color of the material, essentially a solid color
  28750. * unaffected by other lighting.
  28751. *
  28752. * @type {Color}
  28753. * @default (0,0,0)
  28754. */
  28755. this.emissive = new Color( 0x000000 );
  28756. /**
  28757. * Intensity of the emissive light. Modulates the emissive color.
  28758. *
  28759. * @type {number}
  28760. * @default 1
  28761. */
  28762. this.emissiveIntensity = 1.0;
  28763. /**
  28764. * Set emissive (glow) map. The emissive map color is modulated by the
  28765. * emissive color and the emissive intensity. If you have an emissive map,
  28766. * be sure to set the emissive color to something other than black.
  28767. *
  28768. * @type {?Texture}
  28769. * @default null
  28770. */
  28771. this.emissiveMap = null;
  28772. /**
  28773. * The texture to create a bump map. The black and white values map to the
  28774. * perceived depth in relation to the lights. Bump doesn't actually affect
  28775. * the geometry of the object, only the lighting. If a normal map is defined
  28776. * this will be ignored.
  28777. *
  28778. * @type {?Texture}
  28779. * @default null
  28780. */
  28781. this.bumpMap = null;
  28782. /**
  28783. * How much the bump map affects the material. Typical range is `[0,1]`.
  28784. *
  28785. * @type {number}
  28786. * @default 1
  28787. */
  28788. this.bumpScale = 1;
  28789. /**
  28790. * The texture to create a normal map. The RGB values affect the surface
  28791. * normal for each pixel fragment and change the way the color is lit. Normal
  28792. * maps do not change the actual shape of the surface, only the lighting. In
  28793. * case the material has a normal map authored using the left handed
  28794. * convention, the `y` component of `normalScale` should be negated to compensate
  28795. * for the different handedness.
  28796. *
  28797. * @type {?Texture}
  28798. * @default null
  28799. */
  28800. this.normalMap = null;
  28801. /**
  28802. * The type of normal map.
  28803. *
  28804. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28805. * @default TangentSpaceNormalMap
  28806. */
  28807. this.normalMapType = TangentSpaceNormalMap;
  28808. /**
  28809. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28810. *
  28811. * @type {Vector2}
  28812. * @default (1,1)
  28813. */
  28814. this.normalScale = new Vector2( 1, 1 );
  28815. /**
  28816. * The displacement map affects the position of the mesh's vertices. Unlike
  28817. * other maps which only affect the light and shade of the material the
  28818. * displaced vertices can cast shadows, block other objects, and otherwise
  28819. * act as real geometry. The displacement texture is an image where the value
  28820. * of each pixel (white being the highest) is mapped against, and
  28821. * repositions, the vertices of the mesh.
  28822. *
  28823. * @type {?Texture}
  28824. * @default null
  28825. */
  28826. this.displacementMap = null;
  28827. /**
  28828. * How much the displacement map affects the mesh (where black is no
  28829. * displacement, and white is maximum displacement). Without a displacement
  28830. * map set, this value is not applied.
  28831. *
  28832. * @type {number}
  28833. * @default 0
  28834. */
  28835. this.displacementScale = 1;
  28836. /**
  28837. * The offset of the displacement map's values on the mesh's vertices.
  28838. * The bias is added to the scaled sample of the displacement map.
  28839. * Without a displacement map set, this value is not applied.
  28840. *
  28841. * @type {number}
  28842. * @default 0
  28843. */
  28844. this.displacementBias = 0;
  28845. /**
  28846. * The specular map value affects both how much the specular surface
  28847. * highlight contributes and how much of the environment map affects the
  28848. * surface.
  28849. *
  28850. * @type {?Texture}
  28851. * @default null
  28852. */
  28853. this.specularMap = null;
  28854. /**
  28855. * The alpha map is a grayscale texture that controls the opacity across the
  28856. * surface (black: fully transparent; white: fully opaque).
  28857. *
  28858. * Only the color of the texture is used, ignoring the alpha channel if one
  28859. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28860. * when sampling this texture due to the extra bit of precision provided for
  28861. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28862. * luminance/alpha textures will also still work as expected.
  28863. *
  28864. * @type {?Texture}
  28865. * @default null
  28866. */
  28867. this.alphaMap = null;
  28868. /**
  28869. * The environment map.
  28870. *
  28871. * @type {?Texture}
  28872. * @default null
  28873. */
  28874. this.envMap = null;
  28875. /**
  28876. * The rotation of the environment map in radians.
  28877. *
  28878. * @type {Euler}
  28879. * @default (0,0,0)
  28880. */
  28881. this.envMapRotation = new Euler();
  28882. /**
  28883. * How to combine the result of the surface's color with the environment map, if any.
  28884. *
  28885. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28886. * blend between the two colors.
  28887. *
  28888. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28889. * @default MultiplyOperation
  28890. */
  28891. this.combine = MultiplyOperation;
  28892. /**
  28893. * How much the environment map affects the surface.
  28894. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28895. *
  28896. * @type {number}
  28897. * @default 1
  28898. */
  28899. this.reflectivity = 1;
  28900. /**
  28901. * The index of refraction (IOR) of air (approximately 1) divided by the
  28902. * index of refraction of the material. It is used with environment mapping
  28903. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28904. * The refraction ratio should not exceed `1`.
  28905. *
  28906. * @type {number}
  28907. * @default 0.98
  28908. */
  28909. this.refractionRatio = 0.98;
  28910. /**
  28911. * Renders the geometry as a wireframe.
  28912. *
  28913. * @type {boolean}
  28914. * @default false
  28915. */
  28916. this.wireframe = false;
  28917. /**
  28918. * Controls the thickness of the wireframe.
  28919. *
  28920. * Can only be used with {@link SVGRenderer}.
  28921. *
  28922. * @type {number}
  28923. * @default 1
  28924. */
  28925. this.wireframeLinewidth = 1;
  28926. /**
  28927. * Defines appearance of wireframe ends.
  28928. *
  28929. * Can only be used with {@link SVGRenderer}.
  28930. *
  28931. * @type {('round'|'bevel'|'miter')}
  28932. * @default 'round'
  28933. */
  28934. this.wireframeLinecap = 'round';
  28935. /**
  28936. * Defines appearance of wireframe joints.
  28937. *
  28938. * Can only be used with {@link SVGRenderer}.
  28939. *
  28940. * @type {('round'|'bevel'|'miter')}
  28941. * @default 'round'
  28942. */
  28943. this.wireframeLinejoin = 'round';
  28944. /**
  28945. * Whether the material is rendered with flat shading or not.
  28946. *
  28947. * @type {boolean}
  28948. * @default false
  28949. */
  28950. this.flatShading = false;
  28951. /**
  28952. * Whether the material is affected by fog or not.
  28953. *
  28954. * @type {boolean}
  28955. * @default true
  28956. */
  28957. this.fog = true;
  28958. this.setValues( parameters );
  28959. }
  28960. copy( source ) {
  28961. super.copy( source );
  28962. this.color.copy( source.color );
  28963. this.specular.copy( source.specular );
  28964. this.shininess = source.shininess;
  28965. this.map = source.map;
  28966. this.lightMap = source.lightMap;
  28967. this.lightMapIntensity = source.lightMapIntensity;
  28968. this.aoMap = source.aoMap;
  28969. this.aoMapIntensity = source.aoMapIntensity;
  28970. this.emissive.copy( source.emissive );
  28971. this.emissiveMap = source.emissiveMap;
  28972. this.emissiveIntensity = source.emissiveIntensity;
  28973. this.bumpMap = source.bumpMap;
  28974. this.bumpScale = source.bumpScale;
  28975. this.normalMap = source.normalMap;
  28976. this.normalMapType = source.normalMapType;
  28977. this.normalScale.copy( source.normalScale );
  28978. this.displacementMap = source.displacementMap;
  28979. this.displacementScale = source.displacementScale;
  28980. this.displacementBias = source.displacementBias;
  28981. this.specularMap = source.specularMap;
  28982. this.alphaMap = source.alphaMap;
  28983. this.envMap = source.envMap;
  28984. this.envMapRotation.copy( source.envMapRotation );
  28985. this.combine = source.combine;
  28986. this.reflectivity = source.reflectivity;
  28987. this.refractionRatio = source.refractionRatio;
  28988. this.wireframe = source.wireframe;
  28989. this.wireframeLinewidth = source.wireframeLinewidth;
  28990. this.wireframeLinecap = source.wireframeLinecap;
  28991. this.wireframeLinejoin = source.wireframeLinejoin;
  28992. this.flatShading = source.flatShading;
  28993. this.fog = source.fog;
  28994. return this;
  28995. }
  28996. }
  28997. /**
  28998. * A material implementing toon shading.
  28999. *
  29000. * @augments Material
  29001. * @demo scenes/material-browser.html#MeshToonMaterial
  29002. */
  29003. class MeshToonMaterial extends Material {
  29004. /**
  29005. * Constructs a new mesh toon material.
  29006. *
  29007. * @param {Object} [parameters] - An object with one or more properties
  29008. * defining the material's appearance. Any property of the material
  29009. * (including any property from inherited materials) can be passed
  29010. * in here. Color values can be passed any type of value accepted
  29011. * by {@link Color#set}.
  29012. */
  29013. constructor( parameters ) {
  29014. super();
  29015. /**
  29016. * This flag can be used for type testing.
  29017. *
  29018. * @type {boolean}
  29019. * @readonly
  29020. * @default true
  29021. */
  29022. this.isMeshToonMaterial = true;
  29023. this.defines = { 'TOON': '' };
  29024. this.type = 'MeshToonMaterial';
  29025. /**
  29026. * Color of the material.
  29027. *
  29028. * @type {Color}
  29029. * @default (1,1,1)
  29030. */
  29031. this.color = new Color( 0xffffff );
  29032. /**
  29033. * The color map. May optionally include an alpha channel, typically combined
  29034. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29035. * color is modulated by the diffuse `color`.
  29036. *
  29037. * @type {?Texture}
  29038. * @default null
  29039. */
  29040. this.map = null;
  29041. /**
  29042. * Gradient map for toon shading. It's required to set
  29043. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29044. * when using this type of texture.
  29045. *
  29046. * @type {?Texture}
  29047. * @default null
  29048. */
  29049. this.gradientMap = null;
  29050. /**
  29051. * The light map. Requires a second set of UVs.
  29052. *
  29053. * @type {?Texture}
  29054. * @default null
  29055. */
  29056. this.lightMap = null;
  29057. /**
  29058. * Intensity of the baked light.
  29059. *
  29060. * @type {number}
  29061. * @default 1
  29062. */
  29063. this.lightMapIntensity = 1.0;
  29064. /**
  29065. * The red channel of this texture is used as the ambient occlusion map.
  29066. * Requires a second set of UVs.
  29067. *
  29068. * @type {?Texture}
  29069. * @default null
  29070. */
  29071. this.aoMap = null;
  29072. /**
  29073. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29074. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29075. * red channel is also `1`, ambient light is fully occluded on a surface.
  29076. *
  29077. * @type {number}
  29078. * @default 1
  29079. */
  29080. this.aoMapIntensity = 1.0;
  29081. /**
  29082. * Emissive (light) color of the material, essentially a solid color
  29083. * unaffected by other lighting.
  29084. *
  29085. * @type {Color}
  29086. * @default (0,0,0)
  29087. */
  29088. this.emissive = new Color( 0x000000 );
  29089. /**
  29090. * Intensity of the emissive light. Modulates the emissive color.
  29091. *
  29092. * @type {number}
  29093. * @default 1
  29094. */
  29095. this.emissiveIntensity = 1.0;
  29096. /**
  29097. * Set emissive (glow) map. The emissive map color is modulated by the
  29098. * emissive color and the emissive intensity. If you have an emissive map,
  29099. * be sure to set the emissive color to something other than black.
  29100. *
  29101. * @type {?Texture}
  29102. * @default null
  29103. */
  29104. this.emissiveMap = null;
  29105. /**
  29106. * The texture to create a bump map. The black and white values map to the
  29107. * perceived depth in relation to the lights. Bump doesn't actually affect
  29108. * the geometry of the object, only the lighting. If a normal map is defined
  29109. * this will be ignored.
  29110. *
  29111. * @type {?Texture}
  29112. * @default null
  29113. */
  29114. this.bumpMap = null;
  29115. /**
  29116. * How much the bump map affects the material. Typical range is `[0,1]`.
  29117. *
  29118. * @type {number}
  29119. * @default 1
  29120. */
  29121. this.bumpScale = 1;
  29122. /**
  29123. * The texture to create a normal map. The RGB values affect the surface
  29124. * normal for each pixel fragment and change the way the color is lit. Normal
  29125. * maps do not change the actual shape of the surface, only the lighting. In
  29126. * case the material has a normal map authored using the left handed
  29127. * convention, the `y` component of `normalScale` should be negated to compensate
  29128. * for the different handedness.
  29129. *
  29130. * @type {?Texture}
  29131. * @default null
  29132. */
  29133. this.normalMap = null;
  29134. /**
  29135. * The type of normal map.
  29136. *
  29137. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29138. * @default TangentSpaceNormalMap
  29139. */
  29140. this.normalMapType = TangentSpaceNormalMap;
  29141. /**
  29142. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29143. *
  29144. * @type {Vector2}
  29145. * @default (1,1)
  29146. */
  29147. this.normalScale = new Vector2( 1, 1 );
  29148. /**
  29149. * The displacement map affects the position of the mesh's vertices. Unlike
  29150. * other maps which only affect the light and shade of the material the
  29151. * displaced vertices can cast shadows, block other objects, and otherwise
  29152. * act as real geometry. The displacement texture is an image where the value
  29153. * of each pixel (white being the highest) is mapped against, and
  29154. * repositions, the vertices of the mesh.
  29155. *
  29156. * @type {?Texture}
  29157. * @default null
  29158. */
  29159. this.displacementMap = null;
  29160. /**
  29161. * How much the displacement map affects the mesh (where black is no
  29162. * displacement, and white is maximum displacement). Without a displacement
  29163. * map set, this value is not applied.
  29164. *
  29165. * @type {number}
  29166. * @default 0
  29167. */
  29168. this.displacementScale = 1;
  29169. /**
  29170. * The offset of the displacement map's values on the mesh's vertices.
  29171. * The bias is added to the scaled sample of the displacement map.
  29172. * Without a displacement map set, this value is not applied.
  29173. *
  29174. * @type {number}
  29175. * @default 0
  29176. */
  29177. this.displacementBias = 0;
  29178. /**
  29179. * The alpha map is a grayscale texture that controls the opacity across the
  29180. * surface (black: fully transparent; white: fully opaque).
  29181. *
  29182. * Only the color of the texture is used, ignoring the alpha channel if one
  29183. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29184. * when sampling this texture due to the extra bit of precision provided for
  29185. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29186. * luminance/alpha textures will also still work as expected.
  29187. *
  29188. * @type {?Texture}
  29189. * @default null
  29190. */
  29191. this.alphaMap = null;
  29192. /**
  29193. * Renders the geometry as a wireframe.
  29194. *
  29195. * @type {boolean}
  29196. * @default false
  29197. */
  29198. this.wireframe = false;
  29199. /**
  29200. * Controls the thickness of the wireframe.
  29201. *
  29202. * Can only be used with {@link SVGRenderer}.
  29203. *
  29204. * @type {number}
  29205. * @default 1
  29206. */
  29207. this.wireframeLinewidth = 1;
  29208. /**
  29209. * Defines appearance of wireframe ends.
  29210. *
  29211. * Can only be used with {@link SVGRenderer}.
  29212. *
  29213. * @type {('round'|'bevel'|'miter')}
  29214. * @default 'round'
  29215. */
  29216. this.wireframeLinecap = 'round';
  29217. /**
  29218. * Defines appearance of wireframe joints.
  29219. *
  29220. * Can only be used with {@link SVGRenderer}.
  29221. *
  29222. * @type {('round'|'bevel'|'miter')}
  29223. * @default 'round'
  29224. */
  29225. this.wireframeLinejoin = 'round';
  29226. /**
  29227. * Whether the material is affected by fog or not.
  29228. *
  29229. * @type {boolean}
  29230. * @default true
  29231. */
  29232. this.fog = true;
  29233. this.setValues( parameters );
  29234. }
  29235. copy( source ) {
  29236. super.copy( source );
  29237. this.color.copy( source.color );
  29238. this.map = source.map;
  29239. this.gradientMap = source.gradientMap;
  29240. this.lightMap = source.lightMap;
  29241. this.lightMapIntensity = source.lightMapIntensity;
  29242. this.aoMap = source.aoMap;
  29243. this.aoMapIntensity = source.aoMapIntensity;
  29244. this.emissive.copy( source.emissive );
  29245. this.emissiveMap = source.emissiveMap;
  29246. this.emissiveIntensity = source.emissiveIntensity;
  29247. this.bumpMap = source.bumpMap;
  29248. this.bumpScale = source.bumpScale;
  29249. this.normalMap = source.normalMap;
  29250. this.normalMapType = source.normalMapType;
  29251. this.normalScale.copy( source.normalScale );
  29252. this.displacementMap = source.displacementMap;
  29253. this.displacementScale = source.displacementScale;
  29254. this.displacementBias = source.displacementBias;
  29255. this.alphaMap = source.alphaMap;
  29256. this.wireframe = source.wireframe;
  29257. this.wireframeLinewidth = source.wireframeLinewidth;
  29258. this.wireframeLinecap = source.wireframeLinecap;
  29259. this.wireframeLinejoin = source.wireframeLinejoin;
  29260. this.fog = source.fog;
  29261. return this;
  29262. }
  29263. }
  29264. /**
  29265. * A material that maps the normal vectors to RGB colors.
  29266. *
  29267. * @augments Material
  29268. * @demo scenes/material-browser.html#MeshNormalMaterial
  29269. */
  29270. class MeshNormalMaterial extends Material {
  29271. /**
  29272. * Constructs a new mesh normal material.
  29273. *
  29274. * @param {Object} [parameters] - An object with one or more properties
  29275. * defining the material's appearance. Any property of the material
  29276. * (including any property from inherited materials) can be passed
  29277. * in here. Color values can be passed any type of value accepted
  29278. * by {@link Color#set}.
  29279. */
  29280. constructor( parameters ) {
  29281. super();
  29282. /**
  29283. * This flag can be used for type testing.
  29284. *
  29285. * @type {boolean}
  29286. * @readonly
  29287. * @default true
  29288. */
  29289. this.isMeshNormalMaterial = true;
  29290. this.type = 'MeshNormalMaterial';
  29291. /**
  29292. * The texture to create a bump map. The black and white values map to the
  29293. * perceived depth in relation to the lights. Bump doesn't actually affect
  29294. * the geometry of the object, only the lighting. If a normal map is defined
  29295. * this will be ignored.
  29296. *
  29297. * @type {?Texture}
  29298. * @default null
  29299. */
  29300. this.bumpMap = null;
  29301. /**
  29302. * How much the bump map affects the material. Typical range is `[0,1]`.
  29303. *
  29304. * @type {number}
  29305. * @default 1
  29306. */
  29307. this.bumpScale = 1;
  29308. /**
  29309. * The texture to create a normal map. The RGB values affect the surface
  29310. * normal for each pixel fragment and change the way the color is lit. Normal
  29311. * maps do not change the actual shape of the surface, only the lighting. In
  29312. * case the material has a normal map authored using the left handed
  29313. * convention, the `y` component of `normalScale` should be negated to compensate
  29314. * for the different handedness.
  29315. *
  29316. * @type {?Texture}
  29317. * @default null
  29318. */
  29319. this.normalMap = null;
  29320. /**
  29321. * The type of normal map.
  29322. *
  29323. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29324. * @default TangentSpaceNormalMap
  29325. */
  29326. this.normalMapType = TangentSpaceNormalMap;
  29327. /**
  29328. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29329. *
  29330. * @type {Vector2}
  29331. * @default (1,1)
  29332. */
  29333. this.normalScale = new Vector2( 1, 1 );
  29334. /**
  29335. * The displacement map affects the position of the mesh's vertices. Unlike
  29336. * other maps which only affect the light and shade of the material the
  29337. * displaced vertices can cast shadows, block other objects, and otherwise
  29338. * act as real geometry. The displacement texture is an image where the value
  29339. * of each pixel (white being the highest) is mapped against, and
  29340. * repositions, the vertices of the mesh.
  29341. *
  29342. * @type {?Texture}
  29343. * @default null
  29344. */
  29345. this.displacementMap = null;
  29346. /**
  29347. * How much the displacement map affects the mesh (where black is no
  29348. * displacement, and white is maximum displacement). Without a displacement
  29349. * map set, this value is not applied.
  29350. *
  29351. * @type {number}
  29352. * @default 0
  29353. */
  29354. this.displacementScale = 1;
  29355. /**
  29356. * The offset of the displacement map's values on the mesh's vertices.
  29357. * The bias is added to the scaled sample of the displacement map.
  29358. * Without a displacement map set, this value is not applied.
  29359. *
  29360. * @type {number}
  29361. * @default 0
  29362. */
  29363. this.displacementBias = 0;
  29364. /**
  29365. * Renders the geometry as a wireframe.
  29366. *
  29367. * @type {boolean}
  29368. * @default false
  29369. */
  29370. this.wireframe = false;
  29371. /**
  29372. * Controls the thickness of the wireframe.
  29373. *
  29374. * WebGL and WebGPU ignore this property and always render
  29375. * 1 pixel wide lines.
  29376. *
  29377. * @type {number}
  29378. * @default 1
  29379. */
  29380. this.wireframeLinewidth = 1;
  29381. /**
  29382. * Whether the material is rendered with flat shading or not.
  29383. *
  29384. * @type {boolean}
  29385. * @default false
  29386. */
  29387. this.flatShading = false;
  29388. this.setValues( parameters );
  29389. }
  29390. copy( source ) {
  29391. super.copy( source );
  29392. this.bumpMap = source.bumpMap;
  29393. this.bumpScale = source.bumpScale;
  29394. this.normalMap = source.normalMap;
  29395. this.normalMapType = source.normalMapType;
  29396. this.normalScale.copy( source.normalScale );
  29397. this.displacementMap = source.displacementMap;
  29398. this.displacementScale = source.displacementScale;
  29399. this.displacementBias = source.displacementBias;
  29400. this.wireframe = source.wireframe;
  29401. this.wireframeLinewidth = source.wireframeLinewidth;
  29402. this.flatShading = source.flatShading;
  29403. return this;
  29404. }
  29405. }
  29406. /**
  29407. * A material for non-shiny surfaces, without specular highlights.
  29408. *
  29409. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29410. * model for calculating reflectance. This can simulate some surfaces (such
  29411. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29412. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29413. * shading.
  29414. *
  29415. * Due to the simplicity of the reflectance and illumination models,
  29416. * performance will be greater when using this material over the
  29417. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29418. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29419. *
  29420. * @augments Material
  29421. * @demo scenes/material-browser.html#MeshLambertMaterial
  29422. */
  29423. class MeshLambertMaterial extends Material {
  29424. /**
  29425. * Constructs a new mesh lambert material.
  29426. *
  29427. * @param {Object} [parameters] - An object with one or more properties
  29428. * defining the material's appearance. Any property of the material
  29429. * (including any property from inherited materials) can be passed
  29430. * in here. Color values can be passed any type of value accepted
  29431. * by {@link Color#set}.
  29432. */
  29433. constructor( parameters ) {
  29434. super();
  29435. /**
  29436. * This flag can be used for type testing.
  29437. *
  29438. * @type {boolean}
  29439. * @readonly
  29440. * @default true
  29441. */
  29442. this.isMeshLambertMaterial = true;
  29443. this.type = 'MeshLambertMaterial';
  29444. /**
  29445. * Color of the material.
  29446. *
  29447. * @type {Color}
  29448. * @default (1,1,1)
  29449. */
  29450. this.color = new Color( 0xffffff ); // diffuse
  29451. /**
  29452. * The color map. May optionally include an alpha channel, typically combined
  29453. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29454. * color is modulated by the diffuse `color`.
  29455. *
  29456. * @type {?Texture}
  29457. * @default null
  29458. */
  29459. this.map = null;
  29460. /**
  29461. * The light map. Requires a second set of UVs.
  29462. *
  29463. * @type {?Texture}
  29464. * @default null
  29465. */
  29466. this.lightMap = null;
  29467. /**
  29468. * Intensity of the baked light.
  29469. *
  29470. * @type {number}
  29471. * @default 1
  29472. */
  29473. this.lightMapIntensity = 1.0;
  29474. /**
  29475. * The red channel of this texture is used as the ambient occlusion map.
  29476. * Requires a second set of UVs.
  29477. *
  29478. * @type {?Texture}
  29479. * @default null
  29480. */
  29481. this.aoMap = null;
  29482. /**
  29483. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29484. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29485. * red channel is also `1`, ambient light is fully occluded on a surface.
  29486. *
  29487. * @type {number}
  29488. * @default 1
  29489. */
  29490. this.aoMapIntensity = 1.0;
  29491. /**
  29492. * Emissive (light) color of the material, essentially a solid color
  29493. * unaffected by other lighting.
  29494. *
  29495. * @type {Color}
  29496. * @default (0,0,0)
  29497. */
  29498. this.emissive = new Color( 0x000000 );
  29499. /**
  29500. * Intensity of the emissive light. Modulates the emissive color.
  29501. *
  29502. * @type {number}
  29503. * @default 1
  29504. */
  29505. this.emissiveIntensity = 1.0;
  29506. /**
  29507. * Set emissive (glow) map. The emissive map color is modulated by the
  29508. * emissive color and the emissive intensity. If you have an emissive map,
  29509. * be sure to set the emissive color to something other than black.
  29510. *
  29511. * @type {?Texture}
  29512. * @default null
  29513. */
  29514. this.emissiveMap = null;
  29515. /**
  29516. * The texture to create a bump map. The black and white values map to the
  29517. * perceived depth in relation to the lights. Bump doesn't actually affect
  29518. * the geometry of the object, only the lighting. If a normal map is defined
  29519. * this will be ignored.
  29520. *
  29521. * @type {?Texture}
  29522. * @default null
  29523. */
  29524. this.bumpMap = null;
  29525. /**
  29526. * How much the bump map affects the material. Typical range is `[0,1]`.
  29527. *
  29528. * @type {number}
  29529. * @default 1
  29530. */
  29531. this.bumpScale = 1;
  29532. /**
  29533. * The texture to create a normal map. The RGB values affect the surface
  29534. * normal for each pixel fragment and change the way the color is lit. Normal
  29535. * maps do not change the actual shape of the surface, only the lighting. In
  29536. * case the material has a normal map authored using the left handed
  29537. * convention, the `y` component of `normalScale` should be negated to compensate
  29538. * for the different handedness.
  29539. *
  29540. * @type {?Texture}
  29541. * @default null
  29542. */
  29543. this.normalMap = null;
  29544. /**
  29545. * The type of normal map.
  29546. *
  29547. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29548. * @default TangentSpaceNormalMap
  29549. */
  29550. this.normalMapType = TangentSpaceNormalMap;
  29551. /**
  29552. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29553. *
  29554. * @type {Vector2}
  29555. * @default (1,1)
  29556. */
  29557. this.normalScale = new Vector2( 1, 1 );
  29558. /**
  29559. * The displacement map affects the position of the mesh's vertices. Unlike
  29560. * other maps which only affect the light and shade of the material the
  29561. * displaced vertices can cast shadows, block other objects, and otherwise
  29562. * act as real geometry. The displacement texture is an image where the value
  29563. * of each pixel (white being the highest) is mapped against, and
  29564. * repositions, the vertices of the mesh.
  29565. *
  29566. * @type {?Texture}
  29567. * @default null
  29568. */
  29569. this.displacementMap = null;
  29570. /**
  29571. * How much the displacement map affects the mesh (where black is no
  29572. * displacement, and white is maximum displacement). Without a displacement
  29573. * map set, this value is not applied.
  29574. *
  29575. * @type {number}
  29576. * @default 0
  29577. */
  29578. this.displacementScale = 1;
  29579. /**
  29580. * The offset of the displacement map's values on the mesh's vertices.
  29581. * The bias is added to the scaled sample of the displacement map.
  29582. * Without a displacement map set, this value is not applied.
  29583. *
  29584. * @type {number}
  29585. * @default 0
  29586. */
  29587. this.displacementBias = 0;
  29588. /**
  29589. * Specular map used by the material.
  29590. *
  29591. * @type {?Texture}
  29592. * @default null
  29593. */
  29594. this.specularMap = null;
  29595. /**
  29596. * The alpha map is a grayscale texture that controls the opacity across the
  29597. * surface (black: fully transparent; white: fully opaque).
  29598. *
  29599. * Only the color of the texture is used, ignoring the alpha channel if one
  29600. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29601. * when sampling this texture due to the extra bit of precision provided for
  29602. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29603. * luminance/alpha textures will also still work as expected.
  29604. *
  29605. * @type {?Texture}
  29606. * @default null
  29607. */
  29608. this.alphaMap = null;
  29609. /**
  29610. * The environment map.
  29611. *
  29612. * @type {?Texture}
  29613. * @default null
  29614. */
  29615. this.envMap = null;
  29616. /**
  29617. * The rotation of the environment map in radians.
  29618. *
  29619. * @type {Euler}
  29620. * @default (0,0,0)
  29621. */
  29622. this.envMapRotation = new Euler();
  29623. /**
  29624. * How to combine the result of the surface's color with the environment map, if any.
  29625. *
  29626. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29627. * blend between the two colors.
  29628. *
  29629. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29630. * @default MultiplyOperation
  29631. */
  29632. this.combine = MultiplyOperation;
  29633. /**
  29634. * How much the environment map affects the surface.
  29635. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29636. *
  29637. * @type {number}
  29638. * @default 1
  29639. */
  29640. this.reflectivity = 1;
  29641. /**
  29642. * The index of refraction (IOR) of air (approximately 1) divided by the
  29643. * index of refraction of the material. It is used with environment mapping
  29644. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29645. * The refraction ratio should not exceed `1`.
  29646. *
  29647. * @type {number}
  29648. * @default 0.98
  29649. */
  29650. this.refractionRatio = 0.98;
  29651. /**
  29652. * Renders the geometry as a wireframe.
  29653. *
  29654. * @type {boolean}
  29655. * @default false
  29656. */
  29657. this.wireframe = false;
  29658. /**
  29659. * Controls the thickness of the wireframe.
  29660. *
  29661. * Can only be used with {@link SVGRenderer}.
  29662. *
  29663. * @type {number}
  29664. * @default 1
  29665. */
  29666. this.wireframeLinewidth = 1;
  29667. /**
  29668. * Defines appearance of wireframe ends.
  29669. *
  29670. * Can only be used with {@link SVGRenderer}.
  29671. *
  29672. * @type {('round'|'bevel'|'miter')}
  29673. * @default 'round'
  29674. */
  29675. this.wireframeLinecap = 'round';
  29676. /**
  29677. * Defines appearance of wireframe joints.
  29678. *
  29679. * Can only be used with {@link SVGRenderer}.
  29680. *
  29681. * @type {('round'|'bevel'|'miter')}
  29682. * @default 'round'
  29683. */
  29684. this.wireframeLinejoin = 'round';
  29685. /**
  29686. * Whether the material is rendered with flat shading or not.
  29687. *
  29688. * @type {boolean}
  29689. * @default false
  29690. */
  29691. this.flatShading = false;
  29692. /**
  29693. * Whether the material is affected by fog or not.
  29694. *
  29695. * @type {boolean}
  29696. * @default true
  29697. */
  29698. this.fog = true;
  29699. this.setValues( parameters );
  29700. }
  29701. copy( source ) {
  29702. super.copy( source );
  29703. this.color.copy( source.color );
  29704. this.map = source.map;
  29705. this.lightMap = source.lightMap;
  29706. this.lightMapIntensity = source.lightMapIntensity;
  29707. this.aoMap = source.aoMap;
  29708. this.aoMapIntensity = source.aoMapIntensity;
  29709. this.emissive.copy( source.emissive );
  29710. this.emissiveMap = source.emissiveMap;
  29711. this.emissiveIntensity = source.emissiveIntensity;
  29712. this.bumpMap = source.bumpMap;
  29713. this.bumpScale = source.bumpScale;
  29714. this.normalMap = source.normalMap;
  29715. this.normalMapType = source.normalMapType;
  29716. this.normalScale.copy( source.normalScale );
  29717. this.displacementMap = source.displacementMap;
  29718. this.displacementScale = source.displacementScale;
  29719. this.displacementBias = source.displacementBias;
  29720. this.specularMap = source.specularMap;
  29721. this.alphaMap = source.alphaMap;
  29722. this.envMap = source.envMap;
  29723. this.envMapRotation.copy( source.envMapRotation );
  29724. this.combine = source.combine;
  29725. this.reflectivity = source.reflectivity;
  29726. this.refractionRatio = source.refractionRatio;
  29727. this.wireframe = source.wireframe;
  29728. this.wireframeLinewidth = source.wireframeLinewidth;
  29729. this.wireframeLinecap = source.wireframeLinecap;
  29730. this.wireframeLinejoin = source.wireframeLinejoin;
  29731. this.flatShading = source.flatShading;
  29732. this.fog = source.fog;
  29733. return this;
  29734. }
  29735. }
  29736. /**
  29737. * A material for drawing geometry by depth. Depth is based off of the camera
  29738. * near and far plane. White is nearest, black is farthest.
  29739. *
  29740. * @augments Material
  29741. * @demo scenes/material-browser.html#MeshDepthMaterial
  29742. */
  29743. class MeshDepthMaterial extends Material {
  29744. /**
  29745. * Constructs a new mesh depth material.
  29746. *
  29747. * @param {Object} [parameters] - An object with one or more properties
  29748. * defining the material's appearance. Any property of the material
  29749. * (including any property from inherited materials) can be passed
  29750. * in here. Color values can be passed any type of value accepted
  29751. * by {@link Color#set}.
  29752. */
  29753. constructor( parameters ) {
  29754. super();
  29755. /**
  29756. * This flag can be used for type testing.
  29757. *
  29758. * @type {boolean}
  29759. * @readonly
  29760. * @default true
  29761. */
  29762. this.isMeshDepthMaterial = true;
  29763. this.type = 'MeshDepthMaterial';
  29764. /**
  29765. * Type for depth packing.
  29766. *
  29767. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29768. * @default BasicDepthPacking
  29769. */
  29770. this.depthPacking = BasicDepthPacking;
  29771. /**
  29772. * The color map. May optionally include an alpha channel, typically combined
  29773. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29774. *
  29775. * @type {?Texture}
  29776. * @default null
  29777. */
  29778. this.map = null;
  29779. /**
  29780. * The alpha map is a grayscale texture that controls the opacity across the
  29781. * surface (black: fully transparent; white: fully opaque).
  29782. *
  29783. * Only the color of the texture is used, ignoring the alpha channel if one
  29784. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29785. * when sampling this texture due to the extra bit of precision provided for
  29786. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29787. * luminance/alpha textures will also still work as expected.
  29788. *
  29789. * @type {?Texture}
  29790. * @default null
  29791. */
  29792. this.alphaMap = null;
  29793. /**
  29794. * The displacement map affects the position of the mesh's vertices. Unlike
  29795. * other maps which only affect the light and shade of the material the
  29796. * displaced vertices can cast shadows, block other objects, and otherwise
  29797. * act as real geometry. The displacement texture is an image where the value
  29798. * of each pixel (white being the highest) is mapped against, and
  29799. * repositions, the vertices of the mesh.
  29800. *
  29801. * @type {?Texture}
  29802. * @default null
  29803. */
  29804. this.displacementMap = null;
  29805. /**
  29806. * How much the displacement map affects the mesh (where black is no
  29807. * displacement, and white is maximum displacement). Without a displacement
  29808. * map set, this value is not applied.
  29809. *
  29810. * @type {number}
  29811. * @default 0
  29812. */
  29813. this.displacementScale = 1;
  29814. /**
  29815. * The offset of the displacement map's values on the mesh's vertices.
  29816. * The bias is added to the scaled sample of the displacement map.
  29817. * Without a displacement map set, this value is not applied.
  29818. *
  29819. * @type {number}
  29820. * @default 0
  29821. */
  29822. this.displacementBias = 0;
  29823. /**
  29824. * Renders the geometry as a wireframe.
  29825. *
  29826. * @type {boolean}
  29827. * @default false
  29828. */
  29829. this.wireframe = false;
  29830. /**
  29831. * Controls the thickness of the wireframe.
  29832. *
  29833. * WebGL and WebGPU ignore this property and always render
  29834. * 1 pixel wide lines.
  29835. *
  29836. * @type {number}
  29837. * @default 1
  29838. */
  29839. this.wireframeLinewidth = 1;
  29840. this.setValues( parameters );
  29841. }
  29842. copy( source ) {
  29843. super.copy( source );
  29844. this.depthPacking = source.depthPacking;
  29845. this.map = source.map;
  29846. this.alphaMap = source.alphaMap;
  29847. this.displacementMap = source.displacementMap;
  29848. this.displacementScale = source.displacementScale;
  29849. this.displacementBias = source.displacementBias;
  29850. this.wireframe = source.wireframe;
  29851. this.wireframeLinewidth = source.wireframeLinewidth;
  29852. return this;
  29853. }
  29854. }
  29855. /**
  29856. * A material used internally for implementing shadow mapping with
  29857. * point lights.
  29858. *
  29859. * Can also be used to customize the shadow casting of an object by assigning
  29860. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29861. * The following examples demonstrates this approach in order to ensure
  29862. * transparent parts of objects do not cast shadows.
  29863. *
  29864. * @augments Material
  29865. */
  29866. class MeshDistanceMaterial extends Material {
  29867. /**
  29868. * Constructs a new mesh distance material.
  29869. *
  29870. * @param {Object} [parameters] - An object with one or more properties
  29871. * defining the material's appearance. Any property of the material
  29872. * (including any property from inherited materials) can be passed
  29873. * in here. Color values can be passed any type of value accepted
  29874. * by {@link Color#set}.
  29875. */
  29876. constructor( parameters ) {
  29877. super();
  29878. /**
  29879. * This flag can be used for type testing.
  29880. *
  29881. * @type {boolean}
  29882. * @readonly
  29883. * @default true
  29884. */
  29885. this.isMeshDistanceMaterial = true;
  29886. this.type = 'MeshDistanceMaterial';
  29887. /**
  29888. * The color map. May optionally include an alpha channel, typically combined
  29889. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29890. *
  29891. * @type {?Texture}
  29892. * @default null
  29893. */
  29894. this.map = null;
  29895. /**
  29896. * The alpha map is a grayscale texture that controls the opacity across the
  29897. * surface (black: fully transparent; white: fully opaque).
  29898. *
  29899. * Only the color of the texture is used, ignoring the alpha channel if one
  29900. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29901. * when sampling this texture due to the extra bit of precision provided for
  29902. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29903. * luminance/alpha textures will also still work as expected.
  29904. *
  29905. * @type {?Texture}
  29906. * @default null
  29907. */
  29908. this.alphaMap = null;
  29909. /**
  29910. * The displacement map affects the position of the mesh's vertices. Unlike
  29911. * other maps which only affect the light and shade of the material the
  29912. * displaced vertices can cast shadows, block other objects, and otherwise
  29913. * act as real geometry. The displacement texture is an image where the value
  29914. * of each pixel (white being the highest) is mapped against, and
  29915. * repositions, the vertices of the mesh.
  29916. *
  29917. * @type {?Texture}
  29918. * @default null
  29919. */
  29920. this.displacementMap = null;
  29921. /**
  29922. * How much the displacement map affects the mesh (where black is no
  29923. * displacement, and white is maximum displacement). Without a displacement
  29924. * map set, this value is not applied.
  29925. *
  29926. * @type {number}
  29927. * @default 0
  29928. */
  29929. this.displacementScale = 1;
  29930. /**
  29931. * The offset of the displacement map's values on the mesh's vertices.
  29932. * The bias is added to the scaled sample of the displacement map.
  29933. * Without a displacement map set, this value is not applied.
  29934. *
  29935. * @type {number}
  29936. * @default 0
  29937. */
  29938. this.displacementBias = 0;
  29939. this.setValues( parameters );
  29940. }
  29941. copy( source ) {
  29942. super.copy( source );
  29943. this.map = source.map;
  29944. this.alphaMap = source.alphaMap;
  29945. this.displacementMap = source.displacementMap;
  29946. this.displacementScale = source.displacementScale;
  29947. this.displacementBias = source.displacementBias;
  29948. return this;
  29949. }
  29950. }
  29951. /**
  29952. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29953. * material color and shading.
  29954. *
  29955. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29956. * baked lighting. It will cast a shadow onto an object that receives shadows
  29957. * (and shadow clipping works), but it will not self-shadow or receive
  29958. * shadows.
  29959. *
  29960. * @augments Material
  29961. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29962. */
  29963. class MeshMatcapMaterial extends Material {
  29964. /**
  29965. * Constructs a new mesh matcap material.
  29966. *
  29967. * @param {Object} [parameters] - An object with one or more properties
  29968. * defining the material's appearance. Any property of the material
  29969. * (including any property from inherited materials) can be passed
  29970. * in here. Color values can be passed any type of value accepted
  29971. * by {@link Color#set}.
  29972. */
  29973. constructor( parameters ) {
  29974. super();
  29975. /**
  29976. * This flag can be used for type testing.
  29977. *
  29978. * @type {boolean}
  29979. * @readonly
  29980. * @default true
  29981. */
  29982. this.isMeshMatcapMaterial = true;
  29983. this.defines = { 'MATCAP': '' };
  29984. this.type = 'MeshMatcapMaterial';
  29985. /**
  29986. * Color of the material.
  29987. *
  29988. * @type {Color}
  29989. * @default (1,1,1)
  29990. */
  29991. this.color = new Color( 0xffffff ); // diffuse
  29992. /**
  29993. * The matcap map.
  29994. *
  29995. * @type {?Texture}
  29996. * @default null
  29997. */
  29998. this.matcap = null;
  29999. /**
  30000. * The color map. May optionally include an alpha channel, typically combined
  30001. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  30002. * color is modulated by the diffuse `color`.
  30003. *
  30004. * @type {?Texture}
  30005. * @default null
  30006. */
  30007. this.map = null;
  30008. /**
  30009. * The texture to create a bump map. The black and white values map to the
  30010. * perceived depth in relation to the lights. Bump doesn't actually affect
  30011. * the geometry of the object, only the lighting. If a normal map is defined
  30012. * this will be ignored.
  30013. *
  30014. * @type {?Texture}
  30015. * @default null
  30016. */
  30017. this.bumpMap = null;
  30018. /**
  30019. * How much the bump map affects the material. Typical range is `[0,1]`.
  30020. *
  30021. * @type {number}
  30022. * @default 1
  30023. */
  30024. this.bumpScale = 1;
  30025. /**
  30026. * The texture to create a normal map. The RGB values affect the surface
  30027. * normal for each pixel fragment and change the way the color is lit. Normal
  30028. * maps do not change the actual shape of the surface, only the lighting. In
  30029. * case the material has a normal map authored using the left handed
  30030. * convention, the `y` component of `normalScale` should be negated to compensate
  30031. * for the different handedness.
  30032. *
  30033. * @type {?Texture}
  30034. * @default null
  30035. */
  30036. this.normalMap = null;
  30037. /**
  30038. * The type of normal map.
  30039. *
  30040. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30041. * @default TangentSpaceNormalMap
  30042. */
  30043. this.normalMapType = TangentSpaceNormalMap;
  30044. /**
  30045. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30046. *
  30047. * @type {Vector2}
  30048. * @default (1,1)
  30049. */
  30050. this.normalScale = new Vector2( 1, 1 );
  30051. /**
  30052. * The displacement map affects the position of the mesh's vertices. Unlike
  30053. * other maps which only affect the light and shade of the material the
  30054. * displaced vertices can cast shadows, block other objects, and otherwise
  30055. * act as real geometry. The displacement texture is an image where the value
  30056. * of each pixel (white being the highest) is mapped against, and
  30057. * repositions, the vertices of the mesh.
  30058. *
  30059. * @type {?Texture}
  30060. * @default null
  30061. */
  30062. this.displacementMap = null;
  30063. /**
  30064. * How much the displacement map affects the mesh (where black is no
  30065. * displacement, and white is maximum displacement). Without a displacement
  30066. * map set, this value is not applied.
  30067. *
  30068. * @type {number}
  30069. * @default 0
  30070. */
  30071. this.displacementScale = 1;
  30072. /**
  30073. * The offset of the displacement map's values on the mesh's vertices.
  30074. * The bias is added to the scaled sample of the displacement map.
  30075. * Without a displacement map set, this value is not applied.
  30076. *
  30077. * @type {number}
  30078. * @default 0
  30079. */
  30080. this.displacementBias = 0;
  30081. /**
  30082. * The alpha map is a grayscale texture that controls the opacity across the
  30083. * surface (black: fully transparent; white: fully opaque).
  30084. *
  30085. * Only the color of the texture is used, ignoring the alpha channel if one
  30086. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30087. * when sampling this texture due to the extra bit of precision provided for
  30088. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30089. * luminance/alpha textures will also still work as expected.
  30090. *
  30091. * @type {?Texture}
  30092. * @default null
  30093. */
  30094. this.alphaMap = null;
  30095. /**
  30096. * Renders the geometry as a wireframe.
  30097. *
  30098. * @type {boolean}
  30099. * @default false
  30100. */
  30101. this.wireframe = false;
  30102. /**
  30103. * Controls the thickness of the wireframe.
  30104. *
  30105. * Can only be used with {@link SVGRenderer}.
  30106. *
  30107. * @type {number}
  30108. * @default 1
  30109. */
  30110. this.wireframeLinewidth = 1;
  30111. /**
  30112. * Whether the material is rendered with flat shading or not.
  30113. *
  30114. * @type {boolean}
  30115. * @default false
  30116. */
  30117. this.flatShading = false;
  30118. /**
  30119. * Whether the material is affected by fog or not.
  30120. *
  30121. * @type {boolean}
  30122. * @default true
  30123. */
  30124. this.fog = true;
  30125. this.setValues( parameters );
  30126. }
  30127. copy( source ) {
  30128. super.copy( source );
  30129. this.defines = { 'MATCAP': '' };
  30130. this.color.copy( source.color );
  30131. this.matcap = source.matcap;
  30132. this.map = source.map;
  30133. this.bumpMap = source.bumpMap;
  30134. this.bumpScale = source.bumpScale;
  30135. this.normalMap = source.normalMap;
  30136. this.normalMapType = source.normalMapType;
  30137. this.normalScale.copy( source.normalScale );
  30138. this.displacementMap = source.displacementMap;
  30139. this.displacementScale = source.displacementScale;
  30140. this.displacementBias = source.displacementBias;
  30141. this.alphaMap = source.alphaMap;
  30142. this.wireframe = source.wireframe;
  30143. this.wireframeLinewidth = source.wireframeLinewidth;
  30144. this.flatShading = source.flatShading;
  30145. this.fog = source.fog;
  30146. return this;
  30147. }
  30148. }
  30149. /**
  30150. * A material for rendering line primitives.
  30151. *
  30152. * Materials define the appearance of renderable 3D objects.
  30153. *
  30154. * ```js
  30155. * const material = new THREE.LineDashedMaterial( {
  30156. * color: 0xffffff,
  30157. * scale: 1,
  30158. * dashSize: 3,
  30159. * gapSize: 1,
  30160. * } );
  30161. * ```
  30162. *
  30163. * @augments LineBasicMaterial
  30164. */
  30165. class LineDashedMaterial extends LineBasicMaterial {
  30166. /**
  30167. * Constructs a new line dashed material.
  30168. *
  30169. * @param {Object} [parameters] - An object with one or more properties
  30170. * defining the material's appearance. Any property of the material
  30171. * (including any property from inherited materials) can be passed
  30172. * in here. Color values can be passed any type of value accepted
  30173. * by {@link Color#set}.
  30174. */
  30175. constructor( parameters ) {
  30176. super();
  30177. /**
  30178. * This flag can be used for type testing.
  30179. *
  30180. * @type {boolean}
  30181. * @readonly
  30182. * @default true
  30183. */
  30184. this.isLineDashedMaterial = true;
  30185. this.type = 'LineDashedMaterial';
  30186. /**
  30187. * The scale of the dashed part of a line.
  30188. *
  30189. * @type {number}
  30190. * @default 1
  30191. */
  30192. this.scale = 1;
  30193. /**
  30194. * The size of the dash. This is both the gap with the stroke.
  30195. *
  30196. * @type {number}
  30197. * @default 3
  30198. */
  30199. this.dashSize = 3;
  30200. /**
  30201. * The size of the gap.
  30202. *
  30203. * @type {number}
  30204. * @default 1
  30205. */
  30206. this.gapSize = 1;
  30207. this.setValues( parameters );
  30208. }
  30209. copy( source ) {
  30210. super.copy( source );
  30211. this.scale = source.scale;
  30212. this.dashSize = source.dashSize;
  30213. this.gapSize = source.gapSize;
  30214. return this;
  30215. }
  30216. }
  30217. /**
  30218. * Converts an array to a specific type.
  30219. *
  30220. * @param {TypedArray|Array} array - The array to convert.
  30221. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30222. * @return {TypedArray} The converted array.
  30223. */
  30224. function convertArray( array, type ) {
  30225. if ( ! array || array.constructor === type ) return array;
  30226. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30227. return new type( array ); // create typed array
  30228. }
  30229. return Array.prototype.slice.call( array ); // create Array
  30230. }
  30231. /**
  30232. * Returns an array by which times and values can be sorted.
  30233. *
  30234. * @param {Array<number>} times - The keyframe time values.
  30235. * @return {Array<number>} The array.
  30236. */
  30237. function getKeyframeOrder( times ) {
  30238. function compareTime( i, j ) {
  30239. return times[ i ] - times[ j ];
  30240. }
  30241. const n = times.length;
  30242. const result = new Array( n );
  30243. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30244. result.sort( compareTime );
  30245. return result;
  30246. }
  30247. /**
  30248. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30249. *
  30250. * @param {Array<number>} values - The values to sort.
  30251. * @param {number} stride - The stride.
  30252. * @param {Array<number>} order - The sort order.
  30253. * @return {Array<number>} The sorted values.
  30254. */
  30255. function sortedArray( values, stride, order ) {
  30256. const nValues = values.length;
  30257. const result = new values.constructor( nValues );
  30258. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30259. const srcOffset = order[ i ] * stride;
  30260. for ( let j = 0; j !== stride; ++ j ) {
  30261. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30262. }
  30263. }
  30264. return result;
  30265. }
  30266. /**
  30267. * Used for parsing AOS keyframe formats.
  30268. *
  30269. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30270. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30271. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30272. * @param {string} valuePropertyName - The name of the property to use.
  30273. */
  30274. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30275. let i = 1, key = jsonKeys[ 0 ];
  30276. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30277. key = jsonKeys[ i ++ ];
  30278. }
  30279. if ( key === undefined ) return; // no data
  30280. let value = key[ valuePropertyName ];
  30281. if ( value === undefined ) return; // no data
  30282. if ( Array.isArray( value ) ) {
  30283. do {
  30284. value = key[ valuePropertyName ];
  30285. if ( value !== undefined ) {
  30286. times.push( key.time );
  30287. values.push( ...value ); // push all elements
  30288. }
  30289. key = jsonKeys[ i ++ ];
  30290. } while ( key !== undefined );
  30291. } else if ( value.toArray !== undefined ) {
  30292. // ...assume THREE.Math-ish
  30293. do {
  30294. value = key[ valuePropertyName ];
  30295. if ( value !== undefined ) {
  30296. times.push( key.time );
  30297. value.toArray( values, values.length );
  30298. }
  30299. key = jsonKeys[ i ++ ];
  30300. } while ( key !== undefined );
  30301. } else {
  30302. // otherwise push as-is
  30303. do {
  30304. value = key[ valuePropertyName ];
  30305. if ( value !== undefined ) {
  30306. times.push( key.time );
  30307. values.push( value );
  30308. }
  30309. key = jsonKeys[ i ++ ];
  30310. } while ( key !== undefined );
  30311. }
  30312. }
  30313. /**
  30314. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30315. *
  30316. * @param {AnimationClip} sourceClip - The values to sort.
  30317. * @param {string} name - The name of the clip.
  30318. * @param {number} startFrame - The start frame.
  30319. * @param {number} endFrame - The end frame.
  30320. * @param {number} [fps=30] - The FPS.
  30321. * @return {AnimationClip} The new sub clip.
  30322. */
  30323. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30324. const clip = sourceClip.clone();
  30325. clip.name = name;
  30326. const tracks = [];
  30327. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30328. const track = clip.tracks[ i ];
  30329. const valueSize = track.getValueSize();
  30330. const times = [];
  30331. const values = [];
  30332. for ( let j = 0; j < track.times.length; ++ j ) {
  30333. const frame = track.times[ j ] * fps;
  30334. if ( frame < startFrame || frame >= endFrame ) continue;
  30335. times.push( track.times[ j ] );
  30336. for ( let k = 0; k < valueSize; ++ k ) {
  30337. values.push( track.values[ j * valueSize + k ] );
  30338. }
  30339. }
  30340. if ( times.length === 0 ) continue;
  30341. track.times = convertArray( times, track.times.constructor );
  30342. track.values = convertArray( values, track.values.constructor );
  30343. tracks.push( track );
  30344. }
  30345. clip.tracks = tracks;
  30346. // find minimum .times value across all tracks in the trimmed clip
  30347. let minStartTime = Infinity;
  30348. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30349. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30350. minStartTime = clip.tracks[ i ].times[ 0 ];
  30351. }
  30352. }
  30353. // shift all tracks such that clip begins at t=0
  30354. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30355. clip.tracks[ i ].shift( -1 * minStartTime );
  30356. }
  30357. clip.resetDuration();
  30358. return clip;
  30359. }
  30360. /**
  30361. * Converts the keyframes of the given animation clip to an additive format.
  30362. *
  30363. * @param {AnimationClip} targetClip - The clip to make additive.
  30364. * @param {number} [referenceFrame=0] - The reference frame.
  30365. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30366. * @param {number} [fps=30] - The FPS.
  30367. * @return {AnimationClip} The updated clip which is now additive.
  30368. */
  30369. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30370. if ( fps <= 0 ) fps = 30;
  30371. const numTracks = referenceClip.tracks.length;
  30372. const referenceTime = referenceFrame / fps;
  30373. // Make each track's values relative to the values at the reference frame
  30374. for ( let i = 0; i < numTracks; ++ i ) {
  30375. const referenceTrack = referenceClip.tracks[ i ];
  30376. const referenceTrackType = referenceTrack.ValueTypeName;
  30377. // Skip this track if it's non-numeric
  30378. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30379. // Find the track in the target clip whose name and type matches the reference track
  30380. const targetTrack = targetClip.tracks.find( function ( track ) {
  30381. return track.name === referenceTrack.name
  30382. && track.ValueTypeName === referenceTrackType;
  30383. } );
  30384. if ( targetTrack === undefined ) continue;
  30385. let referenceOffset = 0;
  30386. const referenceValueSize = referenceTrack.getValueSize();
  30387. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30388. referenceOffset = referenceValueSize / 3;
  30389. }
  30390. let targetOffset = 0;
  30391. const targetValueSize = targetTrack.getValueSize();
  30392. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30393. targetOffset = targetValueSize / 3;
  30394. }
  30395. const lastIndex = referenceTrack.times.length - 1;
  30396. let referenceValue;
  30397. // Find the value to subtract out of the track
  30398. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30399. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30400. const startIndex = referenceOffset;
  30401. const endIndex = referenceValueSize - referenceOffset;
  30402. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30403. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30404. // Reference frame is after the last keyframe, so just use the last keyframe
  30405. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30406. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30407. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30408. } else {
  30409. // Interpolate to the reference value
  30410. const interpolant = referenceTrack.createInterpolant();
  30411. const startIndex = referenceOffset;
  30412. const endIndex = referenceValueSize - referenceOffset;
  30413. interpolant.evaluate( referenceTime );
  30414. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30415. }
  30416. // Conjugate the quaternion
  30417. if ( referenceTrackType === 'quaternion' ) {
  30418. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30419. referenceQuat.toArray( referenceValue );
  30420. }
  30421. // Subtract the reference value from all of the track values
  30422. const numTimes = targetTrack.times.length;
  30423. for ( let j = 0; j < numTimes; ++ j ) {
  30424. const valueStart = j * targetValueSize + targetOffset;
  30425. if ( referenceTrackType === 'quaternion' ) {
  30426. // Multiply the conjugate for quaternion track types
  30427. Quaternion.multiplyQuaternionsFlat(
  30428. targetTrack.values,
  30429. valueStart,
  30430. referenceValue,
  30431. 0,
  30432. targetTrack.values,
  30433. valueStart
  30434. );
  30435. } else {
  30436. const valueEnd = targetValueSize - targetOffset * 2;
  30437. // Subtract each value for all other numeric track types
  30438. for ( let k = 0; k < valueEnd; ++ k ) {
  30439. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30440. }
  30441. }
  30442. }
  30443. }
  30444. targetClip.blendMode = AdditiveAnimationBlendMode;
  30445. return targetClip;
  30446. }
  30447. /**
  30448. * A class with various methods to assist with animations.
  30449. *
  30450. * @hideconstructor
  30451. */
  30452. class AnimationUtils {
  30453. /**
  30454. * Converts an array to a specific type
  30455. *
  30456. * @static
  30457. * @param {TypedArray|Array} array - The array to convert.
  30458. * @param {TypedArray.constructor} type - The constructor of a type array.
  30459. * @return {TypedArray} The converted array
  30460. */
  30461. static convertArray( array, type ) {
  30462. return convertArray( array, type );
  30463. }
  30464. /**
  30465. * Returns `true` if the given object is a typed array.
  30466. *
  30467. * @static
  30468. * @param {any} object - The object to check.
  30469. * @return {boolean} Whether the given object is a typed array.
  30470. */
  30471. static isTypedArray( object ) {
  30472. return isTypedArray( object );
  30473. }
  30474. /**
  30475. * Returns an array by which times and values can be sorted.
  30476. *
  30477. * @static
  30478. * @param {Array<number>} times - The keyframe time values.
  30479. * @return {Array<number>} The array.
  30480. */
  30481. static getKeyframeOrder( times ) {
  30482. return getKeyframeOrder( times );
  30483. }
  30484. /**
  30485. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30486. *
  30487. * @static
  30488. * @param {Array<number>} values - The values to sort.
  30489. * @param {number} stride - The stride.
  30490. * @param {Array<number>} order - The sort order.
  30491. * @return {Array<number>} The sorted values.
  30492. */
  30493. static sortedArray( values, stride, order ) {
  30494. return sortedArray( values, stride, order );
  30495. }
  30496. /**
  30497. * Used for parsing AOS keyframe formats.
  30498. *
  30499. * @static
  30500. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30501. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30502. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30503. * @param {string} valuePropertyName - The name of the property to use.
  30504. */
  30505. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30506. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30507. }
  30508. /**
  30509. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30510. *
  30511. * @static
  30512. * @param {AnimationClip} sourceClip - The values to sort.
  30513. * @param {string} name - The name of the clip.
  30514. * @param {number} startFrame - The start frame.
  30515. * @param {number} endFrame - The end frame.
  30516. * @param {number} [fps=30] - The FPS.
  30517. * @return {AnimationClip} The new sub clip.
  30518. */
  30519. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30520. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30521. }
  30522. /**
  30523. * Converts the keyframes of the given animation clip to an additive format.
  30524. *
  30525. * @static
  30526. * @param {AnimationClip} targetClip - The clip to make additive.
  30527. * @param {number} [referenceFrame=0] - The reference frame.
  30528. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30529. * @param {number} [fps=30] - The FPS.
  30530. * @return {AnimationClip} The updated clip which is now additive.
  30531. */
  30532. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30533. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30534. }
  30535. }
  30536. /**
  30537. * Abstract base class of interpolants over parametric samples.
  30538. *
  30539. * The parameter domain is one dimensional, typically the time or a path
  30540. * along a curve defined by the data.
  30541. *
  30542. * The sample values can have any dimensionality and derived classes may
  30543. * apply special interpretations to the data.
  30544. *
  30545. * This class provides the interval seek in a Template Method, deferring
  30546. * the actual interpolation to derived classes.
  30547. *
  30548. * Time complexity is O(1) for linear access crossing at most two points
  30549. * and O(log N) for random access, where N is the number of positions.
  30550. *
  30551. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30552. *
  30553. * @abstract
  30554. */
  30555. class Interpolant {
  30556. /**
  30557. * Constructs a new interpolant.
  30558. *
  30559. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30560. * @param {TypedArray} sampleValues - The sample values.
  30561. * @param {number} sampleSize - The sample size
  30562. * @param {TypedArray} [resultBuffer] - The result buffer.
  30563. */
  30564. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30565. /**
  30566. * The parameter positions.
  30567. *
  30568. * @type {TypedArray}
  30569. */
  30570. this.parameterPositions = parameterPositions;
  30571. /**
  30572. * A cache index.
  30573. *
  30574. * @private
  30575. * @type {number}
  30576. * @default 0
  30577. */
  30578. this._cachedIndex = 0;
  30579. /**
  30580. * The result buffer.
  30581. *
  30582. * @type {TypedArray}
  30583. */
  30584. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30585. /**
  30586. * The sample values.
  30587. *
  30588. * @type {TypedArray}
  30589. */
  30590. this.sampleValues = sampleValues;
  30591. /**
  30592. * The value size.
  30593. *
  30594. * @type {TypedArray}
  30595. */
  30596. this.valueSize = sampleSize;
  30597. /**
  30598. * The interpolation settings.
  30599. *
  30600. * @type {?Object}
  30601. * @default null
  30602. */
  30603. this.settings = null;
  30604. /**
  30605. * The default settings object.
  30606. *
  30607. * @type {Object}
  30608. */
  30609. this.DefaultSettings_ = {};
  30610. }
  30611. /**
  30612. * Evaluate the interpolant at position `t`.
  30613. *
  30614. * @param {number} t - The interpolation factor.
  30615. * @return {TypedArray} The result buffer.
  30616. */
  30617. evaluate( t ) {
  30618. const pp = this.parameterPositions;
  30619. let i1 = this._cachedIndex,
  30620. t1 = pp[ i1 ],
  30621. t0 = pp[ i1 - 1 ];
  30622. validate_interval: {
  30623. seek: {
  30624. let right;
  30625. linear_scan: {
  30626. //- See http://jsperf.com/comparison-to-undefined/3
  30627. //- slower code:
  30628. //-
  30629. //- if ( t >= t1 || t1 === undefined ) {
  30630. forward_scan: if ( ! ( t < t1 ) ) {
  30631. for ( let giveUpAt = i1 + 2; ; ) {
  30632. if ( t1 === undefined ) {
  30633. if ( t < t0 ) break forward_scan;
  30634. // after end
  30635. i1 = pp.length;
  30636. this._cachedIndex = i1;
  30637. return this.copySampleValue_( i1 - 1 );
  30638. }
  30639. if ( i1 === giveUpAt ) break; // this loop
  30640. t0 = t1;
  30641. t1 = pp[ ++ i1 ];
  30642. if ( t < t1 ) {
  30643. // we have arrived at the sought interval
  30644. break seek;
  30645. }
  30646. }
  30647. // prepare binary search on the right side of the index
  30648. right = pp.length;
  30649. break linear_scan;
  30650. }
  30651. //- slower code:
  30652. //- if ( t < t0 || t0 === undefined ) {
  30653. if ( ! ( t >= t0 ) ) {
  30654. // looping?
  30655. const t1global = pp[ 1 ];
  30656. if ( t < t1global ) {
  30657. i1 = 2; // + 1, using the scan for the details
  30658. t0 = t1global;
  30659. }
  30660. // linear reverse scan
  30661. for ( let giveUpAt = i1 - 2; ; ) {
  30662. if ( t0 === undefined ) {
  30663. // before start
  30664. this._cachedIndex = 0;
  30665. return this.copySampleValue_( 0 );
  30666. }
  30667. if ( i1 === giveUpAt ) break; // this loop
  30668. t1 = t0;
  30669. t0 = pp[ -- i1 - 1 ];
  30670. if ( t >= t0 ) {
  30671. // we have arrived at the sought interval
  30672. break seek;
  30673. }
  30674. }
  30675. // prepare binary search on the left side of the index
  30676. right = i1;
  30677. i1 = 0;
  30678. break linear_scan;
  30679. }
  30680. // the interval is valid
  30681. break validate_interval;
  30682. } // linear scan
  30683. // binary search
  30684. while ( i1 < right ) {
  30685. const mid = ( i1 + right ) >>> 1;
  30686. if ( t < pp[ mid ] ) {
  30687. right = mid;
  30688. } else {
  30689. i1 = mid + 1;
  30690. }
  30691. }
  30692. t1 = pp[ i1 ];
  30693. t0 = pp[ i1 - 1 ];
  30694. // check boundary cases, again
  30695. if ( t0 === undefined ) {
  30696. this._cachedIndex = 0;
  30697. return this.copySampleValue_( 0 );
  30698. }
  30699. if ( t1 === undefined ) {
  30700. i1 = pp.length;
  30701. this._cachedIndex = i1;
  30702. return this.copySampleValue_( i1 - 1 );
  30703. }
  30704. } // seek
  30705. this._cachedIndex = i1;
  30706. this.intervalChanged_( i1, t0, t1 );
  30707. } // validate_interval
  30708. return this.interpolate_( i1, t0, t, t1 );
  30709. }
  30710. /**
  30711. * Returns the interpolation settings.
  30712. *
  30713. * @return {Object} The interpolation settings.
  30714. */
  30715. getSettings_() {
  30716. return this.settings || this.DefaultSettings_;
  30717. }
  30718. /**
  30719. * Copies a sample value to the result buffer.
  30720. *
  30721. * @param {number} index - An index into the sample value buffer.
  30722. * @return {TypedArray} The result buffer.
  30723. */
  30724. copySampleValue_( index ) {
  30725. // copies a sample value to the result buffer
  30726. const result = this.resultBuffer,
  30727. values = this.sampleValues,
  30728. stride = this.valueSize,
  30729. offset = index * stride;
  30730. for ( let i = 0; i !== stride; ++ i ) {
  30731. result[ i ] = values[ offset + i ];
  30732. }
  30733. return result;
  30734. }
  30735. /**
  30736. * Copies a sample value to the result buffer.
  30737. *
  30738. * @abstract
  30739. * @param {number} i1 - An index into the sample value buffer.
  30740. * @param {number} t0 - The previous interpolation factor.
  30741. * @param {number} t - The current interpolation factor.
  30742. * @param {number} t1 - The next interpolation factor.
  30743. * @return {TypedArray} The result buffer.
  30744. */
  30745. interpolate_( /* i1, t0, t, t1 */ ) {
  30746. throw new Error( 'call to abstract method' );
  30747. // implementations shall return this.resultBuffer
  30748. }
  30749. /**
  30750. * Optional method that is executed when the interval has changed.
  30751. *
  30752. * @param {number} i1 - An index into the sample value buffer.
  30753. * @param {number} t0 - The previous interpolation factor.
  30754. * @param {number} t - The current interpolation factor.
  30755. */
  30756. intervalChanged_( /* i1, t0, t1 */ ) {
  30757. // empty
  30758. }
  30759. }
  30760. /**
  30761. * Fast and simple cubic spline interpolant.
  30762. *
  30763. * It was derived from a Hermitian construction setting the first derivative
  30764. * at each sample position to the linear slope between neighboring positions
  30765. * over their parameter interval.
  30766. *
  30767. * @augments Interpolant
  30768. */
  30769. class CubicInterpolant extends Interpolant {
  30770. /**
  30771. * Constructs a new cubic interpolant.
  30772. *
  30773. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30774. * @param {TypedArray} sampleValues - The sample values.
  30775. * @param {number} sampleSize - The sample size
  30776. * @param {TypedArray} [resultBuffer] - The result buffer.
  30777. */
  30778. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30779. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30780. this._weightPrev = -0;
  30781. this._offsetPrev = -0;
  30782. this._weightNext = -0;
  30783. this._offsetNext = -0;
  30784. this.DefaultSettings_ = {
  30785. endingStart: ZeroCurvatureEnding,
  30786. endingEnd: ZeroCurvatureEnding
  30787. };
  30788. }
  30789. intervalChanged_( i1, t0, t1 ) {
  30790. const pp = this.parameterPositions;
  30791. let iPrev = i1 - 2,
  30792. iNext = i1 + 1,
  30793. tPrev = pp[ iPrev ],
  30794. tNext = pp[ iNext ];
  30795. if ( tPrev === undefined ) {
  30796. switch ( this.getSettings_().endingStart ) {
  30797. case ZeroSlopeEnding:
  30798. // f'(t0) = 0
  30799. iPrev = i1;
  30800. tPrev = 2 * t0 - t1;
  30801. break;
  30802. case WrapAroundEnding:
  30803. // use the other end of the curve
  30804. iPrev = pp.length - 2;
  30805. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30806. break;
  30807. default: // ZeroCurvatureEnding
  30808. // f''(t0) = 0 a.k.a. Natural Spline
  30809. iPrev = i1;
  30810. tPrev = t1;
  30811. }
  30812. }
  30813. if ( tNext === undefined ) {
  30814. switch ( this.getSettings_().endingEnd ) {
  30815. case ZeroSlopeEnding:
  30816. // f'(tN) = 0
  30817. iNext = i1;
  30818. tNext = 2 * t1 - t0;
  30819. break;
  30820. case WrapAroundEnding:
  30821. // use the other end of the curve
  30822. iNext = 1;
  30823. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30824. break;
  30825. default: // ZeroCurvatureEnding
  30826. // f''(tN) = 0, a.k.a. Natural Spline
  30827. iNext = i1 - 1;
  30828. tNext = t0;
  30829. }
  30830. }
  30831. const halfDt = ( t1 - t0 ) * 0.5,
  30832. stride = this.valueSize;
  30833. this._weightPrev = halfDt / ( t0 - tPrev );
  30834. this._weightNext = halfDt / ( tNext - t1 );
  30835. this._offsetPrev = iPrev * stride;
  30836. this._offsetNext = iNext * stride;
  30837. }
  30838. interpolate_( i1, t0, t, t1 ) {
  30839. const result = this.resultBuffer,
  30840. values = this.sampleValues,
  30841. stride = this.valueSize,
  30842. o1 = i1 * stride, o0 = o1 - stride,
  30843. oP = this._offsetPrev, oN = this._offsetNext,
  30844. wP = this._weightPrev, wN = this._weightNext,
  30845. p = ( t - t0 ) / ( t1 - t0 ),
  30846. pp = p * p,
  30847. ppp = pp * p;
  30848. // evaluate polynomials
  30849. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30850. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30851. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30852. const sN = wN * ppp - wN * pp;
  30853. // combine data linearly
  30854. for ( let i = 0; i !== stride; ++ i ) {
  30855. result[ i ] =
  30856. sP * values[ oP + i ] +
  30857. s0 * values[ o0 + i ] +
  30858. s1 * values[ o1 + i ] +
  30859. sN * values[ oN + i ];
  30860. }
  30861. return result;
  30862. }
  30863. }
  30864. /**
  30865. * A basic linear interpolant.
  30866. *
  30867. * @augments Interpolant
  30868. */
  30869. class LinearInterpolant extends Interpolant {
  30870. /**
  30871. * Constructs a new linear interpolant.
  30872. *
  30873. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30874. * @param {TypedArray} sampleValues - The sample values.
  30875. * @param {number} sampleSize - The sample size
  30876. * @param {TypedArray} [resultBuffer] - The result buffer.
  30877. */
  30878. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30879. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30880. }
  30881. interpolate_( i1, t0, t, t1 ) {
  30882. const result = this.resultBuffer,
  30883. values = this.sampleValues,
  30884. stride = this.valueSize,
  30885. offset1 = i1 * stride,
  30886. offset0 = offset1 - stride,
  30887. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30888. weight0 = 1 - weight1;
  30889. for ( let i = 0; i !== stride; ++ i ) {
  30890. result[ i ] =
  30891. values[ offset0 + i ] * weight0 +
  30892. values[ offset1 + i ] * weight1;
  30893. }
  30894. return result;
  30895. }
  30896. }
  30897. /**
  30898. * Interpolant that evaluates to the sample value at the position preceding
  30899. * the parameter.
  30900. *
  30901. * @augments Interpolant
  30902. */
  30903. class DiscreteInterpolant extends Interpolant {
  30904. /**
  30905. * Constructs a new discrete interpolant.
  30906. *
  30907. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30908. * @param {TypedArray} sampleValues - The sample values.
  30909. * @param {number} sampleSize - The sample size
  30910. * @param {TypedArray} [resultBuffer] - The result buffer.
  30911. */
  30912. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30913. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30914. }
  30915. interpolate_( i1 /*, t0, t, t1 */ ) {
  30916. return this.copySampleValue_( i1 - 1 );
  30917. }
  30918. }
  30919. /**
  30920. * Represents s a timed sequence of keyframes, which are composed of lists of
  30921. * times and related values, and which are used to animate a specific property
  30922. * of an object.
  30923. */
  30924. class KeyframeTrack {
  30925. /**
  30926. * Constructs a new keyframe track.
  30927. *
  30928. * @param {string} name - The keyframe track's name.
  30929. * @param {Array<number>} times - A list of keyframe times.
  30930. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30931. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30932. */
  30933. constructor( name, times, values, interpolation ) {
  30934. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30935. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30936. /**
  30937. * The track's name can refer to morph targets or bones or
  30938. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30939. * for the forms of strings that can be parsed for property binding.
  30940. *
  30941. * @type {string}
  30942. */
  30943. this.name = name;
  30944. /**
  30945. * The keyframe times.
  30946. *
  30947. * @type {Float32Array}
  30948. */
  30949. this.times = convertArray( times, this.TimeBufferType );
  30950. /**
  30951. * The keyframe values.
  30952. *
  30953. * @type {Float32Array}
  30954. */
  30955. this.values = convertArray( values, this.ValueBufferType );
  30956. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30957. }
  30958. /**
  30959. * Converts the keyframe track to JSON.
  30960. *
  30961. * @static
  30962. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30963. * @return {Object} The serialized keyframe track as JSON.
  30964. */
  30965. static toJSON( track ) {
  30966. const trackType = track.constructor;
  30967. let json;
  30968. // derived classes can define a static toJSON method
  30969. if ( trackType.toJSON !== this.toJSON ) {
  30970. json = trackType.toJSON( track );
  30971. } else {
  30972. // by default, we assume the data can be serialized as-is
  30973. json = {
  30974. 'name': track.name,
  30975. 'times': convertArray( track.times, Array ),
  30976. 'values': convertArray( track.values, Array )
  30977. };
  30978. const interpolation = track.getInterpolation();
  30979. if ( interpolation !== track.DefaultInterpolation ) {
  30980. json.interpolation = interpolation;
  30981. }
  30982. }
  30983. json.type = track.ValueTypeName; // mandatory
  30984. return json;
  30985. }
  30986. /**
  30987. * Factory method for creating a new discrete interpolant.
  30988. *
  30989. * @static
  30990. * @param {TypedArray} [result] - The result buffer.
  30991. * @return {DiscreteInterpolant} The new interpolant.
  30992. */
  30993. InterpolantFactoryMethodDiscrete( result ) {
  30994. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30995. }
  30996. /**
  30997. * Factory method for creating a new linear interpolant.
  30998. *
  30999. * @static
  31000. * @param {TypedArray} [result] - The result buffer.
  31001. * @return {LinearInterpolant} The new interpolant.
  31002. */
  31003. InterpolantFactoryMethodLinear( result ) {
  31004. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31005. }
  31006. /**
  31007. * Factory method for creating a new smooth interpolant.
  31008. *
  31009. * @static
  31010. * @param {TypedArray} [result] - The result buffer.
  31011. * @return {CubicInterpolant} The new interpolant.
  31012. */
  31013. InterpolantFactoryMethodSmooth( result ) {
  31014. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31015. }
  31016. /**
  31017. * Defines the interpolation factor method for this keyframe track.
  31018. *
  31019. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  31020. * @return {KeyframeTrack} A reference to this keyframe track.
  31021. */
  31022. setInterpolation( interpolation ) {
  31023. let factoryMethod;
  31024. switch ( interpolation ) {
  31025. case InterpolateDiscrete:
  31026. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31027. break;
  31028. case InterpolateLinear:
  31029. factoryMethod = this.InterpolantFactoryMethodLinear;
  31030. break;
  31031. case InterpolateSmooth:
  31032. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31033. break;
  31034. }
  31035. if ( factoryMethod === undefined ) {
  31036. const message = 'unsupported interpolation for ' +
  31037. this.ValueTypeName + ' keyframe track named ' + this.name;
  31038. if ( this.createInterpolant === undefined ) {
  31039. // fall back to default, unless the default itself is messed up
  31040. if ( interpolation !== this.DefaultInterpolation ) {
  31041. this.setInterpolation( this.DefaultInterpolation );
  31042. } else {
  31043. throw new Error( message ); // fatal, in this case
  31044. }
  31045. }
  31046. warn( 'KeyframeTrack:', message );
  31047. return this;
  31048. }
  31049. this.createInterpolant = factoryMethod;
  31050. return this;
  31051. }
  31052. /**
  31053. * Returns the current interpolation type.
  31054. *
  31055. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  31056. */
  31057. getInterpolation() {
  31058. switch ( this.createInterpolant ) {
  31059. case this.InterpolantFactoryMethodDiscrete:
  31060. return InterpolateDiscrete;
  31061. case this.InterpolantFactoryMethodLinear:
  31062. return InterpolateLinear;
  31063. case this.InterpolantFactoryMethodSmooth:
  31064. return InterpolateSmooth;
  31065. }
  31066. }
  31067. /**
  31068. * Returns the value size.
  31069. *
  31070. * @return {number} The value size.
  31071. */
  31072. getValueSize() {
  31073. return this.values.length / this.times.length;
  31074. }
  31075. /**
  31076. * Moves all keyframes either forward or backward in time.
  31077. *
  31078. * @param {number} timeOffset - The offset to move the time values.
  31079. * @return {KeyframeTrack} A reference to this keyframe track.
  31080. */
  31081. shift( timeOffset ) {
  31082. if ( timeOffset !== 0.0 ) {
  31083. const times = this.times;
  31084. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31085. times[ i ] += timeOffset;
  31086. }
  31087. }
  31088. return this;
  31089. }
  31090. /**
  31091. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31092. *
  31093. * @param {number} timeScale - The time scale.
  31094. * @return {KeyframeTrack} A reference to this keyframe track.
  31095. */
  31096. scale( timeScale ) {
  31097. if ( timeScale !== 1.0 ) {
  31098. const times = this.times;
  31099. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31100. times[ i ] *= timeScale;
  31101. }
  31102. }
  31103. return this;
  31104. }
  31105. /**
  31106. * Removes keyframes before and after animation without changing any values within the defined time range.
  31107. *
  31108. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31109. * keys this will change their values
  31110. *
  31111. * @param {number} startTime - The start time.
  31112. * @param {number} endTime - The end time.
  31113. * @return {KeyframeTrack} A reference to this keyframe track.
  31114. */
  31115. trim( startTime, endTime ) {
  31116. const times = this.times,
  31117. nKeys = times.length;
  31118. let from = 0,
  31119. to = nKeys - 1;
  31120. while ( from !== nKeys && times[ from ] < startTime ) {
  31121. ++ from;
  31122. }
  31123. while ( to !== -1 && times[ to ] > endTime ) {
  31124. -- to;
  31125. }
  31126. ++ to; // inclusive -> exclusive bound
  31127. if ( from !== 0 || to !== nKeys ) {
  31128. // empty tracks are forbidden, so keep at least one keyframe
  31129. if ( from >= to ) {
  31130. to = Math.max( to, 1 );
  31131. from = to - 1;
  31132. }
  31133. const stride = this.getValueSize();
  31134. this.times = times.slice( from, to );
  31135. this.values = this.values.slice( from * stride, to * stride );
  31136. }
  31137. return this;
  31138. }
  31139. /**
  31140. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31141. * are valid.
  31142. *
  31143. * @return {boolean} Whether the keyframes are valid or not.
  31144. */
  31145. validate() {
  31146. let valid = true;
  31147. const valueSize = this.getValueSize();
  31148. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31149. error( 'KeyframeTrack: Invalid value size in track.', this );
  31150. valid = false;
  31151. }
  31152. const times = this.times,
  31153. values = this.values,
  31154. nKeys = times.length;
  31155. if ( nKeys === 0 ) {
  31156. error( 'KeyframeTrack: Track is empty.', this );
  31157. valid = false;
  31158. }
  31159. let prevTime = null;
  31160. for ( let i = 0; i !== nKeys; i ++ ) {
  31161. const currTime = times[ i ];
  31162. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31163. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31164. valid = false;
  31165. break;
  31166. }
  31167. if ( prevTime !== null && prevTime > currTime ) {
  31168. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31169. valid = false;
  31170. break;
  31171. }
  31172. prevTime = currTime;
  31173. }
  31174. if ( values !== undefined ) {
  31175. if ( isTypedArray( values ) ) {
  31176. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31177. const value = values[ i ];
  31178. if ( isNaN( value ) ) {
  31179. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31180. valid = false;
  31181. break;
  31182. }
  31183. }
  31184. }
  31185. }
  31186. return valid;
  31187. }
  31188. /**
  31189. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31190. * common in morph target sequences).
  31191. *
  31192. * @return {AnimationClip} A reference to this animation clip.
  31193. */
  31194. optimize() {
  31195. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31196. // times or values may be shared with other tracks, so overwriting is unsafe
  31197. const times = this.times.slice(),
  31198. values = this.values.slice(),
  31199. stride = this.getValueSize(),
  31200. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31201. lastIndex = times.length - 1;
  31202. let writeIndex = 1;
  31203. for ( let i = 1; i < lastIndex; ++ i ) {
  31204. let keep = false;
  31205. const time = times[ i ];
  31206. const timeNext = times[ i + 1 ];
  31207. // remove adjacent keyframes scheduled at the same time
  31208. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31209. if ( ! smoothInterpolation ) {
  31210. // remove unnecessary keyframes same as their neighbors
  31211. const offset = i * stride,
  31212. offsetP = offset - stride,
  31213. offsetN = offset + stride;
  31214. for ( let j = 0; j !== stride; ++ j ) {
  31215. const value = values[ offset + j ];
  31216. if ( value !== values[ offsetP + j ] ||
  31217. value !== values[ offsetN + j ] ) {
  31218. keep = true;
  31219. break;
  31220. }
  31221. }
  31222. } else {
  31223. keep = true;
  31224. }
  31225. }
  31226. // in-place compaction
  31227. if ( keep ) {
  31228. if ( i !== writeIndex ) {
  31229. times[ writeIndex ] = times[ i ];
  31230. const readOffset = i * stride,
  31231. writeOffset = writeIndex * stride;
  31232. for ( let j = 0; j !== stride; ++ j ) {
  31233. values[ writeOffset + j ] = values[ readOffset + j ];
  31234. }
  31235. }
  31236. ++ writeIndex;
  31237. }
  31238. }
  31239. // flush last keyframe (compaction looks ahead)
  31240. if ( lastIndex > 0 ) {
  31241. times[ writeIndex ] = times[ lastIndex ];
  31242. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31243. values[ writeOffset + j ] = values[ readOffset + j ];
  31244. }
  31245. ++ writeIndex;
  31246. }
  31247. if ( writeIndex !== times.length ) {
  31248. this.times = times.slice( 0, writeIndex );
  31249. this.values = values.slice( 0, writeIndex * stride );
  31250. } else {
  31251. this.times = times;
  31252. this.values = values;
  31253. }
  31254. return this;
  31255. }
  31256. /**
  31257. * Returns a new keyframe track with copied values from this instance.
  31258. *
  31259. * @return {KeyframeTrack} A clone of this instance.
  31260. */
  31261. clone() {
  31262. const times = this.times.slice();
  31263. const values = this.values.slice();
  31264. const TypedKeyframeTrack = this.constructor;
  31265. const track = new TypedKeyframeTrack( this.name, times, values );
  31266. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31267. track.createInterpolant = this.createInterpolant;
  31268. return track;
  31269. }
  31270. }
  31271. /**
  31272. * The value type name.
  31273. *
  31274. * @type {string}
  31275. * @default ''
  31276. */
  31277. KeyframeTrack.prototype.ValueTypeName = '';
  31278. /**
  31279. * The time buffer type of this keyframe track.
  31280. *
  31281. * @type {TypedArray|Array}
  31282. * @default Float32Array.constructor
  31283. */
  31284. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31285. /**
  31286. * The value buffer type of this keyframe track.
  31287. *
  31288. * @type {TypedArray|Array}
  31289. * @default Float32Array.constructor
  31290. */
  31291. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31292. /**
  31293. * The default interpolation type of this keyframe track.
  31294. *
  31295. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31296. * @default InterpolateLinear
  31297. */
  31298. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31299. /**
  31300. * A track for boolean keyframe values.
  31301. *
  31302. * @augments KeyframeTrack
  31303. */
  31304. class BooleanKeyframeTrack extends KeyframeTrack {
  31305. /**
  31306. * Constructs a new boolean keyframe track.
  31307. *
  31308. * This keyframe track type has no `interpolation` parameter because the
  31309. * interpolation is always discrete.
  31310. *
  31311. * @param {string} name - The keyframe track's name.
  31312. * @param {Array<number>} times - A list of keyframe times.
  31313. * @param {Array<boolean>} values - A list of keyframe values.
  31314. */
  31315. constructor( name, times, values ) {
  31316. super( name, times, values );
  31317. }
  31318. }
  31319. /**
  31320. * The value type name.
  31321. *
  31322. * @type {string}
  31323. * @default 'bool'
  31324. */
  31325. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31326. /**
  31327. * The value buffer type of this keyframe track.
  31328. *
  31329. * @type {TypedArray|Array}
  31330. * @default Array.constructor
  31331. */
  31332. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31333. /**
  31334. * The default interpolation type of this keyframe track.
  31335. *
  31336. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31337. * @default InterpolateDiscrete
  31338. */
  31339. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31340. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31341. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31342. /**
  31343. * A track for color keyframe values.
  31344. *
  31345. * @augments KeyframeTrack
  31346. */
  31347. class ColorKeyframeTrack extends KeyframeTrack {
  31348. /**
  31349. * Constructs a new color keyframe track.
  31350. *
  31351. * @param {string} name - The keyframe track's name.
  31352. * @param {Array<number>} times - A list of keyframe times.
  31353. * @param {Array<number>} values - A list of keyframe values.
  31354. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31355. */
  31356. constructor( name, times, values, interpolation ) {
  31357. super( name, times, values, interpolation );
  31358. }
  31359. }
  31360. /**
  31361. * The value type name.
  31362. *
  31363. * @type {string}
  31364. * @default 'color'
  31365. */
  31366. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31367. /**
  31368. * A track for numeric keyframe values.
  31369. *
  31370. * @augments KeyframeTrack
  31371. */
  31372. class NumberKeyframeTrack extends KeyframeTrack {
  31373. /**
  31374. * Constructs a new number keyframe track.
  31375. *
  31376. * @param {string} name - The keyframe track's name.
  31377. * @param {Array<number>} times - A list of keyframe times.
  31378. * @param {Array<number>} values - A list of keyframe values.
  31379. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31380. */
  31381. constructor( name, times, values, interpolation ) {
  31382. super( name, times, values, interpolation );
  31383. }
  31384. }
  31385. /**
  31386. * The value type name.
  31387. *
  31388. * @type {string}
  31389. * @default 'number'
  31390. */
  31391. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31392. /**
  31393. * Spherical linear unit quaternion interpolant.
  31394. *
  31395. * @augments Interpolant
  31396. */
  31397. class QuaternionLinearInterpolant extends Interpolant {
  31398. /**
  31399. * Constructs a new SLERP interpolant.
  31400. *
  31401. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31402. * @param {TypedArray} sampleValues - The sample values.
  31403. * @param {number} sampleSize - The sample size
  31404. * @param {TypedArray} [resultBuffer] - The result buffer.
  31405. */
  31406. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31407. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31408. }
  31409. interpolate_( i1, t0, t, t1 ) {
  31410. const result = this.resultBuffer,
  31411. values = this.sampleValues,
  31412. stride = this.valueSize,
  31413. alpha = ( t - t0 ) / ( t1 - t0 );
  31414. let offset = i1 * stride;
  31415. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31416. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31417. }
  31418. return result;
  31419. }
  31420. }
  31421. /**
  31422. * A track for Quaternion keyframe values.
  31423. *
  31424. * @augments KeyframeTrack
  31425. */
  31426. class QuaternionKeyframeTrack extends KeyframeTrack {
  31427. /**
  31428. * Constructs a new Quaternion keyframe track.
  31429. *
  31430. * @param {string} name - The keyframe track's name.
  31431. * @param {Array<number>} times - A list of keyframe times.
  31432. * @param {Array<number>} values - A list of keyframe values.
  31433. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31434. */
  31435. constructor( name, times, values, interpolation ) {
  31436. super( name, times, values, interpolation );
  31437. }
  31438. /**
  31439. * Overwritten so the method returns Quaternion based interpolant.
  31440. *
  31441. * @static
  31442. * @param {TypedArray} [result] - The result buffer.
  31443. * @return {QuaternionLinearInterpolant} The new interpolant.
  31444. */
  31445. InterpolantFactoryMethodLinear( result ) {
  31446. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31447. }
  31448. }
  31449. /**
  31450. * The value type name.
  31451. *
  31452. * @type {string}
  31453. * @default 'quaternion'
  31454. */
  31455. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31456. // ValueBufferType is inherited
  31457. // DefaultInterpolation is inherited;
  31458. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31459. /**
  31460. * A track for string keyframe values.
  31461. *
  31462. * @augments KeyframeTrack
  31463. */
  31464. class StringKeyframeTrack extends KeyframeTrack {
  31465. /**
  31466. * Constructs a new string keyframe track.
  31467. *
  31468. * This keyframe track type has no `interpolation` parameter because the
  31469. * interpolation is always discrete.
  31470. *
  31471. * @param {string} name - The keyframe track's name.
  31472. * @param {Array<number>} times - A list of keyframe times.
  31473. * @param {Array<string>} values - A list of keyframe values.
  31474. */
  31475. constructor( name, times, values ) {
  31476. super( name, times, values );
  31477. }
  31478. }
  31479. /**
  31480. * The value type name.
  31481. *
  31482. * @type {string}
  31483. * @default 'string'
  31484. */
  31485. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31486. /**
  31487. * The value buffer type of this keyframe track.
  31488. *
  31489. * @type {TypedArray|Array}
  31490. * @default Array.constructor
  31491. */
  31492. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31493. /**
  31494. * The default interpolation type of this keyframe track.
  31495. *
  31496. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31497. * @default InterpolateDiscrete
  31498. */
  31499. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31500. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31501. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31502. /**
  31503. * A track for vector keyframe values.
  31504. *
  31505. * @augments KeyframeTrack
  31506. */
  31507. class VectorKeyframeTrack extends KeyframeTrack {
  31508. /**
  31509. * Constructs a new vector keyframe track.
  31510. *
  31511. * @param {string} name - The keyframe track's name.
  31512. * @param {Array<number>} times - A list of keyframe times.
  31513. * @param {Array<number>} values - A list of keyframe values.
  31514. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31515. */
  31516. constructor( name, times, values, interpolation ) {
  31517. super( name, times, values, interpolation );
  31518. }
  31519. }
  31520. /**
  31521. * The value type name.
  31522. *
  31523. * @type {string}
  31524. * @default 'vector'
  31525. */
  31526. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31527. /**
  31528. * A reusable set of keyframe tracks which represent an animation.
  31529. */
  31530. class AnimationClip {
  31531. /**
  31532. * Constructs a new animation clip.
  31533. *
  31534. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31535. * use the static interface of this class for creating clips. In most cases though, animation clips
  31536. * will automatically be created by loaders when importing animated 3D assets.
  31537. *
  31538. * @param {string} [name=''] - The clip's name.
  31539. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31540. * the duration will be calculated from the passed keyframes.
  31541. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31542. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31543. * is blended/combined when two or more animations are simultaneously played.
  31544. */
  31545. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31546. /**
  31547. * The clip's name.
  31548. *
  31549. * @type {string}
  31550. */
  31551. this.name = name;
  31552. /**
  31553. * An array of keyframe tracks.
  31554. *
  31555. * @type {Array<KeyframeTrack>}
  31556. */
  31557. this.tracks = tracks;
  31558. /**
  31559. * The clip's duration in seconds.
  31560. *
  31561. * @type {number}
  31562. */
  31563. this.duration = duration;
  31564. /**
  31565. * Defines how the animation is blended/combined when two or more animations
  31566. * are simultaneously played.
  31567. *
  31568. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31569. */
  31570. this.blendMode = blendMode;
  31571. /**
  31572. * The UUID of the animation clip.
  31573. *
  31574. * @type {string}
  31575. * @readonly
  31576. */
  31577. this.uuid = generateUUID();
  31578. /**
  31579. * An object that can be used to store custom data about the animation clip.
  31580. * It should not hold references to functions as these will not be cloned.
  31581. *
  31582. * @type {Object}
  31583. */
  31584. this.userData = {};
  31585. // this means it should figure out its duration by scanning the tracks
  31586. if ( this.duration < 0 ) {
  31587. this.resetDuration();
  31588. }
  31589. }
  31590. /**
  31591. * Factory method for creating an animation clip from the given JSON.
  31592. *
  31593. * @static
  31594. * @param {Object} json - The serialized animation clip.
  31595. * @return {AnimationClip} The new animation clip.
  31596. */
  31597. static parse( json ) {
  31598. const tracks = [],
  31599. jsonTracks = json.tracks,
  31600. frameTime = 1.0 / ( json.fps || 1.0 );
  31601. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31602. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31603. }
  31604. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31605. clip.uuid = json.uuid;
  31606. clip.userData = JSON.parse( json.userData || '{}' );
  31607. return clip;
  31608. }
  31609. /**
  31610. * Serializes the given animation clip into JSON.
  31611. *
  31612. * @static
  31613. * @param {AnimationClip} clip - The animation clip to serialize.
  31614. * @return {Object} The JSON object.
  31615. */
  31616. static toJSON( clip ) {
  31617. const tracks = [],
  31618. clipTracks = clip.tracks;
  31619. const json = {
  31620. 'name': clip.name,
  31621. 'duration': clip.duration,
  31622. 'tracks': tracks,
  31623. 'uuid': clip.uuid,
  31624. 'blendMode': clip.blendMode,
  31625. 'userData': JSON.stringify( clip.userData ),
  31626. };
  31627. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31628. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31629. }
  31630. return json;
  31631. }
  31632. /**
  31633. * Returns a new animation clip from the passed morph targets array of a
  31634. * geometry, taking a name and the number of frames per second.
  31635. *
  31636. * Note: The fps parameter is required, but the animation speed can be
  31637. * overridden via {@link AnimationAction#setDuration}.
  31638. *
  31639. * @static
  31640. * @param {string} name - The name of the animation clip.
  31641. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31642. * @param {number} fps - The Frames-Per-Second value.
  31643. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31644. * @return {AnimationClip} The new animation clip.
  31645. */
  31646. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31647. const numMorphTargets = morphTargetSequence.length;
  31648. const tracks = [];
  31649. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31650. let times = [];
  31651. let values = [];
  31652. times.push(
  31653. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31654. i,
  31655. ( i + 1 ) % numMorphTargets );
  31656. values.push( 0, 1, 0 );
  31657. const order = getKeyframeOrder( times );
  31658. times = sortedArray( times, 1, order );
  31659. values = sortedArray( values, 1, order );
  31660. // if there is a key at the first frame, duplicate it as the
  31661. // last frame as well for perfect loop.
  31662. if ( ! noLoop && times[ 0 ] === 0 ) {
  31663. times.push( numMorphTargets );
  31664. values.push( values[ 0 ] );
  31665. }
  31666. tracks.push(
  31667. new NumberKeyframeTrack(
  31668. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31669. times, values
  31670. ).scale( 1.0 / fps ) );
  31671. }
  31672. return new this( name, -1, tracks );
  31673. }
  31674. /**
  31675. * Searches for an animation clip by name, taking as its first parameter
  31676. * either an array of clips, or a mesh or geometry that contains an
  31677. * array named "animations" property.
  31678. *
  31679. * @static
  31680. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31681. * @param {string} name - The name to search for.
  31682. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31683. */
  31684. static findByName( objectOrClipArray, name ) {
  31685. let clipArray = objectOrClipArray;
  31686. if ( ! Array.isArray( objectOrClipArray ) ) {
  31687. const o = objectOrClipArray;
  31688. clipArray = o.geometry && o.geometry.animations || o.animations;
  31689. }
  31690. for ( let i = 0; i < clipArray.length; i ++ ) {
  31691. if ( clipArray[ i ].name === name ) {
  31692. return clipArray[ i ];
  31693. }
  31694. }
  31695. return null;
  31696. }
  31697. /**
  31698. * Returns an array of new AnimationClips created from the morph target
  31699. * sequences of a geometry, trying to sort morph target names into
  31700. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31701. *
  31702. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31703. *
  31704. * @static
  31705. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31706. * @param {number} fps - The Frames-Per-Second value.
  31707. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31708. * @return {Array<AnimationClip>} An array of new animation clips.
  31709. */
  31710. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31711. const animationToMorphTargets = {};
  31712. // tested with https://regex101.com/ on trick sequences
  31713. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31714. const pattern = /^([\w-]*?)([\d]+)$/;
  31715. // sort morph target names into animation groups based
  31716. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31717. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31718. const morphTarget = morphTargets[ i ];
  31719. const parts = morphTarget.name.match( pattern );
  31720. if ( parts && parts.length > 1 ) {
  31721. const name = parts[ 1 ];
  31722. let animationMorphTargets = animationToMorphTargets[ name ];
  31723. if ( ! animationMorphTargets ) {
  31724. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31725. }
  31726. animationMorphTargets.push( morphTarget );
  31727. }
  31728. }
  31729. const clips = [];
  31730. for ( const name in animationToMorphTargets ) {
  31731. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31732. }
  31733. return clips;
  31734. }
  31735. /**
  31736. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31737. *
  31738. * @static
  31739. * @deprecated since r175.
  31740. * @param {Object} animation - A serialized animation clip as JSON.
  31741. * @param {Array<Bones>} bones - An array of bones.
  31742. * @return {?AnimationClip} The new animation clip.
  31743. */
  31744. static parseAnimation( animation, bones ) {
  31745. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31746. if ( ! animation ) {
  31747. error( 'AnimationClip: No animation in JSONLoader data.' );
  31748. return null;
  31749. }
  31750. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31751. // only return track if there are actually keys.
  31752. if ( animationKeys.length !== 0 ) {
  31753. const times = [];
  31754. const values = [];
  31755. flattenJSON( animationKeys, times, values, propertyName );
  31756. // empty keys are filtered out, so check again
  31757. if ( times.length !== 0 ) {
  31758. destTracks.push( new trackType( trackName, times, values ) );
  31759. }
  31760. }
  31761. };
  31762. const tracks = [];
  31763. const clipName = animation.name || 'default';
  31764. const fps = animation.fps || 30;
  31765. const blendMode = animation.blendMode;
  31766. // automatic length determination in AnimationClip.
  31767. let duration = animation.length || -1;
  31768. const hierarchyTracks = animation.hierarchy || [];
  31769. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31770. const animationKeys = hierarchyTracks[ h ].keys;
  31771. // skip empty tracks
  31772. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31773. // process morph targets
  31774. if ( animationKeys[ 0 ].morphTargets ) {
  31775. // figure out all morph targets used in this track
  31776. const morphTargetNames = {};
  31777. let k;
  31778. for ( k = 0; k < animationKeys.length; k ++ ) {
  31779. if ( animationKeys[ k ].morphTargets ) {
  31780. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31781. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31782. }
  31783. }
  31784. }
  31785. // create a track for each morph target with all zero
  31786. // morphTargetInfluences except for the keys in which
  31787. // the morphTarget is named.
  31788. for ( const morphTargetName in morphTargetNames ) {
  31789. const times = [];
  31790. const values = [];
  31791. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31792. const animationKey = animationKeys[ k ];
  31793. times.push( animationKey.time );
  31794. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31795. }
  31796. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31797. }
  31798. duration = morphTargetNames.length * fps;
  31799. } else {
  31800. // ...assume skeletal animation
  31801. const boneName = '.bones[' + bones[ h ].name + ']';
  31802. addNonemptyTrack(
  31803. VectorKeyframeTrack, boneName + '.position',
  31804. animationKeys, 'pos', tracks );
  31805. addNonemptyTrack(
  31806. QuaternionKeyframeTrack, boneName + '.quaternion',
  31807. animationKeys, 'rot', tracks );
  31808. addNonemptyTrack(
  31809. VectorKeyframeTrack, boneName + '.scale',
  31810. animationKeys, 'scl', tracks );
  31811. }
  31812. }
  31813. if ( tracks.length === 0 ) {
  31814. return null;
  31815. }
  31816. const clip = new this( clipName, duration, tracks, blendMode );
  31817. return clip;
  31818. }
  31819. /**
  31820. * Sets the duration of this clip to the duration of its longest keyframe track.
  31821. *
  31822. * @return {AnimationClip} A reference to this animation clip.
  31823. */
  31824. resetDuration() {
  31825. const tracks = this.tracks;
  31826. let duration = 0;
  31827. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31828. const track = this.tracks[ i ];
  31829. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31830. }
  31831. this.duration = duration;
  31832. return this;
  31833. }
  31834. /**
  31835. * Trims all tracks to the clip's duration.
  31836. *
  31837. * @return {AnimationClip} A reference to this animation clip.
  31838. */
  31839. trim() {
  31840. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31841. this.tracks[ i ].trim( 0, this.duration );
  31842. }
  31843. return this;
  31844. }
  31845. /**
  31846. * Performs minimal validation on each track in the clip. Returns `true` if all
  31847. * tracks are valid.
  31848. *
  31849. * @return {boolean} Whether the clip's keyframes are valid or not.
  31850. */
  31851. validate() {
  31852. let valid = true;
  31853. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31854. valid = valid && this.tracks[ i ].validate();
  31855. }
  31856. return valid;
  31857. }
  31858. /**
  31859. * Optimizes each track by removing equivalent sequential keys (which are
  31860. * common in morph target sequences).
  31861. *
  31862. * @return {AnimationClip} A reference to this animation clip.
  31863. */
  31864. optimize() {
  31865. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31866. this.tracks[ i ].optimize();
  31867. }
  31868. return this;
  31869. }
  31870. /**
  31871. * Returns a new animation clip with copied values from this instance.
  31872. *
  31873. * @return {AnimationClip} A clone of this instance.
  31874. */
  31875. clone() {
  31876. const tracks = [];
  31877. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31878. tracks.push( this.tracks[ i ].clone() );
  31879. }
  31880. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31881. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31882. return clip;
  31883. }
  31884. /**
  31885. * Serializes this animation clip into JSON.
  31886. *
  31887. * @return {Object} The JSON object.
  31888. */
  31889. toJSON() {
  31890. return this.constructor.toJSON( this );
  31891. }
  31892. }
  31893. function getTrackTypeForValueTypeName( typeName ) {
  31894. switch ( typeName.toLowerCase() ) {
  31895. case 'scalar':
  31896. case 'double':
  31897. case 'float':
  31898. case 'number':
  31899. case 'integer':
  31900. return NumberKeyframeTrack;
  31901. case 'vector':
  31902. case 'vector2':
  31903. case 'vector3':
  31904. case 'vector4':
  31905. return VectorKeyframeTrack;
  31906. case 'color':
  31907. return ColorKeyframeTrack;
  31908. case 'quaternion':
  31909. return QuaternionKeyframeTrack;
  31910. case 'bool':
  31911. case 'boolean':
  31912. return BooleanKeyframeTrack;
  31913. case 'string':
  31914. return StringKeyframeTrack;
  31915. }
  31916. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31917. }
  31918. function parseKeyframeTrack( json ) {
  31919. if ( json.type === undefined ) {
  31920. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31921. }
  31922. const trackType = getTrackTypeForValueTypeName( json.type );
  31923. if ( json.times === undefined ) {
  31924. const times = [], values = [];
  31925. flattenJSON( json.keys, times, values, 'value' );
  31926. json.times = times;
  31927. json.values = values;
  31928. }
  31929. // derived classes can define a static parse method
  31930. if ( trackType.parse !== undefined ) {
  31931. return trackType.parse( json );
  31932. } else {
  31933. // by default, we assume a constructor compatible with the base
  31934. return new trackType( json.name, json.times, json.values, json.interpolation );
  31935. }
  31936. }
  31937. /**
  31938. * @class
  31939. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31940. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31941. * @hideconstructor
  31942. */
  31943. const Cache = {
  31944. /**
  31945. * Whether caching is enabled or not.
  31946. *
  31947. * @static
  31948. * @type {boolean}
  31949. * @default false
  31950. */
  31951. enabled: false,
  31952. /**
  31953. * A dictionary that holds cached files.
  31954. *
  31955. * @static
  31956. * @type {Object<string,Object>}
  31957. */
  31958. files: {},
  31959. /**
  31960. * Adds a cache entry with a key to reference the file. If this key already
  31961. * holds a file, it is overwritten.
  31962. *
  31963. * @static
  31964. * @param {string} key - The key to reference the cached file.
  31965. * @param {Object} file - The file to be cached.
  31966. */
  31967. add: function ( key, file ) {
  31968. if ( this.enabled === false ) return;
  31969. // log( 'Cache', 'Adding key:', key );
  31970. this.files[ key ] = file;
  31971. },
  31972. /**
  31973. * Gets the cached value for the given key.
  31974. *
  31975. * @static
  31976. * @param {string} key - The key to reference the cached file.
  31977. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31978. */
  31979. get: function ( key ) {
  31980. if ( this.enabled === false ) return;
  31981. // log( 'Cache', 'Checking key:', key );
  31982. return this.files[ key ];
  31983. },
  31984. /**
  31985. * Removes the cached file associated with the given key.
  31986. *
  31987. * @static
  31988. * @param {string} key - The key to reference the cached file.
  31989. */
  31990. remove: function ( key ) {
  31991. delete this.files[ key ];
  31992. },
  31993. /**
  31994. * Remove all values from the cache.
  31995. *
  31996. * @static
  31997. */
  31998. clear: function () {
  31999. this.files = {};
  32000. }
  32001. };
  32002. /**
  32003. * Handles and keeps track of loaded and pending data. A default global
  32004. * instance of this class is created and used by loaders if not supplied
  32005. * manually.
  32006. *
  32007. * In general that should be sufficient, however there are times when it can
  32008. * be useful to have separate loaders - for example if you want to show
  32009. * separate loading bars for objects and textures.
  32010. *
  32011. * ```js
  32012. * const manager = new THREE.LoadingManager();
  32013. * manager.onLoad = () => console.log( 'Loading complete!' );
  32014. *
  32015. * const loader1 = new OBJLoader( manager );
  32016. * const loader2 = new ColladaLoader( manager );
  32017. * ```
  32018. */
  32019. class LoadingManager {
  32020. /**
  32021. * Constructs a new loading manager.
  32022. *
  32023. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32024. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32025. * @param {Function} [onError] - Executes when an error occurs.
  32026. */
  32027. constructor( onLoad, onProgress, onError ) {
  32028. const scope = this;
  32029. let isLoading = false;
  32030. let itemsLoaded = 0;
  32031. let itemsTotal = 0;
  32032. let urlModifier = undefined;
  32033. const handlers = [];
  32034. // Refer to #5689 for the reason why we don't set .onStart
  32035. // in the constructor
  32036. /**
  32037. * Executes when an item starts loading.
  32038. *
  32039. * @type {Function|undefined}
  32040. * @default undefined
  32041. */
  32042. this.onStart = undefined;
  32043. /**
  32044. * Executes when all items have been loaded.
  32045. *
  32046. * @type {Function|undefined}
  32047. * @default undefined
  32048. */
  32049. this.onLoad = onLoad;
  32050. /**
  32051. * Executes when single items have been loaded.
  32052. *
  32053. * @type {Function|undefined}
  32054. * @default undefined
  32055. */
  32056. this.onProgress = onProgress;
  32057. /**
  32058. * Executes when an error occurs.
  32059. *
  32060. * @type {Function|undefined}
  32061. * @default undefined
  32062. */
  32063. this.onError = onError;
  32064. /**
  32065. * Used for aborting ongoing requests in loaders using this manager.
  32066. *
  32067. * @private
  32068. * @type {AbortController | null}
  32069. */
  32070. this._abortController = null;
  32071. /**
  32072. * This should be called by any loader using the manager when the loader
  32073. * starts loading an item.
  32074. *
  32075. * @param {string} url - The URL to load.
  32076. */
  32077. this.itemStart = function ( url ) {
  32078. itemsTotal ++;
  32079. if ( isLoading === false ) {
  32080. if ( scope.onStart !== undefined ) {
  32081. scope.onStart( url, itemsLoaded, itemsTotal );
  32082. }
  32083. }
  32084. isLoading = true;
  32085. };
  32086. /**
  32087. * This should be called by any loader using the manager when the loader
  32088. * ended loading an item.
  32089. *
  32090. * @param {string} url - The URL of the loaded item.
  32091. */
  32092. this.itemEnd = function ( url ) {
  32093. itemsLoaded ++;
  32094. if ( scope.onProgress !== undefined ) {
  32095. scope.onProgress( url, itemsLoaded, itemsTotal );
  32096. }
  32097. if ( itemsLoaded === itemsTotal ) {
  32098. isLoading = false;
  32099. if ( scope.onLoad !== undefined ) {
  32100. scope.onLoad();
  32101. }
  32102. }
  32103. };
  32104. /**
  32105. * This should be called by any loader using the manager when the loader
  32106. * encounters an error when loading an item.
  32107. *
  32108. * @param {string} url - The URL of the item that produces an error.
  32109. */
  32110. this.itemError = function ( url ) {
  32111. if ( scope.onError !== undefined ) {
  32112. scope.onError( url );
  32113. }
  32114. };
  32115. /**
  32116. * Given a URL, uses the URL modifier callback (if any) and returns a
  32117. * resolved URL. If no URL modifier is set, returns the original URL.
  32118. *
  32119. * @param {string} url - The URL to load.
  32120. * @return {string} The resolved URL.
  32121. */
  32122. this.resolveURL = function ( url ) {
  32123. if ( urlModifier ) {
  32124. return urlModifier( url );
  32125. }
  32126. return url;
  32127. };
  32128. /**
  32129. * If provided, the callback will be passed each resource URL before a
  32130. * request is sent. The callback may return the original URL, or a new URL to
  32131. * override loading behavior. This behavior can be used to load assets from
  32132. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32133. *
  32134. * ```js
  32135. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32136. *
  32137. * const manager = new THREE.LoadingManager();
  32138. *
  32139. * // Initialize loading manager with URL callback.
  32140. * const objectURLs = [];
  32141. * manager.setURLModifier( ( url ) => {
  32142. *
  32143. * url = URL.createObjectURL( blobs[ url ] );
  32144. * objectURLs.push( url );
  32145. * return url;
  32146. *
  32147. * } );
  32148. *
  32149. * // Load as usual, then revoke the blob URLs.
  32150. * const loader = new GLTFLoader( manager );
  32151. * loader.load( 'fish.gltf', (gltf) => {
  32152. *
  32153. * scene.add( gltf.scene );
  32154. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32155. *
  32156. * } );
  32157. * ```
  32158. *
  32159. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32160. * @return {LoadingManager} A reference to this loading manager.
  32161. */
  32162. this.setURLModifier = function ( transform ) {
  32163. urlModifier = transform;
  32164. return this;
  32165. };
  32166. /**
  32167. * Registers a loader with the given regular expression. Can be used to
  32168. * define what loader should be used in order to load specific files. A
  32169. * typical use case is to overwrite the default loader for textures.
  32170. *
  32171. * ```js
  32172. * // add handler for TGA textures
  32173. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32174. * ```
  32175. *
  32176. * @param {string} regex - A regular expression.
  32177. * @param {Loader} loader - A loader that should handle matched cases.
  32178. * @return {LoadingManager} A reference to this loading manager.
  32179. */
  32180. this.addHandler = function ( regex, loader ) {
  32181. handlers.push( regex, loader );
  32182. return this;
  32183. };
  32184. /**
  32185. * Removes the loader for the given regular expression.
  32186. *
  32187. * @param {string} regex - A regular expression.
  32188. * @return {LoadingManager} A reference to this loading manager.
  32189. */
  32190. this.removeHandler = function ( regex ) {
  32191. const index = handlers.indexOf( regex );
  32192. if ( index !== -1 ) {
  32193. handlers.splice( index, 2 );
  32194. }
  32195. return this;
  32196. };
  32197. /**
  32198. * Can be used to retrieve the registered loader for the given file path.
  32199. *
  32200. * @param {string} file - The file path.
  32201. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32202. */
  32203. this.getHandler = function ( file ) {
  32204. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32205. const regex = handlers[ i ];
  32206. const loader = handlers[ i + 1 ];
  32207. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32208. if ( regex.test( file ) ) {
  32209. return loader;
  32210. }
  32211. }
  32212. return null;
  32213. };
  32214. /**
  32215. * Can be used to abort ongoing loading requests in loaders using this manager.
  32216. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32217. * is supported in the browser.
  32218. *
  32219. * @return {LoadingManager} A reference to this loading manager.
  32220. */
  32221. this.abort = function () {
  32222. this.abortController.abort();
  32223. this._abortController = null;
  32224. return this;
  32225. };
  32226. }
  32227. // TODO: Revert this back to a single member variable once this issue has been fixed
  32228. // https://github.com/cloudflare/workerd/issues/3657
  32229. /**
  32230. * Used for aborting ongoing requests in loaders using this manager.
  32231. *
  32232. * @type {AbortController}
  32233. */
  32234. get abortController() {
  32235. if ( ! this._abortController ) {
  32236. this._abortController = new AbortController();
  32237. }
  32238. return this._abortController;
  32239. }
  32240. }
  32241. /**
  32242. * The global default loading manager.
  32243. *
  32244. * @constant
  32245. * @type {LoadingManager}
  32246. */
  32247. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32248. /**
  32249. * Abstract base class for loaders.
  32250. *
  32251. * @abstract
  32252. */
  32253. class Loader {
  32254. /**
  32255. * Constructs a new loader.
  32256. *
  32257. * @param {LoadingManager} [manager] - The loading manager.
  32258. */
  32259. constructor( manager ) {
  32260. /**
  32261. * The loading manager.
  32262. *
  32263. * @type {LoadingManager}
  32264. * @default DefaultLoadingManager
  32265. */
  32266. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32267. /**
  32268. * The crossOrigin string to implement CORS for loading the url from a
  32269. * different domain that allows CORS.
  32270. *
  32271. * @type {string}
  32272. * @default 'anonymous'
  32273. */
  32274. this.crossOrigin = 'anonymous';
  32275. /**
  32276. * Whether the XMLHttpRequest uses credentials.
  32277. *
  32278. * @type {boolean}
  32279. * @default false
  32280. */
  32281. this.withCredentials = false;
  32282. /**
  32283. * The base path from which the asset will be loaded.
  32284. *
  32285. * @type {string}
  32286. */
  32287. this.path = '';
  32288. /**
  32289. * The base path from which additional resources like textures will be loaded.
  32290. *
  32291. * @type {string}
  32292. */
  32293. this.resourcePath = '';
  32294. /**
  32295. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32296. * used in HTTP request.
  32297. *
  32298. * @type {Object<string, any>}
  32299. */
  32300. this.requestHeader = {};
  32301. }
  32302. /**
  32303. * This method needs to be implemented by all concrete loaders. It holds the
  32304. * logic for loading assets from the backend.
  32305. *
  32306. * @abstract
  32307. * @param {string} url - The path/URL of the file to be loaded.
  32308. * @param {Function} onLoad - Executed when the loading process has been finished.
  32309. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32310. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32311. */
  32312. load( /* url, onLoad, onProgress, onError */ ) {}
  32313. /**
  32314. * A async version of {@link Loader#load}.
  32315. *
  32316. * @param {string} url - The path/URL of the file to be loaded.
  32317. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32318. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32319. */
  32320. loadAsync( url, onProgress ) {
  32321. const scope = this;
  32322. return new Promise( function ( resolve, reject ) {
  32323. scope.load( url, resolve, onProgress, reject );
  32324. } );
  32325. }
  32326. /**
  32327. * This method needs to be implemented by all concrete loaders. It holds the
  32328. * logic for parsing the asset into three.js entities.
  32329. *
  32330. * @abstract
  32331. * @param {any} data - The data to parse.
  32332. */
  32333. parse( /* data */ ) {}
  32334. /**
  32335. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32336. * from a different domain that allows CORS.
  32337. *
  32338. * @param {string} crossOrigin - The `crossOrigin` value.
  32339. * @return {Loader} A reference to this instance.
  32340. */
  32341. setCrossOrigin( crossOrigin ) {
  32342. this.crossOrigin = crossOrigin;
  32343. return this;
  32344. }
  32345. /**
  32346. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32347. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32348. *
  32349. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32350. *
  32351. * @param {boolean} value - The `withCredentials` value.
  32352. * @return {Loader} A reference to this instance.
  32353. */
  32354. setWithCredentials( value ) {
  32355. this.withCredentials = value;
  32356. return this;
  32357. }
  32358. /**
  32359. * Sets the base path for the asset.
  32360. *
  32361. * @param {string} path - The base path.
  32362. * @return {Loader} A reference to this instance.
  32363. */
  32364. setPath( path ) {
  32365. this.path = path;
  32366. return this;
  32367. }
  32368. /**
  32369. * Sets the base path for dependent resources like textures.
  32370. *
  32371. * @param {string} resourcePath - The resource path.
  32372. * @return {Loader} A reference to this instance.
  32373. */
  32374. setResourcePath( resourcePath ) {
  32375. this.resourcePath = resourcePath;
  32376. return this;
  32377. }
  32378. /**
  32379. * Sets the given request header.
  32380. *
  32381. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32382. * for configuring the HTTP request.
  32383. * @return {Loader} A reference to this instance.
  32384. */
  32385. setRequestHeader( requestHeader ) {
  32386. this.requestHeader = requestHeader;
  32387. return this;
  32388. }
  32389. /**
  32390. * This method can be implemented in loaders for aborting ongoing requests.
  32391. *
  32392. * @abstract
  32393. * @return {Loader} A reference to this instance.
  32394. */
  32395. abort() {
  32396. return this;
  32397. }
  32398. }
  32399. /**
  32400. * Callback for onProgress in loaders.
  32401. *
  32402. * @callback onProgressCallback
  32403. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32404. */
  32405. /**
  32406. * Callback for onError in loaders.
  32407. *
  32408. * @callback onErrorCallback
  32409. * @param {Error} error - The error which occurred during the loading process.
  32410. */
  32411. /**
  32412. * The default material name that is used by loaders
  32413. * when creating materials for loaded 3D objects.
  32414. *
  32415. * Note: Not all loaders might honor this setting.
  32416. *
  32417. * @static
  32418. * @type {string}
  32419. * @default '__DEFAULT'
  32420. */
  32421. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32422. const loading = {};
  32423. class HttpError extends Error {
  32424. constructor( message, response ) {
  32425. super( message );
  32426. this.response = response;
  32427. }
  32428. }
  32429. /**
  32430. * A low level class for loading resources with the Fetch API, used internally by
  32431. * most loaders. It can also be used directly to load any file type that does
  32432. * not have a loader.
  32433. *
  32434. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32435. * once to your application.
  32436. *
  32437. * ```js
  32438. * const loader = new THREE.FileLoader();
  32439. * const data = await loader.loadAsync( 'example.txt' );
  32440. * ```
  32441. *
  32442. * @augments Loader
  32443. */
  32444. class FileLoader extends Loader {
  32445. /**
  32446. * Constructs a new file loader.
  32447. *
  32448. * @param {LoadingManager} [manager] - The loading manager.
  32449. */
  32450. constructor( manager ) {
  32451. super( manager );
  32452. /**
  32453. * The expected mime type. Valid values can be found
  32454. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32455. *
  32456. * @type {string}
  32457. */
  32458. this.mimeType = '';
  32459. /**
  32460. * The expected response type.
  32461. *
  32462. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32463. * @default ''
  32464. */
  32465. this.responseType = '';
  32466. /**
  32467. * Used for aborting requests.
  32468. *
  32469. * @private
  32470. * @type {AbortController}
  32471. */
  32472. this._abortController = new AbortController();
  32473. }
  32474. /**
  32475. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32476. *
  32477. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32478. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32479. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32480. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32481. * @return {any|undefined} The cached resource if available.
  32482. */
  32483. load( url, onLoad, onProgress, onError ) {
  32484. if ( url === undefined ) url = '';
  32485. if ( this.path !== undefined ) url = this.path + url;
  32486. url = this.manager.resolveURL( url );
  32487. const cached = Cache.get( `file:${url}` );
  32488. if ( cached !== undefined ) {
  32489. this.manager.itemStart( url );
  32490. setTimeout( () => {
  32491. if ( onLoad ) onLoad( cached );
  32492. this.manager.itemEnd( url );
  32493. }, 0 );
  32494. return cached;
  32495. }
  32496. // Check if request is duplicate
  32497. if ( loading[ url ] !== undefined ) {
  32498. loading[ url ].push( {
  32499. onLoad: onLoad,
  32500. onProgress: onProgress,
  32501. onError: onError
  32502. } );
  32503. return;
  32504. }
  32505. // Initialise array for duplicate requests
  32506. loading[ url ] = [];
  32507. loading[ url ].push( {
  32508. onLoad: onLoad,
  32509. onProgress: onProgress,
  32510. onError: onError,
  32511. } );
  32512. // create request
  32513. const req = new Request( url, {
  32514. headers: new Headers( this.requestHeader ),
  32515. credentials: this.withCredentials ? 'include' : 'same-origin',
  32516. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32517. } );
  32518. // record states ( avoid data race )
  32519. const mimeType = this.mimeType;
  32520. const responseType = this.responseType;
  32521. // start the fetch
  32522. fetch( req )
  32523. .then( response => {
  32524. if ( response.status === 200 || response.status === 0 ) {
  32525. // Some browsers return HTTP Status 0 when using non-http protocol
  32526. // e.g. 'file://' or 'data://'. Handle as success.
  32527. if ( response.status === 0 ) {
  32528. warn( 'FileLoader: HTTP Status 0 received.' );
  32529. }
  32530. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32531. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32532. return response;
  32533. }
  32534. const callbacks = loading[ url ];
  32535. const reader = response.body.getReader();
  32536. // Nginx needs X-File-Size check
  32537. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32538. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32539. const total = contentLength ? parseInt( contentLength ) : 0;
  32540. const lengthComputable = total !== 0;
  32541. let loaded = 0;
  32542. // periodically read data into the new stream tracking while download progress
  32543. const stream = new ReadableStream( {
  32544. start( controller ) {
  32545. readData();
  32546. function readData() {
  32547. reader.read().then( ( { done, value } ) => {
  32548. if ( done ) {
  32549. controller.close();
  32550. } else {
  32551. loaded += value.byteLength;
  32552. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32553. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32554. const callback = callbacks[ i ];
  32555. if ( callback.onProgress ) callback.onProgress( event );
  32556. }
  32557. controller.enqueue( value );
  32558. readData();
  32559. }
  32560. }, ( e ) => {
  32561. controller.error( e );
  32562. } );
  32563. }
  32564. }
  32565. } );
  32566. return new Response( stream );
  32567. } else {
  32568. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32569. }
  32570. } )
  32571. .then( response => {
  32572. switch ( responseType ) {
  32573. case 'arraybuffer':
  32574. return response.arrayBuffer();
  32575. case 'blob':
  32576. return response.blob();
  32577. case 'document':
  32578. return response.text()
  32579. .then( text => {
  32580. const parser = new DOMParser();
  32581. return parser.parseFromString( text, mimeType );
  32582. } );
  32583. case 'json':
  32584. return response.json();
  32585. default:
  32586. if ( mimeType === '' ) {
  32587. return response.text();
  32588. } else {
  32589. // sniff encoding
  32590. const re = /charset="?([^;"\s]*)"?/i;
  32591. const exec = re.exec( mimeType );
  32592. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32593. const decoder = new TextDecoder( label );
  32594. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32595. }
  32596. }
  32597. } )
  32598. .then( data => {
  32599. // Add to cache only on HTTP success, so that we do not cache
  32600. // error response bodies as proper responses to requests.
  32601. Cache.add( `file:${url}`, data );
  32602. const callbacks = loading[ url ];
  32603. delete loading[ url ];
  32604. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32605. const callback = callbacks[ i ];
  32606. if ( callback.onLoad ) callback.onLoad( data );
  32607. }
  32608. } )
  32609. .catch( err => {
  32610. // Abort errors and other errors are handled the same
  32611. const callbacks = loading[ url ];
  32612. if ( callbacks === undefined ) {
  32613. // When onLoad was called and url was deleted in `loading`
  32614. this.manager.itemError( url );
  32615. throw err;
  32616. }
  32617. delete loading[ url ];
  32618. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32619. const callback = callbacks[ i ];
  32620. if ( callback.onError ) callback.onError( err );
  32621. }
  32622. this.manager.itemError( url );
  32623. } )
  32624. .finally( () => {
  32625. this.manager.itemEnd( url );
  32626. } );
  32627. this.manager.itemStart( url );
  32628. }
  32629. /**
  32630. * Sets the expected response type.
  32631. *
  32632. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32633. * @return {FileLoader} A reference to this file loader.
  32634. */
  32635. setResponseType( value ) {
  32636. this.responseType = value;
  32637. return this;
  32638. }
  32639. /**
  32640. * Sets the expected mime type of the loaded file.
  32641. *
  32642. * @param {string} value - The mime type.
  32643. * @return {FileLoader} A reference to this file loader.
  32644. */
  32645. setMimeType( value ) {
  32646. this.mimeType = value;
  32647. return this;
  32648. }
  32649. /**
  32650. * Aborts ongoing fetch requests.
  32651. *
  32652. * @return {FileLoader} A reference to this instance.
  32653. */
  32654. abort() {
  32655. this._abortController.abort();
  32656. this._abortController = new AbortController();
  32657. return this;
  32658. }
  32659. }
  32660. /**
  32661. * Class for loading animation clips in the JSON format. The files are internally
  32662. * loaded via {@link FileLoader}.
  32663. *
  32664. * ```js
  32665. * const loader = new THREE.AnimationLoader();
  32666. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32667. * ```
  32668. *
  32669. * @augments Loader
  32670. */
  32671. class AnimationLoader extends Loader {
  32672. /**
  32673. * Constructs a new animation loader.
  32674. *
  32675. * @param {LoadingManager} [manager] - The loading manager.
  32676. */
  32677. constructor( manager ) {
  32678. super( manager );
  32679. }
  32680. /**
  32681. * Starts loading from the given URL and pass the loaded animations as an array
  32682. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32683. *
  32684. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32685. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32686. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32687. * @param {onErrorCallback} onError - Executed when errors occur.
  32688. */
  32689. load( url, onLoad, onProgress, onError ) {
  32690. const scope = this;
  32691. const loader = new FileLoader( this.manager );
  32692. loader.setPath( this.path );
  32693. loader.setRequestHeader( this.requestHeader );
  32694. loader.setWithCredentials( this.withCredentials );
  32695. loader.load( url, function ( text ) {
  32696. try {
  32697. onLoad( scope.parse( JSON.parse( text ) ) );
  32698. } catch ( e ) {
  32699. if ( onError ) {
  32700. onError( e );
  32701. } else {
  32702. error( e );
  32703. }
  32704. scope.manager.itemError( url );
  32705. }
  32706. }, onProgress, onError );
  32707. }
  32708. /**
  32709. * Parses the given JSON object and returns an array of animation clips.
  32710. *
  32711. * @param {Object} json - The serialized animation clips.
  32712. * @return {Array<AnimationClip>} The parsed animation clips.
  32713. */
  32714. parse( json ) {
  32715. const animations = [];
  32716. for ( let i = 0; i < json.length; i ++ ) {
  32717. const clip = AnimationClip.parse( json[ i ] );
  32718. animations.push( clip );
  32719. }
  32720. return animations;
  32721. }
  32722. }
  32723. /**
  32724. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32725. * Textures are internally loaded via {@link FileLoader}.
  32726. *
  32727. * Derived classes have to implement the `parse()` method which holds the parsing
  32728. * for the respective format.
  32729. *
  32730. * @abstract
  32731. * @augments Loader
  32732. */
  32733. class CompressedTextureLoader extends Loader {
  32734. /**
  32735. * Constructs a new compressed texture loader.
  32736. *
  32737. * @param {LoadingManager} [manager] - The loading manager.
  32738. */
  32739. constructor( manager ) {
  32740. super( manager );
  32741. }
  32742. /**
  32743. * Starts loading from the given URL and passes the loaded compressed texture
  32744. * to the `onLoad()` callback. The method also returns a new texture object which can
  32745. * directly be used for material creation. If you do it this way, the texture
  32746. * may pop up in your scene once the respective loading process is finished.
  32747. *
  32748. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32749. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32750. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32751. * @param {onErrorCallback} onError - Executed when errors occur.
  32752. * @return {CompressedTexture} The compressed texture.
  32753. */
  32754. load( url, onLoad, onProgress, onError ) {
  32755. const scope = this;
  32756. const images = [];
  32757. const texture = new CompressedTexture();
  32758. const loader = new FileLoader( this.manager );
  32759. loader.setPath( this.path );
  32760. loader.setResponseType( 'arraybuffer' );
  32761. loader.setRequestHeader( this.requestHeader );
  32762. loader.setWithCredentials( scope.withCredentials );
  32763. let loaded = 0;
  32764. function loadTexture( i ) {
  32765. loader.load( url[ i ], function ( buffer ) {
  32766. const texDatas = scope.parse( buffer, true );
  32767. images[ i ] = {
  32768. width: texDatas.width,
  32769. height: texDatas.height,
  32770. format: texDatas.format,
  32771. mipmaps: texDatas.mipmaps
  32772. };
  32773. loaded += 1;
  32774. if ( loaded === 6 ) {
  32775. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32776. texture.image = images;
  32777. texture.format = texDatas.format;
  32778. texture.needsUpdate = true;
  32779. if ( onLoad ) onLoad( texture );
  32780. }
  32781. }, onProgress, onError );
  32782. }
  32783. if ( Array.isArray( url ) ) {
  32784. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32785. loadTexture( i );
  32786. }
  32787. } else {
  32788. // compressed cubemap texture stored in a single DDS file
  32789. loader.load( url, function ( buffer ) {
  32790. const texDatas = scope.parse( buffer, true );
  32791. if ( texDatas.isCubemap ) {
  32792. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32793. for ( let f = 0; f < faces; f ++ ) {
  32794. images[ f ] = { mipmaps: [] };
  32795. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32796. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32797. images[ f ].format = texDatas.format;
  32798. images[ f ].width = texDatas.width;
  32799. images[ f ].height = texDatas.height;
  32800. }
  32801. }
  32802. texture.image = images;
  32803. } else {
  32804. texture.image.width = texDatas.width;
  32805. texture.image.height = texDatas.height;
  32806. texture.mipmaps = texDatas.mipmaps;
  32807. }
  32808. if ( texDatas.mipmapCount === 1 ) {
  32809. texture.minFilter = LinearFilter;
  32810. }
  32811. texture.format = texDatas.format;
  32812. texture.needsUpdate = true;
  32813. if ( onLoad ) onLoad( texture );
  32814. }, onProgress, onError );
  32815. }
  32816. return texture;
  32817. }
  32818. }
  32819. const _loading = new WeakMap();
  32820. /**
  32821. * A loader for loading images. The class loads images with the HTML `Image` API.
  32822. *
  32823. * ```js
  32824. * const loader = new THREE.ImageLoader();
  32825. * const image = await loader.loadAsync( 'image.png' );
  32826. * ```
  32827. * Please note that `ImageLoader` has dropped support for progress
  32828. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32829. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32830. *
  32831. * @augments Loader
  32832. */
  32833. class ImageLoader extends Loader {
  32834. /**
  32835. * Constructs a new image loader.
  32836. *
  32837. * @param {LoadingManager} [manager] - The loading manager.
  32838. */
  32839. constructor( manager ) {
  32840. super( manager );
  32841. }
  32842. /**
  32843. * Starts loading from the given URL and passes the loaded image
  32844. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32845. * directly be used for texture creation. If you do it this way, the texture
  32846. * may pop up in your scene once the respective loading process is finished.
  32847. *
  32848. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32849. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32850. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32851. * @param {onErrorCallback} onError - Executed when errors occur.
  32852. * @return {Image} The image.
  32853. */
  32854. load( url, onLoad, onProgress, onError ) {
  32855. if ( this.path !== undefined ) url = this.path + url;
  32856. url = this.manager.resolveURL( url );
  32857. const scope = this;
  32858. const cached = Cache.get( `image:${url}` );
  32859. if ( cached !== undefined ) {
  32860. if ( cached.complete === true ) {
  32861. scope.manager.itemStart( url );
  32862. setTimeout( function () {
  32863. if ( onLoad ) onLoad( cached );
  32864. scope.manager.itemEnd( url );
  32865. }, 0 );
  32866. } else {
  32867. let arr = _loading.get( cached );
  32868. if ( arr === undefined ) {
  32869. arr = [];
  32870. _loading.set( cached, arr );
  32871. }
  32872. arr.push( { onLoad, onError } );
  32873. }
  32874. return cached;
  32875. }
  32876. const image = createElementNS( 'img' );
  32877. function onImageLoad() {
  32878. removeEventListeners();
  32879. if ( onLoad ) onLoad( this );
  32880. //
  32881. const callbacks = _loading.get( this ) || [];
  32882. for ( let i = 0; i < callbacks.length; i ++ ) {
  32883. const callback = callbacks[ i ];
  32884. if ( callback.onLoad ) callback.onLoad( this );
  32885. }
  32886. _loading.delete( this );
  32887. scope.manager.itemEnd( url );
  32888. }
  32889. function onImageError( event ) {
  32890. removeEventListeners();
  32891. if ( onError ) onError( event );
  32892. Cache.remove( `image:${url}` );
  32893. //
  32894. const callbacks = _loading.get( this ) || [];
  32895. for ( let i = 0; i < callbacks.length; i ++ ) {
  32896. const callback = callbacks[ i ];
  32897. if ( callback.onError ) callback.onError( event );
  32898. }
  32899. _loading.delete( this );
  32900. scope.manager.itemError( url );
  32901. scope.manager.itemEnd( url );
  32902. }
  32903. function removeEventListeners() {
  32904. image.removeEventListener( 'load', onImageLoad, false );
  32905. image.removeEventListener( 'error', onImageError, false );
  32906. }
  32907. image.addEventListener( 'load', onImageLoad, false );
  32908. image.addEventListener( 'error', onImageError, false );
  32909. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32910. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32911. }
  32912. Cache.add( `image:${url}`, image );
  32913. scope.manager.itemStart( url );
  32914. image.src = url;
  32915. return image;
  32916. }
  32917. }
  32918. /**
  32919. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32920. *
  32921. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32922. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32923. * like vertical and horizontal cross, column and row layouts are not supported.
  32924. *
  32925. * Note that, by convention, cube maps are specified in a coordinate system
  32926. * in which positive-x is to the right when looking up the positive-z axis --
  32927. * in other words, using a left-handed coordinate system. Since three.js uses
  32928. * a right-handed coordinate system, environment maps used in three.js will
  32929. * have pos-x and neg-x swapped.
  32930. *
  32931. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32932. * is set to `SRGBColorSpace` by default.
  32933. *
  32934. * ```js
  32935. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32936. * const cubeTexture = await loader.loadAsync( [
  32937. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32938. * ] );
  32939. * scene.background = cubeTexture;
  32940. * ```
  32941. *
  32942. * @augments Loader
  32943. */
  32944. class CubeTextureLoader extends Loader {
  32945. /**
  32946. * Constructs a new cube texture loader.
  32947. *
  32948. * @param {LoadingManager} [manager] - The loading manager.
  32949. */
  32950. constructor( manager ) {
  32951. super( manager );
  32952. }
  32953. /**
  32954. * Starts loading from the given URL and pass the fully loaded cube texture
  32955. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32956. * directly be used for material creation. If you do it this way, the cube texture
  32957. * may pop up in your scene once the respective loading process is finished.
  32958. *
  32959. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32960. * cube texture. The urls should be specified in the following order: pos-x,
  32961. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32962. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32963. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32964. * @param {onErrorCallback} onError - Executed when errors occur.
  32965. * @return {CubeTexture} The cube texture.
  32966. */
  32967. load( urls, onLoad, onProgress, onError ) {
  32968. const texture = new CubeTexture();
  32969. texture.colorSpace = SRGBColorSpace;
  32970. const loader = new ImageLoader( this.manager );
  32971. loader.setCrossOrigin( this.crossOrigin );
  32972. loader.setPath( this.path );
  32973. let loaded = 0;
  32974. function loadTexture( i ) {
  32975. loader.load( urls[ i ], function ( image ) {
  32976. texture.images[ i ] = image;
  32977. loaded ++;
  32978. if ( loaded === 6 ) {
  32979. texture.needsUpdate = true;
  32980. if ( onLoad ) onLoad( texture );
  32981. }
  32982. }, undefined, onError );
  32983. }
  32984. for ( let i = 0; i < urls.length; ++ i ) {
  32985. loadTexture( i );
  32986. }
  32987. return texture;
  32988. }
  32989. }
  32990. /**
  32991. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32992. * Textures are internally loaded via {@link FileLoader}.
  32993. *
  32994. * Derived classes have to implement the `parse()` method which holds the parsing
  32995. * for the respective format.
  32996. *
  32997. * @abstract
  32998. * @augments Loader
  32999. */
  33000. class DataTextureLoader extends Loader {
  33001. /**
  33002. * Constructs a new data texture loader.
  33003. *
  33004. * @param {LoadingManager} [manager] - The loading manager.
  33005. */
  33006. constructor( manager ) {
  33007. super( manager );
  33008. }
  33009. /**
  33010. * Starts loading from the given URL and passes the loaded data texture
  33011. * to the `onLoad()` callback. The method also returns a new texture object which can
  33012. * directly be used for material creation. If you do it this way, the texture
  33013. * may pop up in your scene once the respective loading process is finished.
  33014. *
  33015. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33016. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33017. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33018. * @param {onErrorCallback} onError - Executed when errors occur.
  33019. * @return {DataTexture} The data texture.
  33020. */
  33021. load( url, onLoad, onProgress, onError ) {
  33022. const scope = this;
  33023. const texture = new DataTexture();
  33024. const loader = new FileLoader( this.manager );
  33025. loader.setResponseType( 'arraybuffer' );
  33026. loader.setRequestHeader( this.requestHeader );
  33027. loader.setPath( this.path );
  33028. loader.setWithCredentials( scope.withCredentials );
  33029. loader.load( url, function ( buffer ) {
  33030. let texData;
  33031. try {
  33032. texData = scope.parse( buffer );
  33033. } catch ( error ) {
  33034. if ( onError !== undefined ) {
  33035. onError( error );
  33036. } else {
  33037. error( error );
  33038. return;
  33039. }
  33040. }
  33041. if ( texData.image !== undefined ) {
  33042. texture.image = texData.image;
  33043. } else if ( texData.data !== undefined ) {
  33044. texture.image.width = texData.width;
  33045. texture.image.height = texData.height;
  33046. texture.image.data = texData.data;
  33047. }
  33048. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33049. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33050. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33051. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33052. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33053. if ( texData.colorSpace !== undefined ) {
  33054. texture.colorSpace = texData.colorSpace;
  33055. }
  33056. if ( texData.flipY !== undefined ) {
  33057. texture.flipY = texData.flipY;
  33058. }
  33059. if ( texData.format !== undefined ) {
  33060. texture.format = texData.format;
  33061. }
  33062. if ( texData.type !== undefined ) {
  33063. texture.type = texData.type;
  33064. }
  33065. if ( texData.mipmaps !== undefined ) {
  33066. texture.mipmaps = texData.mipmaps;
  33067. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33068. }
  33069. if ( texData.mipmapCount === 1 ) {
  33070. texture.minFilter = LinearFilter;
  33071. }
  33072. if ( texData.generateMipmaps !== undefined ) {
  33073. texture.generateMipmaps = texData.generateMipmaps;
  33074. }
  33075. texture.needsUpdate = true;
  33076. if ( onLoad ) onLoad( texture, texData );
  33077. }, onProgress, onError );
  33078. return texture;
  33079. }
  33080. }
  33081. /**
  33082. * Class for loading textures. Images are internally
  33083. * loaded via {@link ImageLoader}.
  33084. *
  33085. * ```js
  33086. * const loader = new THREE.TextureLoader();
  33087. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33088. *
  33089. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33090. * ```
  33091. * Please note that `TextureLoader` has dropped support for progress
  33092. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33093. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33094. *
  33095. * @augments Loader
  33096. */
  33097. class TextureLoader extends Loader {
  33098. /**
  33099. * Constructs a new texture loader.
  33100. *
  33101. * @param {LoadingManager} [manager] - The loading manager.
  33102. */
  33103. constructor( manager ) {
  33104. super( manager );
  33105. }
  33106. /**
  33107. * Starts loading from the given URL and pass the fully loaded texture
  33108. * to the `onLoad()` callback. The method also returns a new texture object which can
  33109. * directly be used for material creation. If you do it this way, the texture
  33110. * may pop up in your scene once the respective loading process is finished.
  33111. *
  33112. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33113. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33114. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33115. * @param {onErrorCallback} onError - Executed when errors occur.
  33116. * @return {Texture} The texture.
  33117. */
  33118. load( url, onLoad, onProgress, onError ) {
  33119. const texture = new Texture();
  33120. const loader = new ImageLoader( this.manager );
  33121. loader.setCrossOrigin( this.crossOrigin );
  33122. loader.setPath( this.path );
  33123. loader.load( url, function ( image ) {
  33124. texture.image = image;
  33125. texture.needsUpdate = true;
  33126. if ( onLoad !== undefined ) {
  33127. onLoad( texture );
  33128. }
  33129. }, onProgress, onError );
  33130. return texture;
  33131. }
  33132. }
  33133. /**
  33134. * Abstract base class for lights - all other light types inherit the
  33135. * properties and methods described here.
  33136. *
  33137. * @abstract
  33138. * @augments Object3D
  33139. */
  33140. class Light extends Object3D {
  33141. /**
  33142. * Constructs a new light.
  33143. *
  33144. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33145. * @param {number} [intensity=1] - The light's strength/intensity.
  33146. */
  33147. constructor( color, intensity = 1 ) {
  33148. super();
  33149. /**
  33150. * This flag can be used for type testing.
  33151. *
  33152. * @type {boolean}
  33153. * @readonly
  33154. * @default true
  33155. */
  33156. this.isLight = true;
  33157. this.type = 'Light';
  33158. /**
  33159. * The light's color.
  33160. *
  33161. * @type {Color}
  33162. */
  33163. this.color = new Color( color );
  33164. /**
  33165. * The light's intensity.
  33166. *
  33167. * @type {number}
  33168. * @default 1
  33169. */
  33170. this.intensity = intensity;
  33171. }
  33172. /**
  33173. * Frees the GPU-related resources allocated by this instance. Call this
  33174. * method whenever this instance is no longer used in your app.
  33175. */
  33176. dispose() {
  33177. this.dispatchEvent( { type: 'dispose' } );
  33178. }
  33179. copy( source, recursive ) {
  33180. super.copy( source, recursive );
  33181. this.color.copy( source.color );
  33182. this.intensity = source.intensity;
  33183. return this;
  33184. }
  33185. toJSON( meta ) {
  33186. const data = super.toJSON( meta );
  33187. data.object.color = this.color.getHex();
  33188. data.object.intensity = this.intensity;
  33189. return data;
  33190. }
  33191. }
  33192. /**
  33193. * A light source positioned directly above the scene, with color fading from
  33194. * the sky color to the ground color.
  33195. *
  33196. * This light cannot be used to cast shadows.
  33197. *
  33198. * ```js
  33199. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33200. * scene.add( light );
  33201. * ```
  33202. *
  33203. * @augments Light
  33204. */
  33205. class HemisphereLight extends Light {
  33206. /**
  33207. * Constructs a new hemisphere light.
  33208. *
  33209. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33210. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33211. * @param {number} [intensity=1] - The light's strength/intensity.
  33212. */
  33213. constructor( skyColor, groundColor, intensity ) {
  33214. super( skyColor, intensity );
  33215. /**
  33216. * This flag can be used for type testing.
  33217. *
  33218. * @type {boolean}
  33219. * @readonly
  33220. * @default true
  33221. */
  33222. this.isHemisphereLight = true;
  33223. this.type = 'HemisphereLight';
  33224. this.position.copy( Object3D.DEFAULT_UP );
  33225. this.updateMatrix();
  33226. /**
  33227. * The light's ground color.
  33228. *
  33229. * @type {Color}
  33230. */
  33231. this.groundColor = new Color( groundColor );
  33232. }
  33233. copy( source, recursive ) {
  33234. super.copy( source, recursive );
  33235. this.groundColor.copy( source.groundColor );
  33236. return this;
  33237. }
  33238. toJSON( meta ) {
  33239. const data = super.toJSON( meta );
  33240. data.object.groundColor = this.groundColor.getHex();
  33241. return data;
  33242. }
  33243. }
  33244. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33245. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33246. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33247. /**
  33248. * Abstract base class for light shadow classes. These classes
  33249. * represent the shadow configuration for different light types.
  33250. *
  33251. * @abstract
  33252. */
  33253. class LightShadow {
  33254. /**
  33255. * Constructs a new light shadow.
  33256. *
  33257. * @param {Camera} camera - The light's view of the world.
  33258. */
  33259. constructor( camera ) {
  33260. /**
  33261. * The light's view of the world.
  33262. *
  33263. * @type {Camera}
  33264. */
  33265. this.camera = camera;
  33266. /**
  33267. * The intensity of the shadow. The default is `1`.
  33268. * Valid values are in the range `[0, 1]`.
  33269. *
  33270. * @type {number}
  33271. * @default 1
  33272. */
  33273. this.intensity = 1;
  33274. /**
  33275. * Shadow map bias, how much to add or subtract from the normalized depth
  33276. * when deciding whether a surface is in shadow.
  33277. *
  33278. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33279. * may help reduce artifacts in shadows.
  33280. *
  33281. * @type {number}
  33282. * @default 0
  33283. */
  33284. this.bias = 0;
  33285. /**
  33286. * Defines how much the position used to query the shadow map is offset along
  33287. * the object normal. The default is `0`. Increasing this value can be used to
  33288. * reduce shadow acne especially in large scenes where light shines onto
  33289. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33290. *
  33291. * @type {number}
  33292. * @default 0
  33293. */
  33294. this.normalBias = 0;
  33295. /**
  33296. * Setting this to values greater than 1 will blur the edges of the shadow.
  33297. * High values will cause unwanted banding effects in the shadows - a greater
  33298. * map size will allow for a higher value to be used here before these effects
  33299. * become visible.
  33300. *
  33301. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33302. *
  33303. * @type {number}
  33304. * @default 1
  33305. */
  33306. this.radius = 1;
  33307. /**
  33308. * The amount of samples to use when blurring a VSM shadow map.
  33309. *
  33310. * @type {number}
  33311. * @default 8
  33312. */
  33313. this.blurSamples = 8;
  33314. /**
  33315. * Defines the width and height of the shadow map. Higher values give better quality
  33316. * shadows at the cost of computation time. Values must be powers of two.
  33317. *
  33318. * @type {Vector2}
  33319. * @default (512,512)
  33320. */
  33321. this.mapSize = new Vector2( 512, 512 );
  33322. /**
  33323. * The type of shadow texture. The default is `UnsignedByteType`.
  33324. *
  33325. * @type {number}
  33326. * @default UnsignedByteType
  33327. */
  33328. this.mapType = UnsignedByteType;
  33329. /**
  33330. * The depth map generated using the internal camera; a location beyond a
  33331. * pixel's depth is in shadow. Computed internally during rendering.
  33332. *
  33333. * @type {?RenderTarget}
  33334. * @default null
  33335. */
  33336. this.map = null;
  33337. /**
  33338. * The distribution map generated using the internal camera; an occlusion is
  33339. * calculated based on the distribution of depths. Computed internally during
  33340. * rendering.
  33341. *
  33342. * @type {?RenderTarget}
  33343. * @default null
  33344. */
  33345. this.mapPass = null;
  33346. /**
  33347. * Model to shadow camera space, to compute location and depth in shadow map.
  33348. * This is computed internally during rendering.
  33349. *
  33350. * @type {Matrix4}
  33351. */
  33352. this.matrix = new Matrix4();
  33353. /**
  33354. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33355. * lighting / shadows, you may set this to `false`.
  33356. *
  33357. * @type {boolean}
  33358. * @default true
  33359. */
  33360. this.autoUpdate = true;
  33361. /**
  33362. * When set to `true`, shadow maps will be updated in the next `render` call.
  33363. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33364. * set this property to `true` and then make a render call to update the light's shadow.
  33365. *
  33366. * @type {boolean}
  33367. * @default false
  33368. */
  33369. this.needsUpdate = false;
  33370. this._frustum = new Frustum();
  33371. this._frameExtents = new Vector2( 1, 1 );
  33372. this._viewportCount = 1;
  33373. this._viewports = [
  33374. new Vector4( 0, 0, 1, 1 )
  33375. ];
  33376. }
  33377. /**
  33378. * Used internally by the renderer to get the number of viewports that need
  33379. * to be rendered for this shadow.
  33380. *
  33381. * @return {number} The viewport count.
  33382. */
  33383. getViewportCount() {
  33384. return this._viewportCount;
  33385. }
  33386. /**
  33387. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33388. *
  33389. * @return {Frustum} The shadow camera frustum.
  33390. */
  33391. getFrustum() {
  33392. return this._frustum;
  33393. }
  33394. /**
  33395. * Update the matrices for the camera and shadow, used internally by the renderer.
  33396. *
  33397. * @param {Light} light - The light for which the shadow is being rendered.
  33398. */
  33399. updateMatrices( light ) {
  33400. const shadowCamera = this.camera;
  33401. const shadowMatrix = this.matrix;
  33402. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33403. shadowCamera.position.copy( _lightPositionWorld$1 );
  33404. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33405. shadowCamera.lookAt( _lookTarget$1 );
  33406. shadowCamera.updateMatrixWorld();
  33407. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33408. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33409. if ( shadowCamera.reversedDepth ) {
  33410. shadowMatrix.set(
  33411. 0.5, 0.0, 0.0, 0.5,
  33412. 0.0, 0.5, 0.0, 0.5,
  33413. 0.0, 0.0, 1.0, 0.0,
  33414. 0.0, 0.0, 0.0, 1.0
  33415. );
  33416. } else {
  33417. shadowMatrix.set(
  33418. 0.5, 0.0, 0.0, 0.5,
  33419. 0.0, 0.5, 0.0, 0.5,
  33420. 0.0, 0.0, 0.5, 0.5,
  33421. 0.0, 0.0, 0.0, 1.0
  33422. );
  33423. }
  33424. shadowMatrix.multiply( _projScreenMatrix$1 );
  33425. }
  33426. /**
  33427. * Returns a viewport definition for the given viewport index.
  33428. *
  33429. * @param {number} viewportIndex - The viewport index.
  33430. * @return {Vector4} The viewport.
  33431. */
  33432. getViewport( viewportIndex ) {
  33433. return this._viewports[ viewportIndex ];
  33434. }
  33435. /**
  33436. * Returns the frame extends.
  33437. *
  33438. * @return {Vector2} The frame extends.
  33439. */
  33440. getFrameExtents() {
  33441. return this._frameExtents;
  33442. }
  33443. /**
  33444. * Frees the GPU-related resources allocated by this instance. Call this
  33445. * method whenever this instance is no longer used in your app.
  33446. */
  33447. dispose() {
  33448. if ( this.map ) {
  33449. this.map.dispose();
  33450. }
  33451. if ( this.mapPass ) {
  33452. this.mapPass.dispose();
  33453. }
  33454. }
  33455. /**
  33456. * Copies the values of the given light shadow instance to this instance.
  33457. *
  33458. * @param {LightShadow} source - The light shadow to copy.
  33459. * @return {LightShadow} A reference to this light shadow instance.
  33460. */
  33461. copy( source ) {
  33462. this.camera = source.camera.clone();
  33463. this.intensity = source.intensity;
  33464. this.bias = source.bias;
  33465. this.radius = source.radius;
  33466. this.autoUpdate = source.autoUpdate;
  33467. this.needsUpdate = source.needsUpdate;
  33468. this.normalBias = source.normalBias;
  33469. this.blurSamples = source.blurSamples;
  33470. this.mapSize.copy( source.mapSize );
  33471. return this;
  33472. }
  33473. /**
  33474. * Returns a new light shadow instance with copied values from this instance.
  33475. *
  33476. * @return {LightShadow} A clone of this instance.
  33477. */
  33478. clone() {
  33479. return new this.constructor().copy( this );
  33480. }
  33481. /**
  33482. * Serializes the light shadow into JSON.
  33483. *
  33484. * @return {Object} A JSON object representing the serialized light shadow.
  33485. * @see {@link ObjectLoader#parse}
  33486. */
  33487. toJSON() {
  33488. const object = {};
  33489. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33490. if ( this.bias !== 0 ) object.bias = this.bias;
  33491. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33492. if ( this.radius !== 1 ) object.radius = this.radius;
  33493. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33494. object.camera = this.camera.toJSON( false ).object;
  33495. delete object.camera.matrix;
  33496. return object;
  33497. }
  33498. }
  33499. /**
  33500. * Represents the shadow configuration of directional lights.
  33501. *
  33502. * @augments LightShadow
  33503. */
  33504. class SpotLightShadow extends LightShadow {
  33505. /**
  33506. * Constructs a new spot light shadow.
  33507. */
  33508. constructor() {
  33509. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33510. /**
  33511. * This flag can be used for type testing.
  33512. *
  33513. * @type {boolean}
  33514. * @readonly
  33515. * @default true
  33516. */
  33517. this.isSpotLightShadow = true;
  33518. /**
  33519. * Used to focus the shadow camera. The camera's field of view is set as a
  33520. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33521. *
  33522. * @type {number}
  33523. * @default 1
  33524. */
  33525. this.focus = 1;
  33526. /**
  33527. * Texture aspect ratio.
  33528. *
  33529. * @type {number}
  33530. * @default 1
  33531. */
  33532. this.aspect = 1;
  33533. }
  33534. updateMatrices( light ) {
  33535. const camera = this.camera;
  33536. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33537. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33538. const far = light.distance || camera.far;
  33539. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33540. camera.fov = fov;
  33541. camera.aspect = aspect;
  33542. camera.far = far;
  33543. camera.updateProjectionMatrix();
  33544. }
  33545. super.updateMatrices( light );
  33546. }
  33547. copy( source ) {
  33548. super.copy( source );
  33549. this.focus = source.focus;
  33550. return this;
  33551. }
  33552. }
  33553. /**
  33554. * This light gets emitted from a single point in one direction, along a cone
  33555. * that increases in size the further from the light it gets.
  33556. *
  33557. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33558. *
  33559. * ```js
  33560. * // white spotlight shining from the side, modulated by a texture
  33561. * const spotLight = new THREE.SpotLight( 0xffffff );
  33562. * spotLight.position.set( 100, 1000, 100 );
  33563. * spotLight.map = new THREE.TextureLoader().load( url );
  33564. *
  33565. * spotLight.castShadow = true;
  33566. * spotLight.shadow.mapSize.width = 1024;
  33567. * spotLight.shadow.mapSize.height = 1024;
  33568. * spotLight.shadow.camera.near = 500;
  33569. * spotLight.shadow.camera.far = 4000;
  33570. * spotLight.shadow.camera.fov = 30;s
  33571. * ```
  33572. *
  33573. * @augments Light
  33574. */
  33575. class SpotLight extends Light {
  33576. /**
  33577. * Constructs a new spot light.
  33578. *
  33579. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33580. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33581. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33582. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33583. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33584. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33585. */
  33586. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33587. super( color, intensity );
  33588. /**
  33589. * This flag can be used for type testing.
  33590. *
  33591. * @type {boolean}
  33592. * @readonly
  33593. * @default true
  33594. */
  33595. this.isSpotLight = true;
  33596. this.type = 'SpotLight';
  33597. this.position.copy( Object3D.DEFAULT_UP );
  33598. this.updateMatrix();
  33599. /**
  33600. * The spot light points from its position to the
  33601. * target's position.
  33602. *
  33603. * For the target's position to be changed to anything other
  33604. * than the default, it must be added to the scene.
  33605. *
  33606. * It is also possible to set the target to be another 3D object
  33607. * in the scene. The light will now track the target object.
  33608. *
  33609. * @type {Object3D}
  33610. */
  33611. this.target = new Object3D();
  33612. /**
  33613. * Maximum range of the light. `0` means no limit.
  33614. *
  33615. * @type {number}
  33616. * @default 0
  33617. */
  33618. this.distance = distance;
  33619. /**
  33620. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33621. *
  33622. * @type {number}
  33623. * @default Math.PI/3
  33624. */
  33625. this.angle = angle;
  33626. /**
  33627. * Percent of the spotlight cone that is attenuated due to penumbra.
  33628. * Value range is `[0,1]`.
  33629. *
  33630. * @type {number}
  33631. * @default 0
  33632. */
  33633. this.penumbra = penumbra;
  33634. /**
  33635. * The amount the light dims along the distance of the light. In context of
  33636. * physically-correct rendering the default value should not be changed.
  33637. *
  33638. * @type {number}
  33639. * @default 2
  33640. */
  33641. this.decay = decay;
  33642. /**
  33643. * A texture used to modulate the color of the light. The spot light
  33644. * color is mixed with the RGB value of this texture, with a ratio
  33645. * corresponding to its alpha value. The cookie-like masking effect is
  33646. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33647. *
  33648. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33649. *
  33650. * @type {?Texture}
  33651. * @default null
  33652. */
  33653. this.map = null;
  33654. /**
  33655. * This property holds the light's shadow configuration.
  33656. *
  33657. * @type {SpotLightShadow}
  33658. */
  33659. this.shadow = new SpotLightShadow();
  33660. }
  33661. /**
  33662. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33663. * Changing the power will also change the light's intensity.
  33664. *
  33665. * @type {number}
  33666. */
  33667. get power() {
  33668. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33669. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33670. return this.intensity * Math.PI;
  33671. }
  33672. set power( power ) {
  33673. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33674. this.intensity = power / Math.PI;
  33675. }
  33676. dispose() {
  33677. super.dispose();
  33678. this.shadow.dispose();
  33679. }
  33680. copy( source, recursive ) {
  33681. super.copy( source, recursive );
  33682. this.distance = source.distance;
  33683. this.angle = source.angle;
  33684. this.penumbra = source.penumbra;
  33685. this.decay = source.decay;
  33686. this.target = source.target.clone();
  33687. this.map = source.map;
  33688. this.shadow = source.shadow.clone();
  33689. return this;
  33690. }
  33691. toJSON( meta ) {
  33692. const data = super.toJSON( meta );
  33693. data.object.distance = this.distance;
  33694. data.object.angle = this.angle;
  33695. data.object.decay = this.decay;
  33696. data.object.penumbra = this.penumbra;
  33697. data.object.target = this.target.uuid;
  33698. if ( this.map && this.map.isTexture ) data.object.map = this.map.toJSON( meta ).uuid;
  33699. data.object.shadow = this.shadow.toJSON();
  33700. return data;
  33701. }
  33702. }
  33703. /**
  33704. * Represents the shadow configuration of point lights.
  33705. *
  33706. * @augments LightShadow
  33707. */
  33708. class PointLightShadow extends LightShadow {
  33709. /**
  33710. * Constructs a new point light shadow.
  33711. */
  33712. constructor() {
  33713. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33714. /**
  33715. * This flag can be used for type testing.
  33716. *
  33717. * @type {boolean}
  33718. * @readonly
  33719. * @default true
  33720. */
  33721. this.isPointLightShadow = true;
  33722. }
  33723. }
  33724. /**
  33725. * A light that gets emitted from a single point in all directions. A common
  33726. * use case for this is to replicate the light emitted from a bare
  33727. * lightbulb.
  33728. *
  33729. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33730. *
  33731. * ```js
  33732. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33733. * light.position.set( 50, 50, 50 );
  33734. * scene.add( light );
  33735. * ```
  33736. *
  33737. * @augments Light
  33738. */
  33739. class PointLight extends Light {
  33740. /**
  33741. * Constructs a new point light.
  33742. *
  33743. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33744. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33745. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33746. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33747. */
  33748. constructor( color, intensity, distance = 0, decay = 2 ) {
  33749. super( color, intensity );
  33750. /**
  33751. * This flag can be used for type testing.
  33752. *
  33753. * @type {boolean}
  33754. * @readonly
  33755. * @default true
  33756. */
  33757. this.isPointLight = true;
  33758. this.type = 'PointLight';
  33759. /**
  33760. * When distance is zero, light will attenuate according to inverse-square
  33761. * law to infinite distance. When distance is non-zero, light will attenuate
  33762. * according to inverse-square law until near the distance cutoff, where it
  33763. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33764. * physically correct.
  33765. *
  33766. * @type {number}
  33767. * @default 0
  33768. */
  33769. this.distance = distance;
  33770. /**
  33771. * The amount the light dims along the distance of the light. In context of
  33772. * physically-correct rendering the default value should not be changed.
  33773. *
  33774. * @type {number}
  33775. * @default 2
  33776. */
  33777. this.decay = decay;
  33778. /**
  33779. * This property holds the light's shadow configuration.
  33780. *
  33781. * @type {PointLightShadow}
  33782. */
  33783. this.shadow = new PointLightShadow();
  33784. }
  33785. /**
  33786. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33787. * Changing the power will also change the light's intensity.
  33788. *
  33789. * @type {number}
  33790. */
  33791. get power() {
  33792. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33793. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33794. return this.intensity * 4 * Math.PI;
  33795. }
  33796. set power( power ) {
  33797. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33798. this.intensity = power / ( 4 * Math.PI );
  33799. }
  33800. dispose() {
  33801. super.dispose();
  33802. this.shadow.dispose();
  33803. }
  33804. copy( source, recursive ) {
  33805. super.copy( source, recursive );
  33806. this.distance = source.distance;
  33807. this.decay = source.decay;
  33808. this.shadow = source.shadow.clone();
  33809. return this;
  33810. }
  33811. toJSON( meta ) {
  33812. const data = super.toJSON( meta );
  33813. data.object.distance = this.distance;
  33814. data.object.decay = this.decay;
  33815. data.object.shadow = this.shadow.toJSON();
  33816. return data;
  33817. }
  33818. }
  33819. /**
  33820. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  33821. *
  33822. * In this projection mode, an object's size in the rendered image stays
  33823. * constant regardless of its distance from the camera. This can be useful
  33824. * for rendering 2D scenes and UI elements, amongst other things.
  33825. *
  33826. * ```js
  33827. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33828. * scene.add( camera );
  33829. * ```
  33830. *
  33831. * @augments Camera
  33832. */
  33833. class OrthographicCamera extends Camera {
  33834. /**
  33835. * Constructs a new orthographic camera.
  33836. *
  33837. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33838. * @param {number} [right=1] - The right plane of the camera's frustum.
  33839. * @param {number} [top=1] - The top plane of the camera's frustum.
  33840. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33841. * @param {number} [near=0.1] - The camera's near plane.
  33842. * @param {number} [far=2000] - The camera's far plane.
  33843. */
  33844. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33845. super();
  33846. /**
  33847. * This flag can be used for type testing.
  33848. *
  33849. * @type {boolean}
  33850. * @readonly
  33851. * @default true
  33852. */
  33853. this.isOrthographicCamera = true;
  33854. this.type = 'OrthographicCamera';
  33855. /**
  33856. * The zoom factor of the camera.
  33857. *
  33858. * @type {number}
  33859. * @default 1
  33860. */
  33861. this.zoom = 1;
  33862. /**
  33863. * Represents the frustum window specification. This property should not be edited
  33864. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33865. *
  33866. * @type {?Object}
  33867. * @default null
  33868. */
  33869. this.view = null;
  33870. /**
  33871. * The left plane of the camera's frustum.
  33872. *
  33873. * @type {number}
  33874. * @default -1
  33875. */
  33876. this.left = left;
  33877. /**
  33878. * The right plane of the camera's frustum.
  33879. *
  33880. * @type {number}
  33881. * @default 1
  33882. */
  33883. this.right = right;
  33884. /**
  33885. * The top plane of the camera's frustum.
  33886. *
  33887. * @type {number}
  33888. * @default 1
  33889. */
  33890. this.top = top;
  33891. /**
  33892. * The bottom plane of the camera's frustum.
  33893. *
  33894. * @type {number}
  33895. * @default -1
  33896. */
  33897. this.bottom = bottom;
  33898. /**
  33899. * The camera's near plane. The valid range is greater than `0`
  33900. * and less than the current value of {@link OrthographicCamera#far}.
  33901. *
  33902. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33903. * valid value for an orthographic camera's near plane.
  33904. *
  33905. * @type {number}
  33906. * @default 0.1
  33907. */
  33908. this.near = near;
  33909. /**
  33910. * The camera's far plane. Must be greater than the
  33911. * current value of {@link OrthographicCamera#near}.
  33912. *
  33913. * @type {number}
  33914. * @default 2000
  33915. */
  33916. this.far = far;
  33917. this.updateProjectionMatrix();
  33918. }
  33919. copy( source, recursive ) {
  33920. super.copy( source, recursive );
  33921. this.left = source.left;
  33922. this.right = source.right;
  33923. this.top = source.top;
  33924. this.bottom = source.bottom;
  33925. this.near = source.near;
  33926. this.far = source.far;
  33927. this.zoom = source.zoom;
  33928. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33929. return this;
  33930. }
  33931. /**
  33932. * Sets an offset in a larger frustum. This is useful for multi-window or
  33933. * multi-monitor/multi-machine setups.
  33934. *
  33935. * @param {number} fullWidth - The full width of multiview setup.
  33936. * @param {number} fullHeight - The full height of multiview setup.
  33937. * @param {number} x - The horizontal offset of the subcamera.
  33938. * @param {number} y - The vertical offset of the subcamera.
  33939. * @param {number} width - The width of subcamera.
  33940. * @param {number} height - The height of subcamera.
  33941. * @see {@link PerspectiveCamera#setViewOffset}
  33942. */
  33943. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33944. if ( this.view === null ) {
  33945. this.view = {
  33946. enabled: true,
  33947. fullWidth: 1,
  33948. fullHeight: 1,
  33949. offsetX: 0,
  33950. offsetY: 0,
  33951. width: 1,
  33952. height: 1
  33953. };
  33954. }
  33955. this.view.enabled = true;
  33956. this.view.fullWidth = fullWidth;
  33957. this.view.fullHeight = fullHeight;
  33958. this.view.offsetX = x;
  33959. this.view.offsetY = y;
  33960. this.view.width = width;
  33961. this.view.height = height;
  33962. this.updateProjectionMatrix();
  33963. }
  33964. /**
  33965. * Removes the view offset from the projection matrix.
  33966. */
  33967. clearViewOffset() {
  33968. if ( this.view !== null ) {
  33969. this.view.enabled = false;
  33970. }
  33971. this.updateProjectionMatrix();
  33972. }
  33973. /**
  33974. * Updates the camera's projection matrix. Must be called after any change of
  33975. * camera properties.
  33976. */
  33977. updateProjectionMatrix() {
  33978. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33979. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33980. const cx = ( this.right + this.left ) / 2;
  33981. const cy = ( this.top + this.bottom ) / 2;
  33982. let left = cx - dx;
  33983. let right = cx + dx;
  33984. let top = cy + dy;
  33985. let bottom = cy - dy;
  33986. if ( this.view !== null && this.view.enabled ) {
  33987. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33988. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33989. left += scaleW * this.view.offsetX;
  33990. right = left + scaleW * this.view.width;
  33991. top -= scaleH * this.view.offsetY;
  33992. bottom = top - scaleH * this.view.height;
  33993. }
  33994. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  33995. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  33996. }
  33997. toJSON( meta ) {
  33998. const data = super.toJSON( meta );
  33999. data.object.zoom = this.zoom;
  34000. data.object.left = this.left;
  34001. data.object.right = this.right;
  34002. data.object.top = this.top;
  34003. data.object.bottom = this.bottom;
  34004. data.object.near = this.near;
  34005. data.object.far = this.far;
  34006. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34007. return data;
  34008. }
  34009. }
  34010. /**
  34011. * Represents the shadow configuration of directional lights.
  34012. *
  34013. * @augments LightShadow
  34014. */
  34015. class DirectionalLightShadow extends LightShadow {
  34016. /**
  34017. * Constructs a new directional light shadow.
  34018. */
  34019. constructor() {
  34020. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34021. /**
  34022. * This flag can be used for type testing.
  34023. *
  34024. * @type {boolean}
  34025. * @readonly
  34026. * @default true
  34027. */
  34028. this.isDirectionalLightShadow = true;
  34029. }
  34030. }
  34031. /**
  34032. * A light that gets emitted in a specific direction. This light will behave
  34033. * as though it is infinitely far away and the rays produced from it are all
  34034. * parallel. The common use case for this is to simulate daylight; the sun is
  34035. * far enough away that its position can be considered to be infinite, and
  34036. * all light rays coming from it are parallel.
  34037. *
  34038. * A common point of confusion for directional lights is that setting the
  34039. * rotation has no effect. This is because three.js's DirectionalLight is the
  34040. * equivalent to what is often called a 'Target Direct Light' in other
  34041. * applications.
  34042. *
  34043. * This means that its direction is calculated as pointing from the light's
  34044. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34045. * (as opposed to a 'Free Direct Light' that just has a rotation
  34046. * component).
  34047. *
  34048. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34049. *
  34050. * ```js
  34051. * // White directional light at half intensity shining from the top.
  34052. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34053. * scene.add( directionalLight );
  34054. * ```
  34055. *
  34056. * @augments Light
  34057. */
  34058. class DirectionalLight extends Light {
  34059. /**
  34060. * Constructs a new directional light.
  34061. *
  34062. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34063. * @param {number} [intensity=1] - The light's strength/intensity.
  34064. */
  34065. constructor( color, intensity ) {
  34066. super( color, intensity );
  34067. /**
  34068. * This flag can be used for type testing.
  34069. *
  34070. * @type {boolean}
  34071. * @readonly
  34072. * @default true
  34073. */
  34074. this.isDirectionalLight = true;
  34075. this.type = 'DirectionalLight';
  34076. this.position.copy( Object3D.DEFAULT_UP );
  34077. this.updateMatrix();
  34078. /**
  34079. * The directional light points from its position to the
  34080. * target's position.
  34081. *
  34082. * For the target's position to be changed to anything other
  34083. * than the default, it must be added to the scene.
  34084. *
  34085. * It is also possible to set the target to be another 3D object
  34086. * in the scene. The light will now track the target object.
  34087. *
  34088. * @type {Object3D}
  34089. */
  34090. this.target = new Object3D();
  34091. /**
  34092. * This property holds the light's shadow configuration.
  34093. *
  34094. * @type {DirectionalLightShadow}
  34095. */
  34096. this.shadow = new DirectionalLightShadow();
  34097. }
  34098. dispose() {
  34099. super.dispose();
  34100. this.shadow.dispose();
  34101. }
  34102. copy( source ) {
  34103. super.copy( source );
  34104. this.target = source.target.clone();
  34105. this.shadow = source.shadow.clone();
  34106. return this;
  34107. }
  34108. toJSON( meta ) {
  34109. const data = super.toJSON( meta );
  34110. data.object.shadow = this.shadow.toJSON();
  34111. data.object.target = this.target.uuid;
  34112. return data;
  34113. }
  34114. }
  34115. /**
  34116. * This light globally illuminates all objects in the scene equally.
  34117. *
  34118. * It cannot be used to cast shadows as it does not have a direction.
  34119. *
  34120. * ```js
  34121. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34122. * scene.add( light );
  34123. * ```
  34124. *
  34125. * @augments Light
  34126. */
  34127. class AmbientLight extends Light {
  34128. /**
  34129. * Constructs a new ambient light.
  34130. *
  34131. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34132. * @param {number} [intensity=1] - The light's strength/intensity.
  34133. */
  34134. constructor( color, intensity ) {
  34135. super( color, intensity );
  34136. /**
  34137. * This flag can be used for type testing.
  34138. *
  34139. * @type {boolean}
  34140. * @readonly
  34141. * @default true
  34142. */
  34143. this.isAmbientLight = true;
  34144. this.type = 'AmbientLight';
  34145. }
  34146. }
  34147. /**
  34148. * This class emits light uniformly across the face a rectangular plane.
  34149. * This light type can be used to simulate light sources such as bright
  34150. * windows or strip lighting.
  34151. *
  34152. * Important Notes:
  34153. *
  34154. * - There is no shadow support.
  34155. * - Only PBR materials are supported.
  34156. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34157. * into your app and init the uniforms/textures.
  34158. *
  34159. * ```js
  34160. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34161. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34162. *
  34163. * const intensity = 1; const width = 10; const height = 10;
  34164. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34165. * rectLight.position.set( 5, 5, 0 );
  34166. * rectLight.lookAt( 0, 0, 0 );
  34167. * scene.add( rectLight )
  34168. * ```
  34169. *
  34170. * @augments Light
  34171. */
  34172. class RectAreaLight extends Light {
  34173. /**
  34174. * Constructs a new area light.
  34175. *
  34176. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34177. * @param {number} [intensity=1] - The light's strength/intensity.
  34178. * @param {number} [width=10] - The width of the light.
  34179. * @param {number} [height=10] - The height of the light.
  34180. */
  34181. constructor( color, intensity, width = 10, height = 10 ) {
  34182. super( color, intensity );
  34183. /**
  34184. * This flag can be used for type testing.
  34185. *
  34186. * @type {boolean}
  34187. * @readonly
  34188. * @default true
  34189. */
  34190. this.isRectAreaLight = true;
  34191. this.type = 'RectAreaLight';
  34192. /**
  34193. * The width of the light.
  34194. *
  34195. * @type {number}
  34196. * @default 10
  34197. */
  34198. this.width = width;
  34199. /**
  34200. * The height of the light.
  34201. *
  34202. * @type {number}
  34203. * @default 10
  34204. */
  34205. this.height = height;
  34206. }
  34207. /**
  34208. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34209. * Changing the power will also change the light's intensity.
  34210. *
  34211. * @type {number}
  34212. */
  34213. get power() {
  34214. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34215. return this.intensity * this.width * this.height * Math.PI;
  34216. }
  34217. set power( power ) {
  34218. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34219. this.intensity = power / ( this.width * this.height * Math.PI );
  34220. }
  34221. copy( source ) {
  34222. super.copy( source );
  34223. this.width = source.width;
  34224. this.height = source.height;
  34225. return this;
  34226. }
  34227. toJSON( meta ) {
  34228. const data = super.toJSON( meta );
  34229. data.object.width = this.width;
  34230. data.object.height = this.height;
  34231. return data;
  34232. }
  34233. }
  34234. /**
  34235. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34236. * to encode lighting information.
  34237. *
  34238. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34239. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34240. */
  34241. class SphericalHarmonics3 {
  34242. /**
  34243. * Constructs a new spherical harmonics.
  34244. */
  34245. constructor() {
  34246. /**
  34247. * This flag can be used for type testing.
  34248. *
  34249. * @type {boolean}
  34250. * @readonly
  34251. * @default true
  34252. */
  34253. this.isSphericalHarmonics3 = true;
  34254. /**
  34255. * An array holding the (9) SH coefficients.
  34256. *
  34257. * @type {Array<Vector3>}
  34258. */
  34259. this.coefficients = [];
  34260. for ( let i = 0; i < 9; i ++ ) {
  34261. this.coefficients.push( new Vector3() );
  34262. }
  34263. }
  34264. /**
  34265. * Sets the given SH coefficients to this instance by copying
  34266. * the values.
  34267. *
  34268. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34269. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34270. */
  34271. set( coefficients ) {
  34272. for ( let i = 0; i < 9; i ++ ) {
  34273. this.coefficients[ i ].copy( coefficients[ i ] );
  34274. }
  34275. return this;
  34276. }
  34277. /**
  34278. * Sets all SH coefficients to `0`.
  34279. *
  34280. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34281. */
  34282. zero() {
  34283. for ( let i = 0; i < 9; i ++ ) {
  34284. this.coefficients[ i ].set( 0, 0, 0 );
  34285. }
  34286. return this;
  34287. }
  34288. /**
  34289. * Returns the radiance in the direction of the given normal.
  34290. *
  34291. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34292. * @param {Vector3} target - The target vector that is used to store the method's result.
  34293. * @return {Vector3} The radiance.
  34294. */
  34295. getAt( normal, target ) {
  34296. // normal is assumed to be unit length
  34297. const x = normal.x, y = normal.y, z = normal.z;
  34298. const coeff = this.coefficients;
  34299. // band 0
  34300. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34301. // band 1
  34302. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34303. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34304. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34305. // band 2
  34306. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34307. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34308. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34309. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34310. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34311. return target;
  34312. }
  34313. /**
  34314. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34315. * direction of the given normal.
  34316. *
  34317. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34318. * @param {Vector3} target - The target vector that is used to store the method's result.
  34319. * @return {Vector3} The irradiance.
  34320. */
  34321. getIrradianceAt( normal, target ) {
  34322. // normal is assumed to be unit length
  34323. const x = normal.x, y = normal.y, z = normal.z;
  34324. const coeff = this.coefficients;
  34325. // band 0
  34326. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34327. // band 1
  34328. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34329. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34330. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34331. // band 2
  34332. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34333. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34334. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34335. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34336. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34337. return target;
  34338. }
  34339. /**
  34340. * Adds the given SH to this instance.
  34341. *
  34342. * @param {SphericalHarmonics3} sh - The SH to add.
  34343. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34344. */
  34345. add( sh ) {
  34346. for ( let i = 0; i < 9; i ++ ) {
  34347. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34348. }
  34349. return this;
  34350. }
  34351. /**
  34352. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34353. * {@link SphericalHarmonics3#scale} at once.
  34354. *
  34355. * @param {SphericalHarmonics3} sh - The SH to add.
  34356. * @param {number} s - The scale factor.
  34357. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34358. */
  34359. addScaledSH( sh, s ) {
  34360. for ( let i = 0; i < 9; i ++ ) {
  34361. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34362. }
  34363. return this;
  34364. }
  34365. /**
  34366. * Scales this SH by the given scale factor.
  34367. *
  34368. * @param {number} s - The scale factor.
  34369. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34370. */
  34371. scale( s ) {
  34372. for ( let i = 0; i < 9; i ++ ) {
  34373. this.coefficients[ i ].multiplyScalar( s );
  34374. }
  34375. return this;
  34376. }
  34377. /**
  34378. * Linear interpolates between the given SH and this instance by the given
  34379. * alpha factor.
  34380. *
  34381. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34382. * @param {number} alpha - The alpha factor.
  34383. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34384. */
  34385. lerp( sh, alpha ) {
  34386. for ( let i = 0; i < 9; i ++ ) {
  34387. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34388. }
  34389. return this;
  34390. }
  34391. /**
  34392. * Returns `true` if this spherical harmonics is equal with the given one.
  34393. *
  34394. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34395. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34396. */
  34397. equals( sh ) {
  34398. for ( let i = 0; i < 9; i ++ ) {
  34399. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34400. return false;
  34401. }
  34402. }
  34403. return true;
  34404. }
  34405. /**
  34406. * Copies the values of the given spherical harmonics to this instance.
  34407. *
  34408. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34409. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34410. */
  34411. copy( sh ) {
  34412. return this.set( sh.coefficients );
  34413. }
  34414. /**
  34415. * Returns a new spherical harmonics with copied values from this instance.
  34416. *
  34417. * @return {SphericalHarmonics3} A clone of this instance.
  34418. */
  34419. clone() {
  34420. return new this.constructor().copy( this );
  34421. }
  34422. /**
  34423. * Sets the SH coefficients of this instance from the given array.
  34424. *
  34425. * @param {Array<number>} array - An array holding the SH coefficients.
  34426. * @param {number} [offset=0] - The array offset where to start copying.
  34427. * @return {SphericalHarmonics3} A clone of this instance.
  34428. */
  34429. fromArray( array, offset = 0 ) {
  34430. const coefficients = this.coefficients;
  34431. for ( let i = 0; i < 9; i ++ ) {
  34432. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34433. }
  34434. return this;
  34435. }
  34436. /**
  34437. * Returns an array with the SH coefficients, or copies them into the provided
  34438. * array. The coefficients are represented as numbers.
  34439. *
  34440. * @param {Array<number>} [array=[]] - The target array.
  34441. * @param {number} [offset=0] - The array offset where to start copying.
  34442. * @return {Array<number>} An array with flat SH coefficients.
  34443. */
  34444. toArray( array = [], offset = 0 ) {
  34445. const coefficients = this.coefficients;
  34446. for ( let i = 0; i < 9; i ++ ) {
  34447. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34448. }
  34449. return array;
  34450. }
  34451. /**
  34452. * Computes the SH basis for the given normal vector.
  34453. *
  34454. * @param {Vector3} normal - The normal.
  34455. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34456. */
  34457. static getBasisAt( normal, shBasis ) {
  34458. // normal is assumed to be unit length
  34459. const x = normal.x, y = normal.y, z = normal.z;
  34460. // band 0
  34461. shBasis[ 0 ] = 0.282095;
  34462. // band 1
  34463. shBasis[ 1 ] = 0.488603 * y;
  34464. shBasis[ 2 ] = 0.488603 * z;
  34465. shBasis[ 3 ] = 0.488603 * x;
  34466. // band 2
  34467. shBasis[ 4 ] = 1.092548 * x * y;
  34468. shBasis[ 5 ] = 1.092548 * y * z;
  34469. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34470. shBasis[ 7 ] = 1.092548 * x * z;
  34471. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34472. }
  34473. }
  34474. /**
  34475. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34476. * classical light sources (e.g. directional, point or spot lights), light
  34477. * probes do not emit light. Instead they store information about light
  34478. * passing through 3D space. During rendering, the light that hits a 3D
  34479. * object is approximated by using the data from the light probe.
  34480. *
  34481. * Light probes are usually created from (radiance) environment maps. The
  34482. * class {@link LightProbeGenerator} can be used to create light probes from
  34483. * cube textures or render targets. However, light estimation data could also
  34484. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34485. * augmented reality content that reacts to real world lighting.
  34486. *
  34487. * The current probe implementation in three.js supports so-called diffuse
  34488. * light probes. This type of light probe is functionally equivalent to an
  34489. * irradiance environment map.
  34490. *
  34491. * @augments Light
  34492. */
  34493. class LightProbe extends Light {
  34494. /**
  34495. * Constructs a new light probe.
  34496. *
  34497. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34498. * @param {number} [intensity=1] - The light's strength/intensity.
  34499. */
  34500. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34501. super( undefined, intensity );
  34502. /**
  34503. * This flag can be used for type testing.
  34504. *
  34505. * @type {boolean}
  34506. * @readonly
  34507. * @default true
  34508. */
  34509. this.isLightProbe = true;
  34510. /**
  34511. * A light probe uses spherical harmonics to encode lighting information.
  34512. *
  34513. * @type {SphericalHarmonics3}
  34514. */
  34515. this.sh = sh;
  34516. }
  34517. copy( source ) {
  34518. super.copy( source );
  34519. this.sh.copy( source.sh );
  34520. return this;
  34521. }
  34522. toJSON( meta ) {
  34523. const data = super.toJSON( meta );
  34524. data.object.sh = this.sh.toArray();
  34525. return data;
  34526. }
  34527. }
  34528. /**
  34529. * Class for loading materials. The files are internally
  34530. * loaded via {@link FileLoader}.
  34531. *
  34532. * ```js
  34533. * const loader = new THREE.MaterialLoader();
  34534. * const material = await loader.loadAsync( 'material.json' );
  34535. * ```
  34536. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34537. *
  34538. * @augments Loader
  34539. */
  34540. class MaterialLoader extends Loader {
  34541. /**
  34542. * Constructs a new material loader.
  34543. *
  34544. * @param {LoadingManager} [manager] - The loading manager.
  34545. */
  34546. constructor( manager ) {
  34547. super( manager );
  34548. /**
  34549. * A dictionary holding textures used by the material.
  34550. *
  34551. * @type {Object<string,Texture>}
  34552. */
  34553. this.textures = {};
  34554. }
  34555. /**
  34556. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34557. *
  34558. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34559. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34560. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34561. * @param {onErrorCallback} onError - Executed when errors occur.
  34562. */
  34563. load( url, onLoad, onProgress, onError ) {
  34564. const scope = this;
  34565. const loader = new FileLoader( scope.manager );
  34566. loader.setPath( scope.path );
  34567. loader.setRequestHeader( scope.requestHeader );
  34568. loader.setWithCredentials( scope.withCredentials );
  34569. loader.load( url, function ( text ) {
  34570. try {
  34571. onLoad( scope.parse( JSON.parse( text ) ) );
  34572. } catch ( e ) {
  34573. if ( onError ) {
  34574. onError( e );
  34575. } else {
  34576. error( e );
  34577. }
  34578. scope.manager.itemError( url );
  34579. }
  34580. }, onProgress, onError );
  34581. }
  34582. /**
  34583. * Parses the given JSON object and returns a material.
  34584. *
  34585. * @param {Object} json - The serialized material.
  34586. * @return {Material} The parsed material.
  34587. */
  34588. parse( json ) {
  34589. const textures = this.textures;
  34590. function getTexture( name ) {
  34591. if ( textures[ name ] === undefined ) {
  34592. warn( 'MaterialLoader: Undefined texture', name );
  34593. }
  34594. return textures[ name ];
  34595. }
  34596. const material = this.createMaterialFromType( json.type );
  34597. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34598. if ( json.name !== undefined ) material.name = json.name;
  34599. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34600. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34601. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34602. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34603. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34604. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34605. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34606. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34607. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34608. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34609. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34610. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34611. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34612. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34613. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34614. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34615. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34616. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34617. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34618. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34619. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34620. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34621. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34622. if ( json.fog !== undefined ) material.fog = json.fog;
  34623. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34624. if ( json.blending !== undefined ) material.blending = json.blending;
  34625. if ( json.combine !== undefined ) material.combine = json.combine;
  34626. if ( json.side !== undefined ) material.side = json.side;
  34627. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34628. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34629. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34630. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34631. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34632. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34633. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34634. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34635. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34636. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34637. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34638. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34639. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34640. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34641. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34642. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34643. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34644. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34645. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34646. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34647. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34648. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34649. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34650. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34651. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34652. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34653. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34654. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34655. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34656. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34657. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34658. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34659. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34660. if ( json.scale !== undefined ) material.scale = json.scale;
  34661. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34662. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34663. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34664. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34665. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34666. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34667. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34668. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34669. if ( json.visible !== undefined ) material.visible = json.visible;
  34670. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34671. if ( json.userData !== undefined ) material.userData = json.userData;
  34672. if ( json.vertexColors !== undefined ) {
  34673. if ( typeof json.vertexColors === 'number' ) {
  34674. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34675. } else {
  34676. material.vertexColors = json.vertexColors;
  34677. }
  34678. }
  34679. // Shader Material
  34680. if ( json.uniforms !== undefined ) {
  34681. for ( const name in json.uniforms ) {
  34682. const uniform = json.uniforms[ name ];
  34683. material.uniforms[ name ] = {};
  34684. switch ( uniform.type ) {
  34685. case 't':
  34686. material.uniforms[ name ].value = getTexture( uniform.value );
  34687. break;
  34688. case 'c':
  34689. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34690. break;
  34691. case 'v2':
  34692. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34693. break;
  34694. case 'v3':
  34695. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34696. break;
  34697. case 'v4':
  34698. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34699. break;
  34700. case 'm3':
  34701. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34702. break;
  34703. case 'm4':
  34704. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34705. break;
  34706. default:
  34707. material.uniforms[ name ].value = uniform.value;
  34708. }
  34709. }
  34710. }
  34711. if ( json.defines !== undefined ) material.defines = json.defines;
  34712. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34713. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34714. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34715. if ( json.extensions !== undefined ) {
  34716. for ( const key in json.extensions ) {
  34717. material.extensions[ key ] = json.extensions[ key ];
  34718. }
  34719. }
  34720. if ( json.lights !== undefined ) material.lights = json.lights;
  34721. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34722. // for PointsMaterial
  34723. if ( json.size !== undefined ) material.size = json.size;
  34724. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34725. // maps
  34726. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34727. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34728. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34729. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34730. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34731. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34732. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34733. if ( json.normalScale !== undefined ) {
  34734. let normalScale = json.normalScale;
  34735. if ( Array.isArray( normalScale ) === false ) {
  34736. // Blender exporter used to export a scalar. See #7459
  34737. normalScale = [ normalScale, normalScale ];
  34738. }
  34739. material.normalScale = new Vector2().fromArray( normalScale );
  34740. }
  34741. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34742. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34743. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34744. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34745. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34746. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34747. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34748. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34749. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34750. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34751. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34752. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34753. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34754. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34755. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34756. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34757. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34758. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34759. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34760. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34761. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34762. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34763. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34764. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34765. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34766. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34767. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34768. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34769. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34770. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34771. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34772. return material;
  34773. }
  34774. /**
  34775. * Textures are not embedded in the material JSON so they have
  34776. * to be injected before the loading process starts.
  34777. *
  34778. * @param {Object} value - A dictionary holding textures for material properties.
  34779. * @return {MaterialLoader} A reference to this material loader.
  34780. */
  34781. setTextures( value ) {
  34782. this.textures = value;
  34783. return this;
  34784. }
  34785. /**
  34786. * Creates a material for the given type.
  34787. *
  34788. * @param {string} type - The material type.
  34789. * @return {Material} The new material.
  34790. */
  34791. createMaterialFromType( type ) {
  34792. return MaterialLoader.createMaterialFromType( type );
  34793. }
  34794. /**
  34795. * Creates a material for the given type.
  34796. *
  34797. * @static
  34798. * @param {string} type - The material type.
  34799. * @return {Material} The new material.
  34800. */
  34801. static createMaterialFromType( type ) {
  34802. const materialLib = {
  34803. ShadowMaterial,
  34804. SpriteMaterial,
  34805. RawShaderMaterial,
  34806. ShaderMaterial,
  34807. PointsMaterial,
  34808. MeshPhysicalMaterial,
  34809. MeshStandardMaterial,
  34810. MeshPhongMaterial,
  34811. MeshToonMaterial,
  34812. MeshNormalMaterial,
  34813. MeshLambertMaterial,
  34814. MeshDepthMaterial,
  34815. MeshDistanceMaterial,
  34816. MeshBasicMaterial,
  34817. MeshMatcapMaterial,
  34818. LineDashedMaterial,
  34819. LineBasicMaterial,
  34820. Material
  34821. };
  34822. return new materialLib[ type ]();
  34823. }
  34824. }
  34825. /**
  34826. * A class with loader utility functions.
  34827. */
  34828. class LoaderUtils {
  34829. /**
  34830. * Extracts the base URL from the given URL.
  34831. *
  34832. * @param {string} url -The URL to extract the base URL from.
  34833. * @return {string} The extracted base URL.
  34834. */
  34835. static extractUrlBase( url ) {
  34836. const index = url.lastIndexOf( '/' );
  34837. if ( index === -1 ) return './';
  34838. return url.slice( 0, index + 1 );
  34839. }
  34840. /**
  34841. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34842. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34843. * string.
  34844. *
  34845. * @param {string} url -The URL to resolve.
  34846. * @param {string} path - The base path for relative URLs to be resolved against.
  34847. * @return {string} The resolved URL.
  34848. */
  34849. static resolveURL( url, path ) {
  34850. // Invalid URL
  34851. if ( typeof url !== 'string' || url === '' ) return '';
  34852. // Host Relative URL
  34853. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34854. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34855. }
  34856. // Absolute URL http://,https://,//
  34857. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34858. // Data URI
  34859. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34860. // Blob URL
  34861. if ( /^blob:.*$/i.test( url ) ) return url;
  34862. // Relative URL
  34863. return path + url;
  34864. }
  34865. }
  34866. /**
  34867. * An instanced version of a geometry.
  34868. */
  34869. class InstancedBufferGeometry extends BufferGeometry {
  34870. /**
  34871. * Constructs a new instanced buffer geometry.
  34872. */
  34873. constructor() {
  34874. super();
  34875. /**
  34876. * This flag can be used for type testing.
  34877. *
  34878. * @type {boolean}
  34879. * @readonly
  34880. * @default true
  34881. */
  34882. this.isInstancedBufferGeometry = true;
  34883. this.type = 'InstancedBufferGeometry';
  34884. /**
  34885. * The instance count.
  34886. *
  34887. * @type {number}
  34888. * @default Infinity
  34889. */
  34890. this.instanceCount = Infinity;
  34891. }
  34892. copy( source ) {
  34893. super.copy( source );
  34894. this.instanceCount = source.instanceCount;
  34895. return this;
  34896. }
  34897. toJSON() {
  34898. const data = super.toJSON();
  34899. data.instanceCount = this.instanceCount;
  34900. data.isInstancedBufferGeometry = true;
  34901. return data;
  34902. }
  34903. }
  34904. /**
  34905. * Class for loading geometries. The files are internally
  34906. * loaded via {@link FileLoader}.
  34907. *
  34908. * ```js
  34909. * const loader = new THREE.BufferGeometryLoader();
  34910. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34911. *
  34912. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34913. * const object = new THREE.Mesh( geometry, material );
  34914. * scene.add( object );
  34915. * ```
  34916. *
  34917. * @augments Loader
  34918. */
  34919. class BufferGeometryLoader extends Loader {
  34920. /**
  34921. * Constructs a new geometry loader.
  34922. *
  34923. * @param {LoadingManager} [manager] - The loading manager.
  34924. */
  34925. constructor( manager ) {
  34926. super( manager );
  34927. }
  34928. /**
  34929. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34930. *
  34931. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34932. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34933. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34934. * @param {onErrorCallback} onError - Executed when errors occur.
  34935. */
  34936. load( url, onLoad, onProgress, onError ) {
  34937. const scope = this;
  34938. const loader = new FileLoader( scope.manager );
  34939. loader.setPath( scope.path );
  34940. loader.setRequestHeader( scope.requestHeader );
  34941. loader.setWithCredentials( scope.withCredentials );
  34942. loader.load( url, function ( text ) {
  34943. try {
  34944. onLoad( scope.parse( JSON.parse( text ) ) );
  34945. } catch ( e ) {
  34946. if ( onError ) {
  34947. onError( e );
  34948. } else {
  34949. error( e );
  34950. }
  34951. scope.manager.itemError( url );
  34952. }
  34953. }, onProgress, onError );
  34954. }
  34955. /**
  34956. * Parses the given JSON object and returns a geometry.
  34957. *
  34958. * @param {Object} json - The serialized geometry.
  34959. * @return {BufferGeometry} The parsed geometry.
  34960. */
  34961. parse( json ) {
  34962. const interleavedBufferMap = {};
  34963. const arrayBufferMap = {};
  34964. function getInterleavedBuffer( json, uuid ) {
  34965. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34966. const interleavedBuffers = json.interleavedBuffers;
  34967. const interleavedBuffer = interleavedBuffers[ uuid ];
  34968. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34969. const array = getTypedArray( interleavedBuffer.type, buffer );
  34970. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34971. ib.uuid = interleavedBuffer.uuid;
  34972. interleavedBufferMap[ uuid ] = ib;
  34973. return ib;
  34974. }
  34975. function getArrayBuffer( json, uuid ) {
  34976. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34977. const arrayBuffers = json.arrayBuffers;
  34978. const arrayBuffer = arrayBuffers[ uuid ];
  34979. const ab = new Uint32Array( arrayBuffer ).buffer;
  34980. arrayBufferMap[ uuid ] = ab;
  34981. return ab;
  34982. }
  34983. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34984. const index = json.data.index;
  34985. if ( index !== undefined ) {
  34986. const typedArray = getTypedArray( index.type, index.array );
  34987. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  34988. }
  34989. const attributes = json.data.attributes;
  34990. for ( const key in attributes ) {
  34991. const attribute = attributes[ key ];
  34992. let bufferAttribute;
  34993. if ( attribute.isInterleavedBufferAttribute ) {
  34994. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  34995. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  34996. } else {
  34997. const typedArray = getTypedArray( attribute.type, attribute.array );
  34998. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  34999. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35000. }
  35001. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35002. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35003. geometry.setAttribute( key, bufferAttribute );
  35004. }
  35005. const morphAttributes = json.data.morphAttributes;
  35006. if ( morphAttributes ) {
  35007. for ( const key in morphAttributes ) {
  35008. const attributeArray = morphAttributes[ key ];
  35009. const array = [];
  35010. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35011. const attribute = attributeArray[ i ];
  35012. let bufferAttribute;
  35013. if ( attribute.isInterleavedBufferAttribute ) {
  35014. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35015. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35016. } else {
  35017. const typedArray = getTypedArray( attribute.type, attribute.array );
  35018. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35019. }
  35020. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35021. array.push( bufferAttribute );
  35022. }
  35023. geometry.morphAttributes[ key ] = array;
  35024. }
  35025. }
  35026. const morphTargetsRelative = json.data.morphTargetsRelative;
  35027. if ( morphTargetsRelative ) {
  35028. geometry.morphTargetsRelative = true;
  35029. }
  35030. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35031. if ( groups !== undefined ) {
  35032. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35033. const group = groups[ i ];
  35034. geometry.addGroup( group.start, group.count, group.materialIndex );
  35035. }
  35036. }
  35037. const boundingSphere = json.data.boundingSphere;
  35038. if ( boundingSphere !== undefined ) {
  35039. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35040. }
  35041. if ( json.name ) geometry.name = json.name;
  35042. if ( json.userData ) geometry.userData = json.userData;
  35043. return geometry;
  35044. }
  35045. }
  35046. /**
  35047. * A loader for loading a JSON resource in the [JSON Object/Scene format](https://github.com/mrdoob/three.js/wiki/JSON-Object-Scene-format-4).
  35048. * The files are internally loaded via {@link FileLoader}.
  35049. *
  35050. * ```js
  35051. * const loader = new THREE.ObjectLoader();
  35052. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35053. * scene.add( obj );
  35054. *
  35055. * // Alternatively, to parse a previously loaded JSON structure
  35056. * const object = await loader.parseAsync( a_json_object );
  35057. * scene.add( object );
  35058. * ```
  35059. *
  35060. * @augments Loader
  35061. */
  35062. class ObjectLoader extends Loader {
  35063. /**
  35064. * Constructs a new object loader.
  35065. *
  35066. * @param {LoadingManager} [manager] - The loading manager.
  35067. */
  35068. constructor( manager ) {
  35069. super( manager );
  35070. }
  35071. /**
  35072. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35073. *
  35074. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35075. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35076. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35077. * @param {onErrorCallback} onError - Executed when errors occur.
  35078. */
  35079. load( url, onLoad, onProgress, onError ) {
  35080. const scope = this;
  35081. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35082. this.resourcePath = this.resourcePath || path;
  35083. const loader = new FileLoader( this.manager );
  35084. loader.setPath( this.path );
  35085. loader.setRequestHeader( this.requestHeader );
  35086. loader.setWithCredentials( this.withCredentials );
  35087. loader.load( url, function ( text ) {
  35088. let json = null;
  35089. try {
  35090. json = JSON.parse( text );
  35091. } catch ( error ) {
  35092. if ( onError !== undefined ) onError( error );
  35093. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35094. return;
  35095. }
  35096. const metadata = json.metadata;
  35097. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35098. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35099. error( 'ObjectLoader: Can\'t load ' + url );
  35100. return;
  35101. }
  35102. scope.parse( json, onLoad );
  35103. }, onProgress, onError );
  35104. }
  35105. /**
  35106. * Async version of {@link ObjectLoader#load}.
  35107. *
  35108. * @async
  35109. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35110. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35111. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35112. */
  35113. async loadAsync( url, onProgress ) {
  35114. const scope = this;
  35115. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35116. this.resourcePath = this.resourcePath || path;
  35117. const loader = new FileLoader( this.manager );
  35118. loader.setPath( this.path );
  35119. loader.setRequestHeader( this.requestHeader );
  35120. loader.setWithCredentials( this.withCredentials );
  35121. const text = await loader.loadAsync( url, onProgress );
  35122. const json = JSON.parse( text );
  35123. const metadata = json.metadata;
  35124. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35125. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35126. }
  35127. return await scope.parseAsync( json );
  35128. }
  35129. /**
  35130. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35131. * but can also be used directly to parse a previously loaded JSON structure.
  35132. *
  35133. * @param {Object} json - The serialized 3D object.
  35134. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35135. * @return {Object3D} The parsed 3D object.
  35136. */
  35137. parse( json, onLoad ) {
  35138. const animations = this.parseAnimations( json.animations );
  35139. const shapes = this.parseShapes( json.shapes );
  35140. const geometries = this.parseGeometries( json.geometries, shapes );
  35141. const images = this.parseImages( json.images, function () {
  35142. if ( onLoad !== undefined ) onLoad( object );
  35143. } );
  35144. const textures = this.parseTextures( json.textures, images );
  35145. const materials = this.parseMaterials( json.materials, textures );
  35146. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35147. const skeletons = this.parseSkeletons( json.skeletons, object );
  35148. this.bindSkeletons( object, skeletons );
  35149. this.bindLightTargets( object );
  35150. //
  35151. if ( onLoad !== undefined ) {
  35152. let hasImages = false;
  35153. for ( const uuid in images ) {
  35154. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35155. hasImages = true;
  35156. break;
  35157. }
  35158. }
  35159. if ( hasImages === false ) onLoad( object );
  35160. }
  35161. return object;
  35162. }
  35163. /**
  35164. * Async version of {@link ObjectLoader#parse}.
  35165. *
  35166. * @param {Object} json - The serialized 3D object.
  35167. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35168. */
  35169. async parseAsync( json ) {
  35170. const animations = this.parseAnimations( json.animations );
  35171. const shapes = this.parseShapes( json.shapes );
  35172. const geometries = this.parseGeometries( json.geometries, shapes );
  35173. const images = await this.parseImagesAsync( json.images );
  35174. const textures = this.parseTextures( json.textures, images );
  35175. const materials = this.parseMaterials( json.materials, textures );
  35176. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35177. const skeletons = this.parseSkeletons( json.skeletons, object );
  35178. this.bindSkeletons( object, skeletons );
  35179. this.bindLightTargets( object );
  35180. return object;
  35181. }
  35182. // internals
  35183. parseShapes( json ) {
  35184. const shapes = {};
  35185. if ( json !== undefined ) {
  35186. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35187. const shape = new Shape().fromJSON( json[ i ] );
  35188. shapes[ shape.uuid ] = shape;
  35189. }
  35190. }
  35191. return shapes;
  35192. }
  35193. parseSkeletons( json, object ) {
  35194. const skeletons = {};
  35195. const bones = {};
  35196. // generate bone lookup table
  35197. object.traverse( function ( child ) {
  35198. if ( child.isBone ) bones[ child.uuid ] = child;
  35199. } );
  35200. // create skeletons
  35201. if ( json !== undefined ) {
  35202. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35203. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35204. skeletons[ skeleton.uuid ] = skeleton;
  35205. }
  35206. }
  35207. return skeletons;
  35208. }
  35209. parseGeometries( json, shapes ) {
  35210. const geometries = {};
  35211. if ( json !== undefined ) {
  35212. const bufferGeometryLoader = new BufferGeometryLoader();
  35213. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35214. let geometry;
  35215. const data = json[ i ];
  35216. switch ( data.type ) {
  35217. case 'BufferGeometry':
  35218. case 'InstancedBufferGeometry':
  35219. geometry = bufferGeometryLoader.parse( data );
  35220. break;
  35221. default:
  35222. if ( data.type in Geometries ) {
  35223. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35224. } else {
  35225. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35226. }
  35227. }
  35228. geometry.uuid = data.uuid;
  35229. if ( data.name !== undefined ) geometry.name = data.name;
  35230. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35231. geometries[ data.uuid ] = geometry;
  35232. }
  35233. }
  35234. return geometries;
  35235. }
  35236. parseMaterials( json, textures ) {
  35237. const cache = {}; // MultiMaterial
  35238. const materials = {};
  35239. if ( json !== undefined ) {
  35240. const loader = new MaterialLoader();
  35241. loader.setTextures( textures );
  35242. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35243. const data = json[ i ];
  35244. if ( cache[ data.uuid ] === undefined ) {
  35245. cache[ data.uuid ] = loader.parse( data );
  35246. }
  35247. materials[ data.uuid ] = cache[ data.uuid ];
  35248. }
  35249. }
  35250. return materials;
  35251. }
  35252. parseAnimations( json ) {
  35253. const animations = {};
  35254. if ( json !== undefined ) {
  35255. for ( let i = 0; i < json.length; i ++ ) {
  35256. const data = json[ i ];
  35257. const clip = AnimationClip.parse( data );
  35258. animations[ clip.uuid ] = clip;
  35259. }
  35260. }
  35261. return animations;
  35262. }
  35263. parseImages( json, onLoad ) {
  35264. const scope = this;
  35265. const images = {};
  35266. let loader;
  35267. function loadImage( url ) {
  35268. scope.manager.itemStart( url );
  35269. return loader.load( url, function () {
  35270. scope.manager.itemEnd( url );
  35271. }, undefined, function () {
  35272. scope.manager.itemError( url );
  35273. scope.manager.itemEnd( url );
  35274. } );
  35275. }
  35276. function deserializeImage( image ) {
  35277. if ( typeof image === 'string' ) {
  35278. const url = image;
  35279. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35280. return loadImage( path );
  35281. } else {
  35282. if ( image.data ) {
  35283. return {
  35284. data: getTypedArray( image.type, image.data ),
  35285. width: image.width,
  35286. height: image.height
  35287. };
  35288. } else {
  35289. return null;
  35290. }
  35291. }
  35292. }
  35293. if ( json !== undefined && json.length > 0 ) {
  35294. const manager = new LoadingManager( onLoad );
  35295. loader = new ImageLoader( manager );
  35296. loader.setCrossOrigin( this.crossOrigin );
  35297. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35298. const image = json[ i ];
  35299. const url = image.url;
  35300. if ( Array.isArray( url ) ) {
  35301. // load array of images e.g CubeTexture
  35302. const imageArray = [];
  35303. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35304. const currentUrl = url[ j ];
  35305. const deserializedImage = deserializeImage( currentUrl );
  35306. if ( deserializedImage !== null ) {
  35307. if ( deserializedImage instanceof HTMLImageElement ) {
  35308. imageArray.push( deserializedImage );
  35309. } else {
  35310. // special case: handle array of data textures for cube textures
  35311. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35312. }
  35313. }
  35314. }
  35315. images[ image.uuid ] = new Source( imageArray );
  35316. } else {
  35317. // load single image
  35318. const deserializedImage = deserializeImage( image.url );
  35319. images[ image.uuid ] = new Source( deserializedImage );
  35320. }
  35321. }
  35322. }
  35323. return images;
  35324. }
  35325. async parseImagesAsync( json ) {
  35326. const scope = this;
  35327. const images = {};
  35328. let loader;
  35329. async function deserializeImage( image ) {
  35330. if ( typeof image === 'string' ) {
  35331. const url = image;
  35332. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35333. return await loader.loadAsync( path );
  35334. } else {
  35335. if ( image.data ) {
  35336. return {
  35337. data: getTypedArray( image.type, image.data ),
  35338. width: image.width,
  35339. height: image.height
  35340. };
  35341. } else {
  35342. return null;
  35343. }
  35344. }
  35345. }
  35346. if ( json !== undefined && json.length > 0 ) {
  35347. loader = new ImageLoader( this.manager );
  35348. loader.setCrossOrigin( this.crossOrigin );
  35349. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35350. const image = json[ i ];
  35351. const url = image.url;
  35352. if ( Array.isArray( url ) ) {
  35353. // load array of images e.g CubeTexture
  35354. const imageArray = [];
  35355. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35356. const currentUrl = url[ j ];
  35357. const deserializedImage = await deserializeImage( currentUrl );
  35358. if ( deserializedImage !== null ) {
  35359. if ( deserializedImage instanceof HTMLImageElement ) {
  35360. imageArray.push( deserializedImage );
  35361. } else {
  35362. // special case: handle array of data textures for cube textures
  35363. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35364. }
  35365. }
  35366. }
  35367. images[ image.uuid ] = new Source( imageArray );
  35368. } else {
  35369. // load single image
  35370. const deserializedImage = await deserializeImage( image.url );
  35371. images[ image.uuid ] = new Source( deserializedImage );
  35372. }
  35373. }
  35374. }
  35375. return images;
  35376. }
  35377. parseTextures( json, images ) {
  35378. function parseConstant( value, type ) {
  35379. if ( typeof value === 'number' ) return value;
  35380. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35381. return type[ value ];
  35382. }
  35383. const textures = {};
  35384. if ( json !== undefined ) {
  35385. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35386. const data = json[ i ];
  35387. if ( data.image === undefined ) {
  35388. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35389. }
  35390. if ( images[ data.image ] === undefined ) {
  35391. warn( 'ObjectLoader: Undefined image', data.image );
  35392. }
  35393. const source = images[ data.image ];
  35394. const image = source.data;
  35395. let texture;
  35396. if ( Array.isArray( image ) ) {
  35397. texture = new CubeTexture();
  35398. if ( image.length === 6 ) texture.needsUpdate = true;
  35399. } else {
  35400. if ( image && image.data ) {
  35401. texture = new DataTexture();
  35402. } else {
  35403. texture = new Texture();
  35404. }
  35405. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35406. }
  35407. texture.source = source;
  35408. texture.uuid = data.uuid;
  35409. if ( data.name !== undefined ) texture.name = data.name;
  35410. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35411. if ( data.channel !== undefined ) texture.channel = data.channel;
  35412. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35413. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35414. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35415. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35416. if ( data.wrap !== undefined ) {
  35417. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35418. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35419. }
  35420. if ( data.format !== undefined ) texture.format = data.format;
  35421. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35422. if ( data.type !== undefined ) texture.type = data.type;
  35423. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35424. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35425. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35426. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35427. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35428. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35429. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35430. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35431. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35432. if ( data.userData !== undefined ) texture.userData = data.userData;
  35433. textures[ data.uuid ] = texture;
  35434. }
  35435. }
  35436. return textures;
  35437. }
  35438. parseObject( data, geometries, materials, textures, animations ) {
  35439. let object;
  35440. function getGeometry( name ) {
  35441. if ( geometries[ name ] === undefined ) {
  35442. warn( 'ObjectLoader: Undefined geometry', name );
  35443. }
  35444. return geometries[ name ];
  35445. }
  35446. function getMaterial( name ) {
  35447. if ( name === undefined ) return undefined;
  35448. if ( Array.isArray( name ) ) {
  35449. const array = [];
  35450. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35451. const uuid = name[ i ];
  35452. if ( materials[ uuid ] === undefined ) {
  35453. warn( 'ObjectLoader: Undefined material', uuid );
  35454. }
  35455. array.push( materials[ uuid ] );
  35456. }
  35457. return array;
  35458. }
  35459. if ( materials[ name ] === undefined ) {
  35460. warn( 'ObjectLoader: Undefined material', name );
  35461. }
  35462. return materials[ name ];
  35463. }
  35464. function getTexture( uuid ) {
  35465. if ( textures[ uuid ] === undefined ) {
  35466. warn( 'ObjectLoader: Undefined texture', uuid );
  35467. }
  35468. return textures[ uuid ];
  35469. }
  35470. let geometry, material;
  35471. switch ( data.type ) {
  35472. case 'Scene':
  35473. object = new Scene();
  35474. if ( data.background !== undefined ) {
  35475. if ( Number.isInteger( data.background ) ) {
  35476. object.background = new Color( data.background );
  35477. } else {
  35478. object.background = getTexture( data.background );
  35479. }
  35480. }
  35481. if ( data.environment !== undefined ) {
  35482. object.environment = getTexture( data.environment );
  35483. }
  35484. if ( data.fog !== undefined ) {
  35485. if ( data.fog.type === 'Fog' ) {
  35486. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35487. } else if ( data.fog.type === 'FogExp2' ) {
  35488. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35489. }
  35490. if ( data.fog.name !== '' ) {
  35491. object.fog.name = data.fog.name;
  35492. }
  35493. }
  35494. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35495. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35496. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35497. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35498. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35499. break;
  35500. case 'PerspectiveCamera':
  35501. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35502. if ( data.focus !== undefined ) object.focus = data.focus;
  35503. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35504. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35505. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35506. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35507. break;
  35508. case 'OrthographicCamera':
  35509. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35510. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35511. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35512. break;
  35513. case 'AmbientLight':
  35514. object = new AmbientLight( data.color, data.intensity );
  35515. break;
  35516. case 'DirectionalLight':
  35517. object = new DirectionalLight( data.color, data.intensity );
  35518. object.target = data.target || '';
  35519. break;
  35520. case 'PointLight':
  35521. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35522. break;
  35523. case 'RectAreaLight':
  35524. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35525. break;
  35526. case 'SpotLight':
  35527. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35528. object.target = data.target || '';
  35529. break;
  35530. case 'HemisphereLight':
  35531. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35532. break;
  35533. case 'LightProbe':
  35534. const sh = new SphericalHarmonics3().fromArray( data.sh );
  35535. object = new LightProbe( sh, data.intensity );
  35536. break;
  35537. case 'SkinnedMesh':
  35538. geometry = getGeometry( data.geometry );
  35539. material = getMaterial( data.material );
  35540. object = new SkinnedMesh( geometry, material );
  35541. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35542. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35543. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35544. break;
  35545. case 'Mesh':
  35546. geometry = getGeometry( data.geometry );
  35547. material = getMaterial( data.material );
  35548. object = new Mesh( geometry, material );
  35549. break;
  35550. case 'InstancedMesh':
  35551. geometry = getGeometry( data.geometry );
  35552. material = getMaterial( data.material );
  35553. const count = data.count;
  35554. const instanceMatrix = data.instanceMatrix;
  35555. const instanceColor = data.instanceColor;
  35556. object = new InstancedMesh( geometry, material, count );
  35557. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35558. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35559. break;
  35560. case 'BatchedMesh':
  35561. geometry = getGeometry( data.geometry );
  35562. material = getMaterial( data.material );
  35563. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35564. object.geometry = geometry;
  35565. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35566. object.sortObjects = data.sortObjects;
  35567. object._drawRanges = data.drawRanges;
  35568. object._reservedRanges = data.reservedRanges;
  35569. object._geometryInfo = data.geometryInfo.map( info => {
  35570. let box = null;
  35571. let sphere = null;
  35572. if ( info.boundingBox !== undefined ) {
  35573. box = new Box3().fromJSON( info.boundingBox );
  35574. }
  35575. if ( info.boundingSphere !== undefined ) {
  35576. sphere = new Sphere().fromJSON( info.boundingSphere );
  35577. }
  35578. return {
  35579. ...info,
  35580. boundingBox: box,
  35581. boundingSphere: sphere
  35582. };
  35583. } );
  35584. object._instanceInfo = data.instanceInfo;
  35585. object._availableInstanceIds = data._availableInstanceIds;
  35586. object._availableGeometryIds = data._availableGeometryIds;
  35587. object._nextIndexStart = data.nextIndexStart;
  35588. object._nextVertexStart = data.nextVertexStart;
  35589. object._geometryCount = data.geometryCount;
  35590. object._maxInstanceCount = data.maxInstanceCount;
  35591. object._maxVertexCount = data.maxVertexCount;
  35592. object._maxIndexCount = data.maxIndexCount;
  35593. object._geometryInitialized = data.geometryInitialized;
  35594. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35595. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35596. if ( data.colorsTexture !== undefined ) {
  35597. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35598. }
  35599. if ( data.boundingSphere !== undefined ) {
  35600. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35601. }
  35602. if ( data.boundingBox !== undefined ) {
  35603. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35604. }
  35605. break;
  35606. case 'LOD':
  35607. object = new LOD();
  35608. break;
  35609. case 'Line':
  35610. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35611. break;
  35612. case 'LineLoop':
  35613. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35614. break;
  35615. case 'LineSegments':
  35616. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35617. break;
  35618. case 'PointCloud':
  35619. case 'Points':
  35620. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35621. break;
  35622. case 'Sprite':
  35623. object = new Sprite( getMaterial( data.material ) );
  35624. break;
  35625. case 'Group':
  35626. object = new Group();
  35627. break;
  35628. case 'Bone':
  35629. object = new Bone();
  35630. break;
  35631. default:
  35632. object = new Object3D();
  35633. }
  35634. object.uuid = data.uuid;
  35635. if ( data.name !== undefined ) object.name = data.name;
  35636. if ( data.matrix !== undefined ) {
  35637. object.matrix.fromArray( data.matrix );
  35638. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35639. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35640. } else {
  35641. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35642. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35643. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35644. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35645. }
  35646. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35647. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35648. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35649. if ( data.shadow ) {
  35650. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35651. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35652. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35653. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35654. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35655. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35656. }
  35657. if ( data.visible !== undefined ) object.visible = data.visible;
  35658. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35659. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35660. if ( data.userData !== undefined ) object.userData = data.userData;
  35661. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35662. if ( data.children !== undefined ) {
  35663. const children = data.children;
  35664. for ( let i = 0; i < children.length; i ++ ) {
  35665. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35666. }
  35667. }
  35668. if ( data.animations !== undefined ) {
  35669. const objectAnimations = data.animations;
  35670. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35671. const uuid = objectAnimations[ i ];
  35672. object.animations.push( animations[ uuid ] );
  35673. }
  35674. }
  35675. if ( data.type === 'LOD' ) {
  35676. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35677. const levels = data.levels;
  35678. for ( let l = 0; l < levels.length; l ++ ) {
  35679. const level = levels[ l ];
  35680. const child = object.getObjectByProperty( 'uuid', level.object );
  35681. if ( child !== undefined ) {
  35682. object.addLevel( child, level.distance, level.hysteresis );
  35683. }
  35684. }
  35685. }
  35686. return object;
  35687. }
  35688. bindSkeletons( object, skeletons ) {
  35689. if ( Object.keys( skeletons ).length === 0 ) return;
  35690. object.traverse( function ( child ) {
  35691. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35692. const skeleton = skeletons[ child.skeleton ];
  35693. if ( skeleton === undefined ) {
  35694. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35695. } else {
  35696. child.bind( skeleton, child.bindMatrix );
  35697. }
  35698. }
  35699. } );
  35700. }
  35701. bindLightTargets( object ) {
  35702. object.traverse( function ( child ) {
  35703. if ( child.isDirectionalLight || child.isSpotLight ) {
  35704. const uuid = child.target;
  35705. const target = object.getObjectByProperty( 'uuid', uuid );
  35706. if ( target !== undefined ) {
  35707. child.target = target;
  35708. } else {
  35709. child.target = new Object3D();
  35710. }
  35711. }
  35712. } );
  35713. }
  35714. }
  35715. const TEXTURE_MAPPING = {
  35716. UVMapping: UVMapping,
  35717. CubeReflectionMapping: CubeReflectionMapping,
  35718. CubeRefractionMapping: CubeRefractionMapping,
  35719. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35720. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35721. CubeUVReflectionMapping: CubeUVReflectionMapping
  35722. };
  35723. const TEXTURE_WRAPPING = {
  35724. RepeatWrapping: RepeatWrapping,
  35725. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35726. MirroredRepeatWrapping: MirroredRepeatWrapping
  35727. };
  35728. const TEXTURE_FILTER = {
  35729. NearestFilter: NearestFilter,
  35730. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35731. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35732. LinearFilter: LinearFilter,
  35733. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35734. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35735. };
  35736. const _errorMap = new WeakMap();
  35737. /**
  35738. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35739. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35740. * textures for rendering.
  35741. *
  35742. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35743. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35744. *
  35745. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35746. *
  35747. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35748. *
  35749. * ```js
  35750. * const loader = new THREE.ImageBitmapLoader();
  35751. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35752. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35753. *
  35754. * const texture = new THREE.Texture( imageBitmap );
  35755. * texture.needsUpdate = true;
  35756. * ```
  35757. *
  35758. * @augments Loader
  35759. */
  35760. class ImageBitmapLoader extends Loader {
  35761. /**
  35762. * Constructs a new image bitmap loader.
  35763. *
  35764. * @param {LoadingManager} [manager] - The loading manager.
  35765. */
  35766. constructor( manager ) {
  35767. super( manager );
  35768. /**
  35769. * This flag can be used for type testing.
  35770. *
  35771. * @type {boolean}
  35772. * @readonly
  35773. * @default true
  35774. */
  35775. this.isImageBitmapLoader = true;
  35776. if ( typeof createImageBitmap === 'undefined' ) {
  35777. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35778. }
  35779. if ( typeof fetch === 'undefined' ) {
  35780. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35781. }
  35782. /**
  35783. * Represents the loader options.
  35784. *
  35785. * @type {Object}
  35786. * @default {premultiplyAlpha:'none'}
  35787. */
  35788. this.options = { premultiplyAlpha: 'none' };
  35789. /**
  35790. * Used for aborting requests.
  35791. *
  35792. * @private
  35793. * @type {AbortController}
  35794. */
  35795. this._abortController = new AbortController();
  35796. }
  35797. /**
  35798. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35799. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  35800. *
  35801. * @param {Object} options - The loader options to set.
  35802. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35803. */
  35804. setOptions( options ) {
  35805. this.options = options;
  35806. return this;
  35807. }
  35808. /**
  35809. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35810. *
  35811. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35812. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35813. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35814. * @param {onErrorCallback} onError - Executed when errors occur.
  35815. * @return {ImageBitmap|undefined} The image bitmap.
  35816. */
  35817. load( url, onLoad, onProgress, onError ) {
  35818. if ( url === undefined ) url = '';
  35819. if ( this.path !== undefined ) url = this.path + url;
  35820. url = this.manager.resolveURL( url );
  35821. const scope = this;
  35822. const cached = Cache.get( `image-bitmap:${url}` );
  35823. if ( cached !== undefined ) {
  35824. scope.manager.itemStart( url );
  35825. // If cached is a promise, wait for it to resolve
  35826. if ( cached.then ) {
  35827. cached.then( imageBitmap => {
  35828. // check if there is an error for the cached promise
  35829. if ( _errorMap.has( cached ) === true ) {
  35830. if ( onError ) onError( _errorMap.get( cached ) );
  35831. scope.manager.itemError( url );
  35832. scope.manager.itemEnd( url );
  35833. } else {
  35834. if ( onLoad ) onLoad( imageBitmap );
  35835. scope.manager.itemEnd( url );
  35836. return imageBitmap;
  35837. }
  35838. } );
  35839. return;
  35840. }
  35841. // If cached is not a promise (i.e., it's already an imageBitmap)
  35842. setTimeout( function () {
  35843. if ( onLoad ) onLoad( cached );
  35844. scope.manager.itemEnd( url );
  35845. }, 0 );
  35846. return cached;
  35847. }
  35848. const fetchOptions = {};
  35849. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35850. fetchOptions.headers = this.requestHeader;
  35851. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35852. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35853. return res.blob();
  35854. } ).then( function ( blob ) {
  35855. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35856. } ).then( function ( imageBitmap ) {
  35857. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35858. if ( onLoad ) onLoad( imageBitmap );
  35859. scope.manager.itemEnd( url );
  35860. return imageBitmap;
  35861. } ).catch( function ( e ) {
  35862. if ( onError ) onError( e );
  35863. _errorMap.set( promise, e );
  35864. Cache.remove( `image-bitmap:${url}` );
  35865. scope.manager.itemError( url );
  35866. scope.manager.itemEnd( url );
  35867. } );
  35868. Cache.add( `image-bitmap:${url}`, promise );
  35869. scope.manager.itemStart( url );
  35870. }
  35871. /**
  35872. * Aborts ongoing fetch requests.
  35873. *
  35874. * @return {ImageBitmapLoader} A reference to this instance.
  35875. */
  35876. abort() {
  35877. this._abortController.abort();
  35878. this._abortController = new AbortController();
  35879. return this;
  35880. }
  35881. }
  35882. let _context;
  35883. /**
  35884. * Manages the global audio context in the engine.
  35885. *
  35886. * @hideconstructor
  35887. */
  35888. class AudioContext {
  35889. /**
  35890. * Returns the global native audio context.
  35891. *
  35892. * @return {AudioContext} The native audio context.
  35893. */
  35894. static getContext() {
  35895. if ( _context === undefined ) {
  35896. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35897. }
  35898. return _context;
  35899. }
  35900. /**
  35901. * Allows to set the global native audio context from outside.
  35902. *
  35903. * @param {AudioContext} value - The native context to set.
  35904. */
  35905. static setContext( value ) {
  35906. _context = value;
  35907. }
  35908. }
  35909. /**
  35910. * Class for loading audio buffers. Audios are internally
  35911. * loaded via {@link FileLoader}.
  35912. *
  35913. * ```js
  35914. * const audioListener = new THREE.AudioListener();
  35915. * const ambientSound = new THREE.Audio( audioListener );
  35916. *
  35917. * const loader = new THREE.AudioLoader();
  35918. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35919. *
  35920. * ambientSound.setBuffer( audioBuffer );
  35921. * ambientSound.play();
  35922. * ```
  35923. *
  35924. * @augments Loader
  35925. */
  35926. class AudioLoader extends Loader {
  35927. /**
  35928. * Constructs a new audio loader.
  35929. *
  35930. * @param {LoadingManager} [manager] - The loading manager.
  35931. */
  35932. constructor( manager ) {
  35933. super( manager );
  35934. }
  35935. /**
  35936. * Starts loading from the given URL and passes the loaded audio buffer
  35937. * to the `onLoad()` callback.
  35938. *
  35939. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35940. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35941. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35942. * @param {onErrorCallback} onError - Executed when errors occur.
  35943. */
  35944. load( url, onLoad, onProgress, onError ) {
  35945. const scope = this;
  35946. const loader = new FileLoader( this.manager );
  35947. loader.setResponseType( 'arraybuffer' );
  35948. loader.setPath( this.path );
  35949. loader.setRequestHeader( this.requestHeader );
  35950. loader.setWithCredentials( this.withCredentials );
  35951. loader.load( url, function ( buffer ) {
  35952. try {
  35953. // Create a copy of the buffer. The `decodeAudioData` method
  35954. // detaches the buffer when complete, preventing reuse.
  35955. const bufferCopy = buffer.slice( 0 );
  35956. const context = AudioContext.getContext();
  35957. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35958. onLoad( audioBuffer );
  35959. } ).catch( handleError );
  35960. } catch ( e ) {
  35961. handleError( e );
  35962. }
  35963. }, onProgress, onError );
  35964. function handleError( e ) {
  35965. if ( onError ) {
  35966. onError( e );
  35967. } else {
  35968. error( e );
  35969. }
  35970. scope.manager.itemError( url );
  35971. }
  35972. }
  35973. }
  35974. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35975. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35976. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35977. /**
  35978. * A special type of camera that uses two perspective cameras with
  35979. * stereoscopic projection. Can be used for rendering stereo effects
  35980. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  35981. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  35982. */
  35983. class StereoCamera {
  35984. /**
  35985. * Constructs a new stereo camera.
  35986. */
  35987. constructor() {
  35988. /**
  35989. * The type property is used for detecting the object type
  35990. * in context of serialization/deserialization.
  35991. *
  35992. * @type {string}
  35993. * @readonly
  35994. */
  35995. this.type = 'StereoCamera';
  35996. /**
  35997. * The aspect.
  35998. *
  35999. * @type {number}
  36000. * @default 1
  36001. */
  36002. this.aspect = 1;
  36003. /**
  36004. * The eye separation which represents the distance
  36005. * between the left and right camera.
  36006. *
  36007. * @type {number}
  36008. * @default 0.064
  36009. */
  36010. this.eyeSep = 0.064;
  36011. /**
  36012. * The camera representing the left eye. This is added to layer `1` so objects to be
  36013. * rendered by the left camera must also be added to this layer.
  36014. *
  36015. * @type {PerspectiveCamera}
  36016. */
  36017. this.cameraL = new PerspectiveCamera();
  36018. this.cameraL.layers.enable( 1 );
  36019. this.cameraL.matrixAutoUpdate = false;
  36020. /**
  36021. * The camera representing the right eye. This is added to layer `2` so objects to be
  36022. * rendered by the right camera must also be added to this layer.
  36023. *
  36024. * @type {PerspectiveCamera}
  36025. */
  36026. this.cameraR = new PerspectiveCamera();
  36027. this.cameraR.layers.enable( 2 );
  36028. this.cameraR.matrixAutoUpdate = false;
  36029. this._cache = {
  36030. focus: null,
  36031. fov: null,
  36032. aspect: null,
  36033. near: null,
  36034. far: null,
  36035. zoom: null,
  36036. eyeSep: null
  36037. };
  36038. }
  36039. /**
  36040. * Updates the stereo camera based on the given perspective camera.
  36041. *
  36042. * @param {PerspectiveCamera} camera - The perspective camera.
  36043. */
  36044. update( camera ) {
  36045. const cache = this._cache;
  36046. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36047. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36048. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36049. if ( needsUpdate ) {
  36050. cache.focus = camera.focus;
  36051. cache.fov = camera.fov;
  36052. cache.aspect = camera.aspect * this.aspect;
  36053. cache.near = camera.near;
  36054. cache.far = camera.far;
  36055. cache.zoom = camera.zoom;
  36056. cache.eyeSep = this.eyeSep;
  36057. // Off-axis stereoscopic effect based on
  36058. // http://paulbourke.net/stereographics/stereorender/
  36059. _projectionMatrix.copy( camera.projectionMatrix );
  36060. const eyeSepHalf = cache.eyeSep / 2;
  36061. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36062. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36063. let xmin, xmax;
  36064. // translate xOffset
  36065. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36066. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36067. // for left eye
  36068. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36069. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36070. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36071. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36072. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36073. // for right eye
  36074. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36075. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36076. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36077. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36078. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36079. }
  36080. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36081. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36082. }
  36083. }
  36084. /**
  36085. * This type of camera can be used in order to efficiently render a scene with a
  36086. * predefined set of cameras. This is an important performance aspect for
  36087. * rendering VR scenes.
  36088. *
  36089. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36090. * to define for each sub camera the `viewport` property which determines the
  36091. * part of the viewport that is rendered with this camera.
  36092. *
  36093. * @augments PerspectiveCamera
  36094. */
  36095. class ArrayCamera extends PerspectiveCamera {
  36096. /**
  36097. * Constructs a new array camera.
  36098. *
  36099. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36100. */
  36101. constructor( array = [] ) {
  36102. super();
  36103. /**
  36104. * This flag can be used for type testing.
  36105. *
  36106. * @type {boolean}
  36107. * @readonly
  36108. * @default true
  36109. */
  36110. this.isArrayCamera = true;
  36111. /**
  36112. * Whether this camera is used with multiview rendering or not.
  36113. *
  36114. * @type {boolean}
  36115. * @readonly
  36116. * @default false
  36117. */
  36118. this.isMultiViewCamera = false;
  36119. /**
  36120. * An array of perspective sub cameras.
  36121. *
  36122. * @type {Array<PerspectiveCamera>}
  36123. */
  36124. this.cameras = array;
  36125. }
  36126. }
  36127. /**
  36128. * Class for keeping track of time.
  36129. */
  36130. class Clock {
  36131. /**
  36132. * Constructs a new clock.
  36133. *
  36134. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36135. * `getDelta()` is called for the first time.
  36136. */
  36137. constructor( autoStart = true ) {
  36138. /**
  36139. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36140. * for the first time.
  36141. *
  36142. * @type {boolean}
  36143. * @default true
  36144. */
  36145. this.autoStart = autoStart;
  36146. /**
  36147. * Holds the time at which the clock's `start()` method was last called.
  36148. *
  36149. * @type {number}
  36150. * @default 0
  36151. */
  36152. this.startTime = 0;
  36153. /**
  36154. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36155. * `getDelta()` methods were last called.
  36156. *
  36157. * @type {number}
  36158. * @default 0
  36159. */
  36160. this.oldTime = 0;
  36161. /**
  36162. * Keeps track of the total time that the clock has been running.
  36163. *
  36164. * @type {number}
  36165. * @default 0
  36166. */
  36167. this.elapsedTime = 0;
  36168. /**
  36169. * Whether the clock is running or not.
  36170. *
  36171. * @type {boolean}
  36172. * @default true
  36173. */
  36174. this.running = false;
  36175. }
  36176. /**
  36177. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36178. * called by the class.
  36179. */
  36180. start() {
  36181. this.startTime = performance.now();
  36182. this.oldTime = this.startTime;
  36183. this.elapsedTime = 0;
  36184. this.running = true;
  36185. }
  36186. /**
  36187. * Stops the clock.
  36188. */
  36189. stop() {
  36190. this.getElapsedTime();
  36191. this.running = false;
  36192. this.autoStart = false;
  36193. }
  36194. /**
  36195. * Returns the elapsed time in seconds.
  36196. *
  36197. * @return {number} The elapsed time.
  36198. */
  36199. getElapsedTime() {
  36200. this.getDelta();
  36201. return this.elapsedTime;
  36202. }
  36203. /**
  36204. * Returns the delta time in seconds.
  36205. *
  36206. * @return {number} The delta time.
  36207. */
  36208. getDelta() {
  36209. let diff = 0;
  36210. if ( this.autoStart && ! this.running ) {
  36211. this.start();
  36212. return 0;
  36213. }
  36214. if ( this.running ) {
  36215. const newTime = performance.now();
  36216. diff = ( newTime - this.oldTime ) / 1000;
  36217. this.oldTime = newTime;
  36218. this.elapsedTime += diff;
  36219. }
  36220. return diff;
  36221. }
  36222. }
  36223. const _position$1 = /*@__PURE__*/ new Vector3();
  36224. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36225. const _scale$1 = /*@__PURE__*/ new Vector3();
  36226. const _forward = /*@__PURE__*/ new Vector3();
  36227. const _up = /*@__PURE__*/ new Vector3();
  36228. /**
  36229. * The class represents a virtual listener of the all positional and non-positional audio effects
  36230. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36231. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36232. *
  36233. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36234. * camera represents the 3D transformation of the listener.
  36235. *
  36236. * @augments Object3D
  36237. */
  36238. class AudioListener extends Object3D {
  36239. /**
  36240. * Constructs a new audio listener.
  36241. */
  36242. constructor() {
  36243. super();
  36244. this.type = 'AudioListener';
  36245. /**
  36246. * The native audio context.
  36247. *
  36248. * @type {AudioContext}
  36249. * @readonly
  36250. */
  36251. this.context = AudioContext.getContext();
  36252. /**
  36253. * The gain node used for volume control.
  36254. *
  36255. * @type {GainNode}
  36256. * @readonly
  36257. */
  36258. this.gain = this.context.createGain();
  36259. this.gain.connect( this.context.destination );
  36260. /**
  36261. * An optional filter.
  36262. *
  36263. * Defined via {@link AudioListener#setFilter}.
  36264. *
  36265. * @type {?AudioNode}
  36266. * @default null
  36267. * @readonly
  36268. */
  36269. this.filter = null;
  36270. /**
  36271. * Time delta values required for `linearRampToValueAtTime()` usage.
  36272. *
  36273. * @type {number}
  36274. * @default 0
  36275. * @readonly
  36276. */
  36277. this.timeDelta = 0;
  36278. // private
  36279. this._clock = new Clock();
  36280. }
  36281. /**
  36282. * Returns the listener's input node.
  36283. *
  36284. * This method is used by other audio nodes to connect to this listener.
  36285. *
  36286. * @return {GainNode} The input node.
  36287. */
  36288. getInput() {
  36289. return this.gain;
  36290. }
  36291. /**
  36292. * Removes the current filter from this listener.
  36293. *
  36294. * @return {AudioListener} A reference to this listener.
  36295. */
  36296. removeFilter() {
  36297. if ( this.filter !== null ) {
  36298. this.gain.disconnect( this.filter );
  36299. this.filter.disconnect( this.context.destination );
  36300. this.gain.connect( this.context.destination );
  36301. this.filter = null;
  36302. }
  36303. return this;
  36304. }
  36305. /**
  36306. * Returns the current set filter.
  36307. *
  36308. * @return {?AudioNode} The filter.
  36309. */
  36310. getFilter() {
  36311. return this.filter;
  36312. }
  36313. /**
  36314. * Sets the given filter to this listener.
  36315. *
  36316. * @param {AudioNode} value - The filter to set.
  36317. * @return {AudioListener} A reference to this listener.
  36318. */
  36319. setFilter( value ) {
  36320. if ( this.filter !== null ) {
  36321. this.gain.disconnect( this.filter );
  36322. this.filter.disconnect( this.context.destination );
  36323. } else {
  36324. this.gain.disconnect( this.context.destination );
  36325. }
  36326. this.filter = value;
  36327. this.gain.connect( this.filter );
  36328. this.filter.connect( this.context.destination );
  36329. return this;
  36330. }
  36331. /**
  36332. * Returns the applications master volume.
  36333. *
  36334. * @return {number} The master volume.
  36335. */
  36336. getMasterVolume() {
  36337. return this.gain.gain.value;
  36338. }
  36339. /**
  36340. * Sets the applications master volume. This volume setting affects
  36341. * all audio nodes in the scene.
  36342. *
  36343. * @param {number} value - The master volume to set.
  36344. * @return {AudioListener} A reference to this listener.
  36345. */
  36346. setMasterVolume( value ) {
  36347. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36348. return this;
  36349. }
  36350. updateMatrixWorld( force ) {
  36351. super.updateMatrixWorld( force );
  36352. const listener = this.context.listener;
  36353. this.timeDelta = this._clock.getDelta();
  36354. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36355. // the initial forward and up directions must be orthogonal
  36356. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36357. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36358. if ( listener.positionX ) {
  36359. // code path for Chrome (see #14393)
  36360. const endTime = this.context.currentTime + this.timeDelta;
  36361. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36362. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36363. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36364. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36365. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36366. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36367. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36368. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36369. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36370. } else {
  36371. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36372. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36373. }
  36374. }
  36375. }
  36376. /**
  36377. * Represents a non-positional ( global ) audio object.
  36378. *
  36379. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36380. *
  36381. * ```js
  36382. * // create an AudioListener and add it to the camera
  36383. * const listener = new THREE.AudioListener();
  36384. * camera.add( listener );
  36385. *
  36386. * // create a global audio source
  36387. * const sound = new THREE.Audio( listener );
  36388. *
  36389. * // load a sound and set it as the Audio object's buffer
  36390. * const audioLoader = new THREE.AudioLoader();
  36391. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36392. * sound.setBuffer( buffer );
  36393. * sound.setLoop( true );
  36394. * sound.setVolume( 0.5 );
  36395. * sound.play();
  36396. * });
  36397. * ```
  36398. *
  36399. * @augments Object3D
  36400. */
  36401. class Audio extends Object3D {
  36402. /**
  36403. * Constructs a new audio.
  36404. *
  36405. * @param {AudioListener} listener - The global audio listener.
  36406. */
  36407. constructor( listener ) {
  36408. super();
  36409. this.type = 'Audio';
  36410. /**
  36411. * The global audio listener.
  36412. *
  36413. * @type {AudioListener}
  36414. * @readonly
  36415. */
  36416. this.listener = listener;
  36417. /**
  36418. * The audio context.
  36419. *
  36420. * @type {AudioContext}
  36421. * @readonly
  36422. */
  36423. this.context = listener.context;
  36424. /**
  36425. * The gain node used for volume control.
  36426. *
  36427. * @type {GainNode}
  36428. * @readonly
  36429. */
  36430. this.gain = this.context.createGain();
  36431. this.gain.connect( listener.getInput() );
  36432. /**
  36433. * Whether to start playback automatically or not.
  36434. *
  36435. * @type {boolean}
  36436. * @default false
  36437. */
  36438. this.autoplay = false;
  36439. /**
  36440. * A reference to an audio buffer.
  36441. *
  36442. * Defined via {@link Audio#setBuffer}.
  36443. *
  36444. * @type {?AudioBuffer}
  36445. * @default null
  36446. * @readonly
  36447. */
  36448. this.buffer = null;
  36449. /**
  36450. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36451. * +/- 1200 is an octave.
  36452. *
  36453. * Defined via {@link Audio#setDetune}.
  36454. *
  36455. * @type {number}
  36456. * @default 0
  36457. * @readonly
  36458. */
  36459. this.detune = 0;
  36460. /**
  36461. * Whether the audio should loop or not.
  36462. *
  36463. * Defined via {@link Audio#setLoop}.
  36464. *
  36465. * @type {boolean}
  36466. * @default false
  36467. * @readonly
  36468. */
  36469. this.loop = false;
  36470. /**
  36471. * Defines where in the audio buffer the replay should
  36472. * start, in seconds.
  36473. *
  36474. * @type {number}
  36475. * @default 0
  36476. */
  36477. this.loopStart = 0;
  36478. /**
  36479. * Defines where in the audio buffer the replay should
  36480. * stop, in seconds.
  36481. *
  36482. * @type {number}
  36483. * @default 0
  36484. */
  36485. this.loopEnd = 0;
  36486. /**
  36487. * An offset to the time within the audio buffer the playback
  36488. * should begin, in seconds.
  36489. *
  36490. * @type {number}
  36491. * @default 0
  36492. */
  36493. this.offset = 0;
  36494. /**
  36495. * Overrides the default duration of the audio.
  36496. *
  36497. * @type {undefined|number}
  36498. * @default undefined
  36499. */
  36500. this.duration = undefined;
  36501. /**
  36502. * The playback speed.
  36503. *
  36504. * Defined via {@link Audio#setPlaybackRate}.
  36505. *
  36506. * @type {number}
  36507. * @readonly
  36508. * @default 1
  36509. */
  36510. this.playbackRate = 1;
  36511. /**
  36512. * Indicates whether the audio is playing or not.
  36513. *
  36514. * This flag will be automatically set when using {@link Audio#play},
  36515. * {@link Audio#pause}, {@link Audio#stop}.
  36516. *
  36517. * @type {boolean}
  36518. * @readonly
  36519. * @default false
  36520. */
  36521. this.isPlaying = false;
  36522. /**
  36523. * Indicates whether the audio playback can be controlled
  36524. * with method like {@link Audio#play} or {@link Audio#pause}.
  36525. *
  36526. * This flag will be automatically set when audio sources are
  36527. * defined.
  36528. *
  36529. * @type {boolean}
  36530. * @readonly
  36531. * @default true
  36532. */
  36533. this.hasPlaybackControl = true;
  36534. /**
  36535. * Holds a reference to the current audio source.
  36536. *
  36537. * The property is automatically by one of the `set*()` methods.
  36538. *
  36539. * @type {?AudioNode}
  36540. * @readonly
  36541. * @default null
  36542. */
  36543. this.source = null;
  36544. /**
  36545. * Defines the source type.
  36546. *
  36547. * The property is automatically by one of the `set*()` methods.
  36548. *
  36549. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36550. * @readonly
  36551. * @default 'empty'
  36552. */
  36553. this.sourceType = 'empty';
  36554. this._startedAt = 0;
  36555. this._progress = 0;
  36556. this._connected = false;
  36557. /**
  36558. * Can be used to apply a variety of low-order filters to create
  36559. * more complex sound effects e.g. via `BiquadFilterNode`.
  36560. *
  36561. * The property is automatically set by {@link Audio#setFilters}.
  36562. *
  36563. * @type {Array<AudioNode>}
  36564. * @readonly
  36565. */
  36566. this.filters = [];
  36567. }
  36568. /**
  36569. * Returns the output audio node.
  36570. *
  36571. * @return {GainNode} The output node.
  36572. */
  36573. getOutput() {
  36574. return this.gain;
  36575. }
  36576. /**
  36577. * Sets the given audio node as the source of this instance.
  36578. *
  36579. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36580. *
  36581. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36582. * @return {Audio} A reference to this instance.
  36583. */
  36584. setNodeSource( audioNode ) {
  36585. this.hasPlaybackControl = false;
  36586. this.sourceType = 'audioNode';
  36587. this.source = audioNode;
  36588. this.connect();
  36589. return this;
  36590. }
  36591. /**
  36592. * Sets the given media element as the source of this instance.
  36593. *
  36594. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36595. *
  36596. * @param {HTMLMediaElement} mediaElement - The media element.
  36597. * @return {Audio} A reference to this instance.
  36598. */
  36599. setMediaElementSource( mediaElement ) {
  36600. this.hasPlaybackControl = false;
  36601. this.sourceType = 'mediaNode';
  36602. this.source = this.context.createMediaElementSource( mediaElement );
  36603. this.connect();
  36604. return this;
  36605. }
  36606. /**
  36607. * Sets the given media stream as the source of this instance.
  36608. *
  36609. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36610. *
  36611. * @param {MediaStream} mediaStream - The media stream.
  36612. * @return {Audio} A reference to this instance.
  36613. */
  36614. setMediaStreamSource( mediaStream ) {
  36615. this.hasPlaybackControl = false;
  36616. this.sourceType = 'mediaStreamNode';
  36617. this.source = this.context.createMediaStreamSource( mediaStream );
  36618. this.connect();
  36619. return this;
  36620. }
  36621. /**
  36622. * Sets the given audio buffer as the source of this instance.
  36623. *
  36624. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36625. *
  36626. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36627. * @return {Audio} A reference to this instance.
  36628. */
  36629. setBuffer( audioBuffer ) {
  36630. this.buffer = audioBuffer;
  36631. this.sourceType = 'buffer';
  36632. if ( this.autoplay ) this.play();
  36633. return this;
  36634. }
  36635. /**
  36636. * Starts the playback of the audio.
  36637. *
  36638. * Can only be used with compatible audio sources that allow playback control.
  36639. *
  36640. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36641. * @return {Audio|undefined} A reference to this instance.
  36642. */
  36643. play( delay = 0 ) {
  36644. if ( this.isPlaying === true ) {
  36645. warn( 'Audio: Audio is already playing.' );
  36646. return;
  36647. }
  36648. if ( this.hasPlaybackControl === false ) {
  36649. warn( 'Audio: this Audio has no playback control.' );
  36650. return;
  36651. }
  36652. this._startedAt = this.context.currentTime + delay;
  36653. const source = this.context.createBufferSource();
  36654. source.buffer = this.buffer;
  36655. source.loop = this.loop;
  36656. source.loopStart = this.loopStart;
  36657. source.loopEnd = this.loopEnd;
  36658. source.onended = this.onEnded.bind( this );
  36659. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36660. this.isPlaying = true;
  36661. this.source = source;
  36662. this.setDetune( this.detune );
  36663. this.setPlaybackRate( this.playbackRate );
  36664. return this.connect();
  36665. }
  36666. /**
  36667. * Pauses the playback of the audio.
  36668. *
  36669. * Can only be used with compatible audio sources that allow playback control.
  36670. *
  36671. * @return {Audio|undefined} A reference to this instance.
  36672. */
  36673. pause() {
  36674. if ( this.hasPlaybackControl === false ) {
  36675. warn( 'Audio: this Audio has no playback control.' );
  36676. return;
  36677. }
  36678. if ( this.isPlaying === true ) {
  36679. // update current progress
  36680. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36681. if ( this.loop === true ) {
  36682. // ensure _progress does not exceed duration with looped audios
  36683. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36684. }
  36685. this.source.stop();
  36686. this.source.onended = null;
  36687. this.isPlaying = false;
  36688. }
  36689. return this;
  36690. }
  36691. /**
  36692. * Stops the playback of the audio.
  36693. *
  36694. * Can only be used with compatible audio sources that allow playback control.
  36695. *
  36696. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36697. * @return {Audio|undefined} A reference to this instance.
  36698. */
  36699. stop( delay = 0 ) {
  36700. if ( this.hasPlaybackControl === false ) {
  36701. warn( 'Audio: this Audio has no playback control.' );
  36702. return;
  36703. }
  36704. this._progress = 0;
  36705. if ( this.source !== null ) {
  36706. this.source.stop( this.context.currentTime + delay );
  36707. this.source.onended = null;
  36708. }
  36709. this.isPlaying = false;
  36710. return this;
  36711. }
  36712. /**
  36713. * Connects to the audio source. This is used internally on
  36714. * initialisation and when setting / removing filters.
  36715. *
  36716. * @return {Audio} A reference to this instance.
  36717. */
  36718. connect() {
  36719. if ( this.filters.length > 0 ) {
  36720. this.source.connect( this.filters[ 0 ] );
  36721. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36722. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36723. }
  36724. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36725. } else {
  36726. this.source.connect( this.getOutput() );
  36727. }
  36728. this._connected = true;
  36729. return this;
  36730. }
  36731. /**
  36732. * Disconnects to the audio source. This is used internally on
  36733. * initialisation and when setting / removing filters.
  36734. *
  36735. * @return {Audio|undefined} A reference to this instance.
  36736. */
  36737. disconnect() {
  36738. if ( this._connected === false ) {
  36739. return;
  36740. }
  36741. if ( this.filters.length > 0 ) {
  36742. this.source.disconnect( this.filters[ 0 ] );
  36743. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36744. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36745. }
  36746. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36747. } else {
  36748. this.source.disconnect( this.getOutput() );
  36749. }
  36750. this._connected = false;
  36751. return this;
  36752. }
  36753. /**
  36754. * Returns the current set filters.
  36755. *
  36756. * @return {Array<AudioNode>} The list of filters.
  36757. */
  36758. getFilters() {
  36759. return this.filters;
  36760. }
  36761. /**
  36762. * Sets an array of filters and connects them with the audio source.
  36763. *
  36764. * @param {Array<AudioNode>} [value] - A list of filters.
  36765. * @return {Audio} A reference to this instance.
  36766. */
  36767. setFilters( value ) {
  36768. if ( ! value ) value = [];
  36769. if ( this._connected === true ) {
  36770. this.disconnect();
  36771. this.filters = value.slice();
  36772. this.connect();
  36773. } else {
  36774. this.filters = value.slice();
  36775. }
  36776. return this;
  36777. }
  36778. /**
  36779. * Defines the detuning of oscillation in cents.
  36780. *
  36781. * @param {number} value - The detuning of oscillation in cents.
  36782. * @return {Audio} A reference to this instance.
  36783. */
  36784. setDetune( value ) {
  36785. this.detune = value;
  36786. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36787. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36788. }
  36789. return this;
  36790. }
  36791. /**
  36792. * Returns the detuning of oscillation in cents.
  36793. *
  36794. * @return {number} The detuning of oscillation in cents.
  36795. */
  36796. getDetune() {
  36797. return this.detune;
  36798. }
  36799. /**
  36800. * Returns the first filter in the list of filters.
  36801. *
  36802. * @return {AudioNode|undefined} The first filter in the list of filters.
  36803. */
  36804. getFilter() {
  36805. return this.getFilters()[ 0 ];
  36806. }
  36807. /**
  36808. * Applies a single filter node to the audio.
  36809. *
  36810. * @param {AudioNode} [filter] - The filter to set.
  36811. * @return {Audio} A reference to this instance.
  36812. */
  36813. setFilter( filter ) {
  36814. return this.setFilters( filter ? [ filter ] : [] );
  36815. }
  36816. /**
  36817. * Sets the playback rate.
  36818. *
  36819. * Can only be used with compatible audio sources that allow playback control.
  36820. *
  36821. * @param {number} [value] - The playback rate to set.
  36822. * @return {Audio|undefined} A reference to this instance.
  36823. */
  36824. setPlaybackRate( value ) {
  36825. if ( this.hasPlaybackControl === false ) {
  36826. warn( 'Audio: this Audio has no playback control.' );
  36827. return;
  36828. }
  36829. this.playbackRate = value;
  36830. if ( this.isPlaying === true ) {
  36831. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36832. }
  36833. return this;
  36834. }
  36835. /**
  36836. * Returns the current playback rate.
  36837. * @return {number} The playback rate.
  36838. */
  36839. getPlaybackRate() {
  36840. return this.playbackRate;
  36841. }
  36842. /**
  36843. * Automatically called when playback finished.
  36844. */
  36845. onEnded() {
  36846. this.isPlaying = false;
  36847. this._progress = 0;
  36848. }
  36849. /**
  36850. * Returns the loop flag.
  36851. *
  36852. * Can only be used with compatible audio sources that allow playback control.
  36853. *
  36854. * @return {boolean} Whether the audio should loop or not.
  36855. */
  36856. getLoop() {
  36857. if ( this.hasPlaybackControl === false ) {
  36858. warn( 'Audio: this Audio has no playback control.' );
  36859. return false;
  36860. }
  36861. return this.loop;
  36862. }
  36863. /**
  36864. * Sets the loop flag.
  36865. *
  36866. * Can only be used with compatible audio sources that allow playback control.
  36867. *
  36868. * @param {boolean} value - Whether the audio should loop or not.
  36869. * @return {Audio|undefined} A reference to this instance.
  36870. */
  36871. setLoop( value ) {
  36872. if ( this.hasPlaybackControl === false ) {
  36873. warn( 'Audio: this Audio has no playback control.' );
  36874. return;
  36875. }
  36876. this.loop = value;
  36877. if ( this.isPlaying === true ) {
  36878. this.source.loop = this.loop;
  36879. }
  36880. return this;
  36881. }
  36882. /**
  36883. * Sets the loop start value which defines where in the audio buffer the replay should
  36884. * start, in seconds.
  36885. *
  36886. * @param {number} value - The loop start value.
  36887. * @return {Audio} A reference to this instance.
  36888. */
  36889. setLoopStart( value ) {
  36890. this.loopStart = value;
  36891. return this;
  36892. }
  36893. /**
  36894. * Sets the loop end value which defines where in the audio buffer the replay should
  36895. * stop, in seconds.
  36896. *
  36897. * @param {number} value - The loop end value.
  36898. * @return {Audio} A reference to this instance.
  36899. */
  36900. setLoopEnd( value ) {
  36901. this.loopEnd = value;
  36902. return this;
  36903. }
  36904. /**
  36905. * Returns the volume.
  36906. *
  36907. * @return {number} The volume.
  36908. */
  36909. getVolume() {
  36910. return this.gain.gain.value;
  36911. }
  36912. /**
  36913. * Sets the volume.
  36914. *
  36915. * @param {number} value - The volume to set.
  36916. * @return {Audio} A reference to this instance.
  36917. */
  36918. setVolume( value ) {
  36919. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36920. return this;
  36921. }
  36922. copy( source, recursive ) {
  36923. super.copy( source, recursive );
  36924. if ( source.sourceType !== 'buffer' ) {
  36925. warn( 'Audio: Audio source type cannot be copied.' );
  36926. return this;
  36927. }
  36928. this.autoplay = source.autoplay;
  36929. this.buffer = source.buffer;
  36930. this.detune = source.detune;
  36931. this.loop = source.loop;
  36932. this.loopStart = source.loopStart;
  36933. this.loopEnd = source.loopEnd;
  36934. this.offset = source.offset;
  36935. this.duration = source.duration;
  36936. this.playbackRate = source.playbackRate;
  36937. this.hasPlaybackControl = source.hasPlaybackControl;
  36938. this.sourceType = source.sourceType;
  36939. this.filters = source.filters.slice();
  36940. return this;
  36941. }
  36942. clone( recursive ) {
  36943. return new this.constructor( this.listener ).copy( this, recursive );
  36944. }
  36945. }
  36946. const _position = /*@__PURE__*/ new Vector3();
  36947. const _quaternion = /*@__PURE__*/ new Quaternion();
  36948. const _scale = /*@__PURE__*/ new Vector3();
  36949. const _orientation = /*@__PURE__*/ new Vector3();
  36950. /**
  36951. * Represents a positional audio object.
  36952. *
  36953. * ```js
  36954. * // create an AudioListener and add it to the camera
  36955. * const listener = new THREE.AudioListener();
  36956. * camera.add( listener );
  36957. *
  36958. * // create the PositionalAudio object (passing in the listener)
  36959. * const sound = new THREE.PositionalAudio( listener );
  36960. *
  36961. * // load a sound and set it as the PositionalAudio object's buffer
  36962. * const audioLoader = new THREE.AudioLoader();
  36963. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36964. * sound.setBuffer( buffer );
  36965. * sound.setRefDistance( 20 );
  36966. * sound.play();
  36967. * });
  36968. *
  36969. * // create an object for the sound to play from
  36970. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36971. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36972. * const mesh = new THREE.Mesh( sphere, material );
  36973. * scene.add( mesh );
  36974. *
  36975. * // finally add the sound to the mesh
  36976. * mesh.add( sound );
  36977. *
  36978. * @augments Audio
  36979. */
  36980. class PositionalAudio extends Audio {
  36981. /**
  36982. * Constructs a positional audio.
  36983. *
  36984. * @param {AudioListener} listener - The global audio listener.
  36985. */
  36986. constructor( listener ) {
  36987. super( listener );
  36988. /**
  36989. * The panner node represents the location, direction, and behavior of an audio
  36990. * source in 3D space.
  36991. *
  36992. * @type {PannerNode}
  36993. * @readonly
  36994. */
  36995. this.panner = this.context.createPanner();
  36996. this.panner.panningModel = 'HRTF';
  36997. this.panner.connect( this.gain );
  36998. }
  36999. connect() {
  37000. super.connect();
  37001. this.panner.connect( this.gain );
  37002. return this;
  37003. }
  37004. disconnect() {
  37005. super.disconnect();
  37006. this.panner.disconnect( this.gain );
  37007. return this;
  37008. }
  37009. getOutput() {
  37010. return this.panner;
  37011. }
  37012. /**
  37013. * Returns the current reference distance.
  37014. *
  37015. * @return {number} The reference distance.
  37016. */
  37017. getRefDistance() {
  37018. return this.panner.refDistance;
  37019. }
  37020. /**
  37021. * Defines the reference distance for reducing volume as the audio source moves
  37022. * further from the listener – i.e. the distance at which the volume reduction
  37023. * starts taking effect.
  37024. *
  37025. * @param {number} value - The reference distance to set.
  37026. * @return {PositionalAudio} A reference to this instance.
  37027. */
  37028. setRefDistance( value ) {
  37029. this.panner.refDistance = value;
  37030. return this;
  37031. }
  37032. /**
  37033. * Returns the current rolloff factor.
  37034. *
  37035. * @return {number} The rolloff factor.
  37036. */
  37037. getRolloffFactor() {
  37038. return this.panner.rolloffFactor;
  37039. }
  37040. /**
  37041. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37042. *
  37043. * @param {number} value - The rolloff factor.
  37044. * @return {PositionalAudio} A reference to this instance.
  37045. */
  37046. setRolloffFactor( value ) {
  37047. this.panner.rolloffFactor = value;
  37048. return this;
  37049. }
  37050. /**
  37051. * Returns the current distance model.
  37052. *
  37053. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37054. */
  37055. getDistanceModel() {
  37056. return this.panner.distanceModel;
  37057. }
  37058. /**
  37059. * Defines which algorithm to use to reduce the volume of the audio source
  37060. * as it moves away from the listener.
  37061. *
  37062. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37063. * for more details.
  37064. *
  37065. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37066. * @return {PositionalAudio} A reference to this instance.
  37067. */
  37068. setDistanceModel( value ) {
  37069. this.panner.distanceModel = value;
  37070. return this;
  37071. }
  37072. /**
  37073. * Returns the current max distance.
  37074. *
  37075. * @return {number} The max distance.
  37076. */
  37077. getMaxDistance() {
  37078. return this.panner.maxDistance;
  37079. }
  37080. /**
  37081. * Defines the maximum distance between the audio source and the listener,
  37082. * after which the volume is not reduced any further.
  37083. *
  37084. * This value is used only by the `linear` distance model.
  37085. *
  37086. * @param {number} value - The max distance.
  37087. * @return {PositionalAudio} A reference to this instance.
  37088. */
  37089. setMaxDistance( value ) {
  37090. this.panner.maxDistance = value;
  37091. return this;
  37092. }
  37093. /**
  37094. * Sets the directional cone in which the audio can be listened.
  37095. *
  37096. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37097. * @param {number} coneOuterAngle - An angle, in degrees, of a cone outside of which the volume will be reduced by a constant value, defined by the `coneOuterGain` parameter.
  37098. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37099. * @return {PositionalAudio} A reference to this instance.
  37100. */
  37101. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37102. this.panner.coneInnerAngle = coneInnerAngle;
  37103. this.panner.coneOuterAngle = coneOuterAngle;
  37104. this.panner.coneOuterGain = coneOuterGain;
  37105. return this;
  37106. }
  37107. updateMatrixWorld( force ) {
  37108. super.updateMatrixWorld( force );
  37109. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37110. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37111. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37112. const panner = this.panner;
  37113. if ( panner.positionX ) {
  37114. // code path for Chrome and Firefox (see #14393)
  37115. const endTime = this.context.currentTime + this.listener.timeDelta;
  37116. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37117. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37118. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37119. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37120. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37121. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37122. } else {
  37123. panner.setPosition( _position.x, _position.y, _position.z );
  37124. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37125. }
  37126. }
  37127. }
  37128. /**
  37129. * This class can be used to analyse audio data.
  37130. *
  37131. * ```js
  37132. * // create an AudioListener and add it to the camera
  37133. * const listener = new THREE.AudioListener();
  37134. * camera.add( listener );
  37135. *
  37136. * // create an Audio source
  37137. * const sound = new THREE.Audio( listener );
  37138. *
  37139. * // load a sound and set it as the Audio object's buffer
  37140. * const audioLoader = new THREE.AudioLoader();
  37141. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37142. * sound.setBuffer( buffer );
  37143. * sound.setLoop(true);
  37144. * sound.setVolume(0.5);
  37145. * sound.play();
  37146. * });
  37147. *
  37148. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37149. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37150. *
  37151. * // get the average frequency of the sound
  37152. * const data = analyser.getAverageFrequency();
  37153. * ```
  37154. */
  37155. class AudioAnalyser {
  37156. /**
  37157. * Constructs a new audio analyzer.
  37158. *
  37159. * @param {Audio} audio - The audio to analyze.
  37160. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37161. */
  37162. constructor( audio, fftSize = 2048 ) {
  37163. /**
  37164. * The global audio listener.
  37165. *
  37166. * @type {AnalyserNode}
  37167. */
  37168. this.analyser = audio.context.createAnalyser();
  37169. this.analyser.fftSize = fftSize;
  37170. /**
  37171. * Holds the analyzed data.
  37172. *
  37173. * @type {Uint8Array}
  37174. */
  37175. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37176. audio.getOutput().connect( this.analyser );
  37177. }
  37178. /**
  37179. * Returns an array with frequency data of the audio.
  37180. *
  37181. * Each item in the array represents the decibel value for a specific frequency.
  37182. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37183. * For example, for 48000 sample rate, the last item of the array will represent
  37184. * the decibel value for 24000 Hz.
  37185. *
  37186. * @return {Uint8Array} The frequency data.
  37187. */
  37188. getFrequencyData() {
  37189. this.analyser.getByteFrequencyData( this.data );
  37190. return this.data;
  37191. }
  37192. /**
  37193. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37194. *
  37195. * @return {number} The average frequency.
  37196. */
  37197. getAverageFrequency() {
  37198. let value = 0;
  37199. const data = this.getFrequencyData();
  37200. for ( let i = 0; i < data.length; i ++ ) {
  37201. value += data[ i ];
  37202. }
  37203. return value / data.length;
  37204. }
  37205. }
  37206. /**
  37207. * Buffered scene graph property that allows weighted accumulation; used internally.
  37208. */
  37209. class PropertyMixer {
  37210. /**
  37211. * Constructs a new property mixer.
  37212. *
  37213. * @param {PropertyBinding} binding - The property binding.
  37214. * @param {string} typeName - The keyframe track type name.
  37215. * @param {number} valueSize - The keyframe track value size.
  37216. */
  37217. constructor( binding, typeName, valueSize ) {
  37218. /**
  37219. * The property binding.
  37220. *
  37221. * @type {PropertyBinding}
  37222. */
  37223. this.binding = binding;
  37224. /**
  37225. * The keyframe track value size.
  37226. *
  37227. * @type {number}
  37228. */
  37229. this.valueSize = valueSize;
  37230. let mixFunction,
  37231. mixFunctionAdditive,
  37232. setIdentity;
  37233. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37234. //
  37235. // interpolators can use .buffer as their .result
  37236. // the data then goes to 'incoming'
  37237. //
  37238. // 'accu0' and 'accu1' are used frame-interleaved for
  37239. // the cumulative result and are compared to detect
  37240. // changes
  37241. //
  37242. // 'orig' stores the original state of the property
  37243. //
  37244. // 'add' is used for additive cumulative results
  37245. //
  37246. // 'work' is optional and is only present for quaternion types. It is used
  37247. // to store intermediate quaternion multiplication results
  37248. switch ( typeName ) {
  37249. case 'quaternion':
  37250. mixFunction = this._slerp;
  37251. mixFunctionAdditive = this._slerpAdditive;
  37252. setIdentity = this._setAdditiveIdentityQuaternion;
  37253. this.buffer = new Float64Array( valueSize * 6 );
  37254. this._workIndex = 5;
  37255. break;
  37256. case 'string':
  37257. case 'bool':
  37258. mixFunction = this._select;
  37259. // Use the regular mix function and for additive on these types,
  37260. // additive is not relevant for non-numeric types
  37261. mixFunctionAdditive = this._select;
  37262. setIdentity = this._setAdditiveIdentityOther;
  37263. this.buffer = new Array( valueSize * 5 );
  37264. break;
  37265. default:
  37266. mixFunction = this._lerp;
  37267. mixFunctionAdditive = this._lerpAdditive;
  37268. setIdentity = this._setAdditiveIdentityNumeric;
  37269. this.buffer = new Float64Array( valueSize * 5 );
  37270. }
  37271. this._mixBufferRegion = mixFunction;
  37272. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37273. this._setIdentity = setIdentity;
  37274. this._origIndex = 3;
  37275. this._addIndex = 4;
  37276. /**
  37277. * TODO
  37278. *
  37279. * @type {number}
  37280. * @default 0
  37281. */
  37282. this.cumulativeWeight = 0;
  37283. /**
  37284. * TODO
  37285. *
  37286. * @type {number}
  37287. * @default 0
  37288. */
  37289. this.cumulativeWeightAdditive = 0;
  37290. /**
  37291. * TODO
  37292. *
  37293. * @type {number}
  37294. * @default 0
  37295. */
  37296. this.useCount = 0;
  37297. /**
  37298. * TODO
  37299. *
  37300. * @type {number}
  37301. * @default 0
  37302. */
  37303. this.referenceCount = 0;
  37304. }
  37305. /**
  37306. * Accumulates data in the `incoming` region into `accu<i>`.
  37307. *
  37308. * @param {number} accuIndex - The accumulation index.
  37309. * @param {number} weight - The weight.
  37310. */
  37311. accumulate( accuIndex, weight ) {
  37312. // note: happily accumulating nothing when weight = 0, the caller knows
  37313. // the weight and shouldn't have made the call in the first place
  37314. const buffer = this.buffer,
  37315. stride = this.valueSize,
  37316. offset = accuIndex * stride + stride;
  37317. let currentWeight = this.cumulativeWeight;
  37318. if ( currentWeight === 0 ) {
  37319. // accuN := incoming * weight
  37320. for ( let i = 0; i !== stride; ++ i ) {
  37321. buffer[ offset + i ] = buffer[ i ];
  37322. }
  37323. currentWeight = weight;
  37324. } else {
  37325. // accuN := accuN + incoming * weight
  37326. currentWeight += weight;
  37327. const mix = weight / currentWeight;
  37328. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37329. }
  37330. this.cumulativeWeight = currentWeight;
  37331. }
  37332. /**
  37333. * Accumulates data in the `incoming` region into `add`.
  37334. *
  37335. * @param {number} weight - The weight.
  37336. */
  37337. accumulateAdditive( weight ) {
  37338. const buffer = this.buffer,
  37339. stride = this.valueSize,
  37340. offset = stride * this._addIndex;
  37341. if ( this.cumulativeWeightAdditive === 0 ) {
  37342. // add = identity
  37343. this._setIdentity();
  37344. }
  37345. // add := add + incoming * weight
  37346. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37347. this.cumulativeWeightAdditive += weight;
  37348. }
  37349. /**
  37350. * Applies the state of `accu<i>` to the binding when accus differ.
  37351. *
  37352. * @param {number} accuIndex - The accumulation index.
  37353. */
  37354. apply( accuIndex ) {
  37355. const stride = this.valueSize,
  37356. buffer = this.buffer,
  37357. offset = accuIndex * stride + stride,
  37358. weight = this.cumulativeWeight,
  37359. weightAdditive = this.cumulativeWeightAdditive,
  37360. binding = this.binding;
  37361. this.cumulativeWeight = 0;
  37362. this.cumulativeWeightAdditive = 0;
  37363. if ( weight < 1 ) {
  37364. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37365. const originalValueOffset = stride * this._origIndex;
  37366. this._mixBufferRegion(
  37367. buffer, offset, originalValueOffset, 1 - weight, stride );
  37368. }
  37369. if ( weightAdditive > 0 ) {
  37370. // accuN := accuN + additive accuN
  37371. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37372. }
  37373. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37374. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37375. // value has changed -> update scene graph
  37376. binding.setValue( buffer, offset );
  37377. break;
  37378. }
  37379. }
  37380. }
  37381. /**
  37382. * Remembers the state of the bound property and copy it to both accus.
  37383. */
  37384. saveOriginalState() {
  37385. const binding = this.binding;
  37386. const buffer = this.buffer,
  37387. stride = this.valueSize,
  37388. originalValueOffset = stride * this._origIndex;
  37389. binding.getValue( buffer, originalValueOffset );
  37390. // accu[0..1] := orig -- initially detect changes against the original
  37391. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37392. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37393. }
  37394. // Add to identity for additive
  37395. this._setIdentity();
  37396. this.cumulativeWeight = 0;
  37397. this.cumulativeWeightAdditive = 0;
  37398. }
  37399. /**
  37400. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37401. */
  37402. restoreOriginalState() {
  37403. const originalValueOffset = this.valueSize * 3;
  37404. this.binding.setValue( this.buffer, originalValueOffset );
  37405. }
  37406. // internals
  37407. _setAdditiveIdentityNumeric() {
  37408. const startIndex = this._addIndex * this.valueSize;
  37409. const endIndex = startIndex + this.valueSize;
  37410. for ( let i = startIndex; i < endIndex; i ++ ) {
  37411. this.buffer[ i ] = 0;
  37412. }
  37413. }
  37414. _setAdditiveIdentityQuaternion() {
  37415. this._setAdditiveIdentityNumeric();
  37416. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37417. }
  37418. _setAdditiveIdentityOther() {
  37419. const startIndex = this._origIndex * this.valueSize;
  37420. const targetIndex = this._addIndex * this.valueSize;
  37421. for ( let i = 0; i < this.valueSize; i ++ ) {
  37422. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37423. }
  37424. }
  37425. // mix functions
  37426. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37427. if ( t >= 0.5 ) {
  37428. for ( let i = 0; i !== stride; ++ i ) {
  37429. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37430. }
  37431. }
  37432. }
  37433. _slerp( buffer, dstOffset, srcOffset, t ) {
  37434. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37435. }
  37436. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37437. const workOffset = this._workIndex * stride;
  37438. // Store result in intermediate buffer offset
  37439. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37440. // Slerp to the intermediate result
  37441. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37442. }
  37443. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37444. const s = 1 - t;
  37445. for ( let i = 0; i !== stride; ++ i ) {
  37446. const j = dstOffset + i;
  37447. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37448. }
  37449. }
  37450. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37451. for ( let i = 0; i !== stride; ++ i ) {
  37452. const j = dstOffset + i;
  37453. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37454. }
  37455. }
  37456. }
  37457. // Characters [].:/ are reserved for track binding syntax.
  37458. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37459. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37460. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37461. // only latin characters, and the unicode \p{L} is not yet supported. So
  37462. // instead, we exclude reserved characters and match everything else.
  37463. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37464. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37465. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37466. // be matched to parse the rest of the track name.
  37467. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37468. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37469. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37470. // Object on target node, and accessor. May not contain reserved
  37471. // characters. Accessor may contain any character except closing bracket.
  37472. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37473. // Property and accessor. May not contain reserved characters. Accessor may
  37474. // contain any non-bracket characters.
  37475. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37476. const _trackRe = new RegExp( ''
  37477. + '^'
  37478. + _directoryRe
  37479. + _nodeRe
  37480. + _objectRe
  37481. + _propertyRe
  37482. + '$'
  37483. );
  37484. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37485. class Composite {
  37486. constructor( targetGroup, path, optionalParsedPath ) {
  37487. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37488. this._targetGroup = targetGroup;
  37489. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37490. }
  37491. getValue( array, offset ) {
  37492. this.bind(); // bind all binding
  37493. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37494. binding = this._bindings[ firstValidIndex ];
  37495. // and only call .getValue on the first
  37496. if ( binding !== undefined ) binding.getValue( array, offset );
  37497. }
  37498. setValue( array, offset ) {
  37499. const bindings = this._bindings;
  37500. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37501. bindings[ i ].setValue( array, offset );
  37502. }
  37503. }
  37504. bind() {
  37505. const bindings = this._bindings;
  37506. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37507. bindings[ i ].bind();
  37508. }
  37509. }
  37510. unbind() {
  37511. const bindings = this._bindings;
  37512. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37513. bindings[ i ].unbind();
  37514. }
  37515. }
  37516. }
  37517. // Note: This class uses a State pattern on a per-method basis:
  37518. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37519. // prototype version of these methods with one that represents
  37520. // the bound state. When the property is not found, the methods
  37521. // become no-ops.
  37522. /**
  37523. * This holds a reference to a real property in the scene graph; used internally.
  37524. */
  37525. class PropertyBinding {
  37526. /**
  37527. * Constructs a new property binding.
  37528. *
  37529. * @param {Object} rootNode - The root node.
  37530. * @param {string} path - The path.
  37531. * @param {?Object} [parsedPath] - The parsed path.
  37532. */
  37533. constructor( rootNode, path, parsedPath ) {
  37534. /**
  37535. * The object path to the animated property.
  37536. *
  37537. * @type {string}
  37538. */
  37539. this.path = path;
  37540. /**
  37541. * An object holding information about the path.
  37542. *
  37543. * @type {Object}
  37544. */
  37545. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37546. /**
  37547. * The object owns the animated property.
  37548. *
  37549. * @type {?Object}
  37550. */
  37551. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37552. /**
  37553. * The root node.
  37554. *
  37555. * @type {Object3D|Skeleton}
  37556. */
  37557. this.rootNode = rootNode;
  37558. // initial state of these methods that calls 'bind'
  37559. this.getValue = this._getValue_unbound;
  37560. this.setValue = this._setValue_unbound;
  37561. }
  37562. /**
  37563. * Factory method for creating a property binding from the given parameters.
  37564. *
  37565. * @static
  37566. * @param {Object} root - The root node.
  37567. * @param {string} path - The path.
  37568. * @param {?Object} [parsedPath] - The parsed path.
  37569. * @return {PropertyBinding|Composite} The created property binding or composite.
  37570. */
  37571. static create( root, path, parsedPath ) {
  37572. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37573. return new PropertyBinding( root, path, parsedPath );
  37574. } else {
  37575. return new PropertyBinding.Composite( root, path, parsedPath );
  37576. }
  37577. }
  37578. /**
  37579. * Replaces spaces with underscores and removes unsupported characters from
  37580. * node names, to ensure compatibility with parseTrackName().
  37581. *
  37582. * @param {string} name - Node name to be sanitized.
  37583. * @return {string} The sanitized node name.
  37584. */
  37585. static sanitizeNodeName( name ) {
  37586. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37587. }
  37588. /**
  37589. * Parses the given track name (an object path to an animated property) and
  37590. * returns an object with information about the path. Matches strings in the following forms:
  37591. *
  37592. * - nodeName.property
  37593. * - nodeName.property[accessor]
  37594. * - nodeName.material.property[accessor]
  37595. * - uuid.property[accessor]
  37596. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37597. * - parentName/nodeName.property
  37598. * - parentName/parentName/nodeName.property[index]
  37599. * - .bone[Armature.DEF_cog].position
  37600. * - scene:helium_balloon_model:helium_balloon_model.position
  37601. *
  37602. * @static
  37603. * @param {string} trackName - The track name to parse.
  37604. * @return {Object} The parsed track name as an object.
  37605. */
  37606. static parseTrackName( trackName ) {
  37607. const matches = _trackRe.exec( trackName );
  37608. if ( matches === null ) {
  37609. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37610. }
  37611. const results = {
  37612. // directoryName: matches[ 1 ], // (tschw) currently unused
  37613. nodeName: matches[ 2 ],
  37614. objectName: matches[ 3 ],
  37615. objectIndex: matches[ 4 ],
  37616. propertyName: matches[ 5 ], // required
  37617. propertyIndex: matches[ 6 ]
  37618. };
  37619. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37620. if ( lastDot !== undefined && lastDot !== -1 ) {
  37621. const objectName = results.nodeName.substring( lastDot + 1 );
  37622. // Object names must be checked against an allowlist. Otherwise, there
  37623. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37624. // 'bar' could be the objectName, or part of a nodeName (which can
  37625. // include '.' characters).
  37626. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37627. results.nodeName = results.nodeName.substring( 0, lastDot );
  37628. results.objectName = objectName;
  37629. }
  37630. }
  37631. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37632. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37633. }
  37634. return results;
  37635. }
  37636. /**
  37637. * Searches for a node in the hierarchy of the given root object by the given
  37638. * node name.
  37639. *
  37640. * @static
  37641. * @param {Object} root - The root object.
  37642. * @param {string|number} nodeName - The name of the node.
  37643. * @return {?Object} The found node. Returns `null` if no object was found.
  37644. */
  37645. static findNode( root, nodeName ) {
  37646. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37647. return root;
  37648. }
  37649. // search into skeleton bones.
  37650. if ( root.skeleton ) {
  37651. const bone = root.skeleton.getBoneByName( nodeName );
  37652. if ( bone !== undefined ) {
  37653. return bone;
  37654. }
  37655. }
  37656. // search into node subtree.
  37657. if ( root.children ) {
  37658. const searchNodeSubtree = function ( children ) {
  37659. for ( let i = 0; i < children.length; i ++ ) {
  37660. const childNode = children[ i ];
  37661. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37662. return childNode;
  37663. }
  37664. const result = searchNodeSubtree( childNode.children );
  37665. if ( result ) return result;
  37666. }
  37667. return null;
  37668. };
  37669. const subTreeNode = searchNodeSubtree( root.children );
  37670. if ( subTreeNode ) {
  37671. return subTreeNode;
  37672. }
  37673. }
  37674. return null;
  37675. }
  37676. // these are used to "bind" a nonexistent property
  37677. _getValue_unavailable() {}
  37678. _setValue_unavailable() {}
  37679. // Getters
  37680. _getValue_direct( buffer, offset ) {
  37681. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37682. }
  37683. _getValue_array( buffer, offset ) {
  37684. const source = this.resolvedProperty;
  37685. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37686. buffer[ offset ++ ] = source[ i ];
  37687. }
  37688. }
  37689. _getValue_arrayElement( buffer, offset ) {
  37690. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37691. }
  37692. _getValue_toArray( buffer, offset ) {
  37693. this.resolvedProperty.toArray( buffer, offset );
  37694. }
  37695. // Direct
  37696. _setValue_direct( buffer, offset ) {
  37697. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37698. }
  37699. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37700. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37701. this.targetObject.needsUpdate = true;
  37702. }
  37703. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37704. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37705. this.targetObject.matrixWorldNeedsUpdate = true;
  37706. }
  37707. // EntireArray
  37708. _setValue_array( buffer, offset ) {
  37709. const dest = this.resolvedProperty;
  37710. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37711. dest[ i ] = buffer[ offset ++ ];
  37712. }
  37713. }
  37714. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37715. const dest = this.resolvedProperty;
  37716. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37717. dest[ i ] = buffer[ offset ++ ];
  37718. }
  37719. this.targetObject.needsUpdate = true;
  37720. }
  37721. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37722. const dest = this.resolvedProperty;
  37723. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37724. dest[ i ] = buffer[ offset ++ ];
  37725. }
  37726. this.targetObject.matrixWorldNeedsUpdate = true;
  37727. }
  37728. // ArrayElement
  37729. _setValue_arrayElement( buffer, offset ) {
  37730. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37731. }
  37732. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37733. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37734. this.targetObject.needsUpdate = true;
  37735. }
  37736. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37737. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37738. this.targetObject.matrixWorldNeedsUpdate = true;
  37739. }
  37740. // HasToFromArray
  37741. _setValue_fromArray( buffer, offset ) {
  37742. this.resolvedProperty.fromArray( buffer, offset );
  37743. }
  37744. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37745. this.resolvedProperty.fromArray( buffer, offset );
  37746. this.targetObject.needsUpdate = true;
  37747. }
  37748. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37749. this.resolvedProperty.fromArray( buffer, offset );
  37750. this.targetObject.matrixWorldNeedsUpdate = true;
  37751. }
  37752. _getValue_unbound( targetArray, offset ) {
  37753. this.bind();
  37754. this.getValue( targetArray, offset );
  37755. }
  37756. _setValue_unbound( sourceArray, offset ) {
  37757. this.bind();
  37758. this.setValue( sourceArray, offset );
  37759. }
  37760. /**
  37761. * Creates a getter / setter pair for the property tracked by this binding.
  37762. */
  37763. bind() {
  37764. let targetObject = this.node;
  37765. const parsedPath = this.parsedPath;
  37766. const objectName = parsedPath.objectName;
  37767. const propertyName = parsedPath.propertyName;
  37768. let propertyIndex = parsedPath.propertyIndex;
  37769. if ( ! targetObject ) {
  37770. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37771. this.node = targetObject;
  37772. }
  37773. // set fail state so we can just 'return' on error
  37774. this.getValue = this._getValue_unavailable;
  37775. this.setValue = this._setValue_unavailable;
  37776. // ensure there is a value node
  37777. if ( ! targetObject ) {
  37778. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  37779. return;
  37780. }
  37781. if ( objectName ) {
  37782. let objectIndex = parsedPath.objectIndex;
  37783. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37784. switch ( objectName ) {
  37785. case 'materials':
  37786. if ( ! targetObject.material ) {
  37787. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37788. return;
  37789. }
  37790. if ( ! targetObject.material.materials ) {
  37791. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37792. return;
  37793. }
  37794. targetObject = targetObject.material.materials;
  37795. break;
  37796. case 'bones':
  37797. if ( ! targetObject.skeleton ) {
  37798. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37799. return;
  37800. }
  37801. // potential future optimization: skip this if propertyIndex is already an integer
  37802. // and convert the integer string to a true integer.
  37803. targetObject = targetObject.skeleton.bones;
  37804. // support resolving morphTarget names into indices.
  37805. for ( let i = 0; i < targetObject.length; i ++ ) {
  37806. if ( targetObject[ i ].name === objectIndex ) {
  37807. objectIndex = i;
  37808. break;
  37809. }
  37810. }
  37811. break;
  37812. case 'map':
  37813. if ( 'map' in targetObject ) {
  37814. targetObject = targetObject.map;
  37815. break;
  37816. }
  37817. if ( ! targetObject.material ) {
  37818. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37819. return;
  37820. }
  37821. if ( ! targetObject.material.map ) {
  37822. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37823. return;
  37824. }
  37825. targetObject = targetObject.material.map;
  37826. break;
  37827. default:
  37828. if ( targetObject[ objectName ] === undefined ) {
  37829. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  37830. return;
  37831. }
  37832. targetObject = targetObject[ objectName ];
  37833. }
  37834. if ( objectIndex !== undefined ) {
  37835. if ( targetObject[ objectIndex ] === undefined ) {
  37836. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37837. return;
  37838. }
  37839. targetObject = targetObject[ objectIndex ];
  37840. }
  37841. }
  37842. // resolve property
  37843. const nodeProperty = targetObject[ propertyName ];
  37844. if ( nodeProperty === undefined ) {
  37845. const nodeName = parsedPath.nodeName;
  37846. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  37847. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37848. return;
  37849. }
  37850. // determine versioning scheme
  37851. let versioning = this.Versioning.None;
  37852. this.targetObject = targetObject;
  37853. if ( targetObject.isMaterial === true ) {
  37854. versioning = this.Versioning.NeedsUpdate;
  37855. } else if ( targetObject.isObject3D === true ) {
  37856. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37857. }
  37858. // determine how the property gets bound
  37859. let bindingType = this.BindingType.Direct;
  37860. if ( propertyIndex !== undefined ) {
  37861. // access a sub element of the property array (only primitives are supported right now)
  37862. if ( propertyName === 'morphTargetInfluences' ) {
  37863. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37864. // support resolving morphTarget names into indices.
  37865. if ( ! targetObject.geometry ) {
  37866. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37867. return;
  37868. }
  37869. if ( ! targetObject.geometry.morphAttributes ) {
  37870. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37871. return;
  37872. }
  37873. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37874. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37875. }
  37876. }
  37877. bindingType = this.BindingType.ArrayElement;
  37878. this.resolvedProperty = nodeProperty;
  37879. this.propertyIndex = propertyIndex;
  37880. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37881. // must use copy for Object3D.Euler/Quaternion
  37882. bindingType = this.BindingType.HasFromToArray;
  37883. this.resolvedProperty = nodeProperty;
  37884. } else if ( Array.isArray( nodeProperty ) ) {
  37885. bindingType = this.BindingType.EntireArray;
  37886. this.resolvedProperty = nodeProperty;
  37887. } else {
  37888. this.propertyName = propertyName;
  37889. }
  37890. // select getter / setter
  37891. this.getValue = this.GetterByBindingType[ bindingType ];
  37892. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37893. }
  37894. /**
  37895. * Unbinds the property.
  37896. */
  37897. unbind() {
  37898. this.node = null;
  37899. // back to the prototype version of getValue / setValue
  37900. // note: avoiding to mutate the shape of 'this' via 'delete'
  37901. this.getValue = this._getValue_unbound;
  37902. this.setValue = this._setValue_unbound;
  37903. }
  37904. }
  37905. PropertyBinding.Composite = Composite;
  37906. PropertyBinding.prototype.BindingType = {
  37907. Direct: 0,
  37908. EntireArray: 1,
  37909. ArrayElement: 2,
  37910. HasFromToArray: 3
  37911. };
  37912. PropertyBinding.prototype.Versioning = {
  37913. None: 0,
  37914. NeedsUpdate: 1,
  37915. MatrixWorldNeedsUpdate: 2
  37916. };
  37917. PropertyBinding.prototype.GetterByBindingType = [
  37918. PropertyBinding.prototype._getValue_direct,
  37919. PropertyBinding.prototype._getValue_array,
  37920. PropertyBinding.prototype._getValue_arrayElement,
  37921. PropertyBinding.prototype._getValue_toArray,
  37922. ];
  37923. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37924. [
  37925. // Direct
  37926. PropertyBinding.prototype._setValue_direct,
  37927. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37928. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37929. ], [
  37930. // EntireArray
  37931. PropertyBinding.prototype._setValue_array,
  37932. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37933. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37934. ], [
  37935. // ArrayElement
  37936. PropertyBinding.prototype._setValue_arrayElement,
  37937. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37938. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37939. ], [
  37940. // HasToFromArray
  37941. PropertyBinding.prototype._setValue_fromArray,
  37942. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37943. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37944. ]
  37945. ];
  37946. /**
  37947. * A group of objects that receives a shared animation state.
  37948. *
  37949. * Usage:
  37950. *
  37951. * - Add objects you would otherwise pass as 'root' to the
  37952. * constructor or the .clipAction method of AnimationMixer.
  37953. * - Instead pass this object as 'root'.
  37954. * - You can also add and remove objects later when the mixer is running.
  37955. *
  37956. * Note:
  37957. *
  37958. * - Objects of this class appear as one object to the mixer,
  37959. * so cache control of the individual objects must be done on the group.
  37960. *
  37961. * Limitation:
  37962. *
  37963. * - The animated properties must be compatible among the all objects in the group.
  37964. * - A single property can either be controlled through a target group or directly, but not both.
  37965. */
  37966. class AnimationObjectGroup {
  37967. /**
  37968. * Constructs a new animation group.
  37969. *
  37970. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37971. */
  37972. constructor() {
  37973. /**
  37974. * This flag can be used for type testing.
  37975. *
  37976. * @type {boolean}
  37977. * @readonly
  37978. * @default true
  37979. */
  37980. this.isAnimationObjectGroup = true;
  37981. /**
  37982. * The UUID of the 3D object.
  37983. *
  37984. * @type {string}
  37985. * @readonly
  37986. */
  37987. this.uuid = generateUUID();
  37988. // cached objects followed by the active ones
  37989. this._objects = Array.prototype.slice.call( arguments );
  37990. this.nCachedObjects_ = 0; // threshold
  37991. // note: read by PropertyBinding.Composite
  37992. const indices = {};
  37993. this._indicesByUUID = indices; // for bookkeeping
  37994. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  37995. indices[ arguments[ i ].uuid ] = i;
  37996. }
  37997. this._paths = []; // inside: string
  37998. this._parsedPaths = []; // inside: { we don't care, here }
  37999. this._bindings = []; // inside: Array< PropertyBinding >
  38000. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38001. const scope = this;
  38002. this.stats = {
  38003. objects: {
  38004. get total() {
  38005. return scope._objects.length;
  38006. },
  38007. get inUse() {
  38008. return this.total - scope.nCachedObjects_;
  38009. }
  38010. },
  38011. get bindingsPerObject() {
  38012. return scope._bindings.length;
  38013. }
  38014. };
  38015. }
  38016. /**
  38017. * Adds an arbitrary number of objects to this animation group.
  38018. *
  38019. * @param {...Object3D} arguments - The 3D objects to add.
  38020. */
  38021. add() {
  38022. const objects = this._objects,
  38023. indicesByUUID = this._indicesByUUID,
  38024. paths = this._paths,
  38025. parsedPaths = this._parsedPaths,
  38026. bindings = this._bindings,
  38027. nBindings = bindings.length;
  38028. let knownObject = undefined,
  38029. nObjects = objects.length,
  38030. nCachedObjects = this.nCachedObjects_;
  38031. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38032. const object = arguments[ i ],
  38033. uuid = object.uuid;
  38034. let index = indicesByUUID[ uuid ];
  38035. if ( index === undefined ) {
  38036. // unknown object -> add it to the ACTIVE region
  38037. index = nObjects ++;
  38038. indicesByUUID[ uuid ] = index;
  38039. objects.push( object );
  38040. // accounting is done, now do the same for all bindings
  38041. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38042. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38043. }
  38044. } else if ( index < nCachedObjects ) {
  38045. knownObject = objects[ index ];
  38046. // move existing object to the ACTIVE region
  38047. const firstActiveIndex = -- nCachedObjects,
  38048. lastCachedObject = objects[ firstActiveIndex ];
  38049. indicesByUUID[ lastCachedObject.uuid ] = index;
  38050. objects[ index ] = lastCachedObject;
  38051. indicesByUUID[ uuid ] = firstActiveIndex;
  38052. objects[ firstActiveIndex ] = object;
  38053. // accounting is done, now do the same for all bindings
  38054. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38055. const bindingsForPath = bindings[ j ],
  38056. lastCached = bindingsForPath[ firstActiveIndex ];
  38057. let binding = bindingsForPath[ index ];
  38058. bindingsForPath[ index ] = lastCached;
  38059. if ( binding === undefined ) {
  38060. // since we do not bother to create new bindings
  38061. // for objects that are cached, the binding may
  38062. // or may not exist
  38063. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38064. }
  38065. bindingsForPath[ firstActiveIndex ] = binding;
  38066. }
  38067. } else if ( objects[ index ] !== knownObject ) {
  38068. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38069. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38070. } // else the object is already where we want it to be
  38071. } // for arguments
  38072. this.nCachedObjects_ = nCachedObjects;
  38073. }
  38074. /**
  38075. * Removes an arbitrary number of objects to this animation group
  38076. *
  38077. * @param {...Object3D} arguments - The 3D objects to remove.
  38078. */
  38079. remove() {
  38080. const objects = this._objects,
  38081. indicesByUUID = this._indicesByUUID,
  38082. bindings = this._bindings,
  38083. nBindings = bindings.length;
  38084. let nCachedObjects = this.nCachedObjects_;
  38085. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38086. const object = arguments[ i ],
  38087. uuid = object.uuid,
  38088. index = indicesByUUID[ uuid ];
  38089. if ( index !== undefined && index >= nCachedObjects ) {
  38090. // move existing object into the CACHED region
  38091. const lastCachedIndex = nCachedObjects ++,
  38092. firstActiveObject = objects[ lastCachedIndex ];
  38093. indicesByUUID[ firstActiveObject.uuid ] = index;
  38094. objects[ index ] = firstActiveObject;
  38095. indicesByUUID[ uuid ] = lastCachedIndex;
  38096. objects[ lastCachedIndex ] = object;
  38097. // accounting is done, now do the same for all bindings
  38098. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38099. const bindingsForPath = bindings[ j ],
  38100. firstActive = bindingsForPath[ lastCachedIndex ],
  38101. binding = bindingsForPath[ index ];
  38102. bindingsForPath[ index ] = firstActive;
  38103. bindingsForPath[ lastCachedIndex ] = binding;
  38104. }
  38105. }
  38106. } // for arguments
  38107. this.nCachedObjects_ = nCachedObjects;
  38108. }
  38109. /**
  38110. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38111. *
  38112. * @param {...Object3D} arguments - The 3D objects to uncache.
  38113. */
  38114. uncache() {
  38115. const objects = this._objects,
  38116. indicesByUUID = this._indicesByUUID,
  38117. bindings = this._bindings,
  38118. nBindings = bindings.length;
  38119. let nCachedObjects = this.nCachedObjects_,
  38120. nObjects = objects.length;
  38121. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38122. const object = arguments[ i ],
  38123. uuid = object.uuid,
  38124. index = indicesByUUID[ uuid ];
  38125. if ( index !== undefined ) {
  38126. delete indicesByUUID[ uuid ];
  38127. if ( index < nCachedObjects ) {
  38128. // object is cached, shrink the CACHED region
  38129. const firstActiveIndex = -- nCachedObjects,
  38130. lastCachedObject = objects[ firstActiveIndex ],
  38131. lastIndex = -- nObjects,
  38132. lastObject = objects[ lastIndex ];
  38133. // last cached object takes this object's place
  38134. indicesByUUID[ lastCachedObject.uuid ] = index;
  38135. objects[ index ] = lastCachedObject;
  38136. // last object goes to the activated slot and pop
  38137. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38138. objects[ firstActiveIndex ] = lastObject;
  38139. objects.pop();
  38140. // accounting is done, now do the same for all bindings
  38141. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38142. const bindingsForPath = bindings[ j ],
  38143. lastCached = bindingsForPath[ firstActiveIndex ],
  38144. last = bindingsForPath[ lastIndex ];
  38145. bindingsForPath[ index ] = lastCached;
  38146. bindingsForPath[ firstActiveIndex ] = last;
  38147. bindingsForPath.pop();
  38148. }
  38149. } else {
  38150. // object is active, just swap with the last and pop
  38151. const lastIndex = -- nObjects,
  38152. lastObject = objects[ lastIndex ];
  38153. if ( lastIndex > 0 ) {
  38154. indicesByUUID[ lastObject.uuid ] = index;
  38155. }
  38156. objects[ index ] = lastObject;
  38157. objects.pop();
  38158. // accounting is done, now do the same for all bindings
  38159. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38160. const bindingsForPath = bindings[ j ];
  38161. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38162. bindingsForPath.pop();
  38163. }
  38164. } // cached or active
  38165. } // if object is known
  38166. } // for arguments
  38167. this.nCachedObjects_ = nCachedObjects;
  38168. }
  38169. // Internal interface used by befriended PropertyBinding.Composite:
  38170. subscribe_( path, parsedPath ) {
  38171. // returns an array of bindings for the given path that is changed
  38172. // according to the contained objects in the group
  38173. const indicesByPath = this._bindingsIndicesByPath;
  38174. let index = indicesByPath[ path ];
  38175. const bindings = this._bindings;
  38176. if ( index !== undefined ) return bindings[ index ];
  38177. const paths = this._paths,
  38178. parsedPaths = this._parsedPaths,
  38179. objects = this._objects,
  38180. nObjects = objects.length,
  38181. nCachedObjects = this.nCachedObjects_,
  38182. bindingsForPath = new Array( nObjects );
  38183. index = bindings.length;
  38184. indicesByPath[ path ] = index;
  38185. paths.push( path );
  38186. parsedPaths.push( parsedPath );
  38187. bindings.push( bindingsForPath );
  38188. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38189. const object = objects[ i ];
  38190. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38191. }
  38192. return bindingsForPath;
  38193. }
  38194. unsubscribe_( path ) {
  38195. // tells the group to forget about a property path and no longer
  38196. // update the array previously obtained with 'subscribe_'
  38197. const indicesByPath = this._bindingsIndicesByPath,
  38198. index = indicesByPath[ path ];
  38199. if ( index !== undefined ) {
  38200. const paths = this._paths,
  38201. parsedPaths = this._parsedPaths,
  38202. bindings = this._bindings,
  38203. lastBindingsIndex = bindings.length - 1,
  38204. lastBindings = bindings[ lastBindingsIndex ],
  38205. lastBindingsPath = path[ lastBindingsIndex ];
  38206. indicesByPath[ lastBindingsPath ] = index;
  38207. bindings[ index ] = lastBindings;
  38208. bindings.pop();
  38209. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38210. parsedPaths.pop();
  38211. paths[ index ] = paths[ lastBindingsIndex ];
  38212. paths.pop();
  38213. }
  38214. }
  38215. }
  38216. /**
  38217. * An instance of `AnimationAction` schedules the playback of an animation which is
  38218. * stored in {@link AnimationClip}.
  38219. */
  38220. class AnimationAction {
  38221. /**
  38222. * Constructs a new animation action.
  38223. *
  38224. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38225. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38226. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38227. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38228. */
  38229. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38230. this._mixer = mixer;
  38231. this._clip = clip;
  38232. this._localRoot = localRoot;
  38233. /**
  38234. * Defines how the animation is blended/combined when two or more animations
  38235. * are simultaneously played.
  38236. *
  38237. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38238. */
  38239. this.blendMode = blendMode;
  38240. const tracks = clip.tracks,
  38241. nTracks = tracks.length,
  38242. interpolants = new Array( nTracks );
  38243. const interpolantSettings = {
  38244. endingStart: ZeroCurvatureEnding,
  38245. endingEnd: ZeroCurvatureEnding
  38246. };
  38247. for ( let i = 0; i !== nTracks; ++ i ) {
  38248. const interpolant = tracks[ i ].createInterpolant( null );
  38249. interpolants[ i ] = interpolant;
  38250. interpolant.settings = interpolantSettings;
  38251. }
  38252. this._interpolantSettings = interpolantSettings;
  38253. this._interpolants = interpolants; // bound by the mixer
  38254. // inside: PropertyMixer (managed by the mixer)
  38255. this._propertyBindings = new Array( nTracks );
  38256. this._cacheIndex = null; // for the memory manager
  38257. this._byClipCacheIndex = null; // for the memory manager
  38258. this._timeScaleInterpolant = null;
  38259. this._weightInterpolant = null;
  38260. /**
  38261. * The loop mode, set via {@link AnimationAction#setLoop}.
  38262. *
  38263. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38264. * @default LoopRepeat
  38265. */
  38266. this.loop = LoopRepeat;
  38267. this._loopCount = -1;
  38268. // global mixer time when the action is to be started
  38269. // it's set back to 'null' upon start of the action
  38270. this._startTime = null;
  38271. /**
  38272. * The local time of this action (in seconds, starting with `0`).
  38273. *
  38274. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38275. * loop state).
  38276. *
  38277. * @type {number}
  38278. * @default Infinity
  38279. */
  38280. this.time = 0;
  38281. /**
  38282. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38283. * animation to pause. Negative values cause the animation to play backwards.
  38284. *
  38285. * @type {number}
  38286. * @default 1
  38287. */
  38288. this.timeScale = 1;
  38289. this._effectiveTimeScale = 1;
  38290. /**
  38291. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38292. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38293. * several actions.
  38294. *
  38295. * @type {number}
  38296. * @default 1
  38297. */
  38298. this.weight = 1;
  38299. this._effectiveWeight = 1;
  38300. /**
  38301. * The number of repetitions of the performed clip over the course of this action.
  38302. * Can be set via {@link AnimationAction#setLoop}.
  38303. *
  38304. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38305. * `THREE:LoopOnce`.
  38306. *
  38307. * @type {number}
  38308. * @default Infinity
  38309. */
  38310. this.repetitions = Infinity;
  38311. /**
  38312. * If set to `true`, the playback of the action is paused.
  38313. *
  38314. * @type {boolean}
  38315. * @default false
  38316. */
  38317. this.paused = false;
  38318. /**
  38319. * If set to `false`, the action is disabled so it has no impact.
  38320. *
  38321. * When the action is re-enabled, the animation continues from its current
  38322. * time (setting `enabled` to `false` doesn't reset the action).
  38323. *
  38324. * @type {boolean}
  38325. * @default true
  38326. */
  38327. this.enabled = true;
  38328. /**
  38329. * If set to true the animation will automatically be paused on its last frame.
  38330. *
  38331. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38332. * to `false` when the last loop of the action has finished, so that this action has
  38333. * no further impact.
  38334. *
  38335. * Note: This member has no impact if the action is interrupted (it
  38336. * has only an effect if its last loop has really finished).
  38337. *
  38338. * @type {boolean}
  38339. * @default false
  38340. */
  38341. this.clampWhenFinished = false;
  38342. /**
  38343. * Enables smooth interpolation without separate clips for start, loop and end.
  38344. *
  38345. * @type {boolean}
  38346. * @default true
  38347. */
  38348. this.zeroSlopeAtStart = true;
  38349. /**
  38350. * Enables smooth interpolation without separate clips for start, loop and end.
  38351. *
  38352. * @type {boolean}
  38353. * @default true
  38354. */
  38355. this.zeroSlopeAtEnd = true;
  38356. }
  38357. /**
  38358. * Starts the playback of the animation.
  38359. *
  38360. * @return {AnimationAction} A reference to this animation action.
  38361. */
  38362. play() {
  38363. this._mixer._activateAction( this );
  38364. return this;
  38365. }
  38366. /**
  38367. * Stops the playback of the animation.
  38368. *
  38369. * @return {AnimationAction} A reference to this animation action.
  38370. */
  38371. stop() {
  38372. this._mixer._deactivateAction( this );
  38373. return this.reset();
  38374. }
  38375. /**
  38376. * Resets the playback of the animation.
  38377. *
  38378. * @return {AnimationAction} A reference to this animation action.
  38379. */
  38380. reset() {
  38381. this.paused = false;
  38382. this.enabled = true;
  38383. this.time = 0; // restart clip
  38384. this._loopCount = -1;// forget previous loops
  38385. this._startTime = null;// forget scheduling
  38386. return this.stopFading().stopWarping();
  38387. }
  38388. /**
  38389. * Returns `true` if the animation is running.
  38390. *
  38391. * @return {boolean} Whether the animation is running or not.
  38392. */
  38393. isRunning() {
  38394. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38395. this._startTime === null && this._mixer._isActiveAction( this );
  38396. }
  38397. /**
  38398. * Returns `true` when {@link AnimationAction#play} has been called.
  38399. *
  38400. * @return {boolean} Whether the animation is scheduled or not.
  38401. */
  38402. isScheduled() {
  38403. return this._mixer._isActiveAction( this );
  38404. }
  38405. /**
  38406. * Defines the time when the animation should start.
  38407. *
  38408. * @param {number} time - The start time in seconds.
  38409. * @return {AnimationAction} A reference to this animation action.
  38410. */
  38411. startAt( time ) {
  38412. this._startTime = time;
  38413. return this;
  38414. }
  38415. /**
  38416. * Configures the loop settings for this action.
  38417. *
  38418. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38419. * @param {number} repetitions - The number of repetitions.
  38420. * @return {AnimationAction} A reference to this animation action.
  38421. */
  38422. setLoop( mode, repetitions ) {
  38423. this.loop = mode;
  38424. this.repetitions = repetitions;
  38425. return this;
  38426. }
  38427. /**
  38428. * Sets the effective weight of this action.
  38429. *
  38430. * An action has no effect and thus an effective weight of zero when the
  38431. * action is disabled.
  38432. *
  38433. * @param {number} weight - The weight to set.
  38434. * @return {AnimationAction} A reference to this animation action.
  38435. */
  38436. setEffectiveWeight( weight ) {
  38437. this.weight = weight;
  38438. // note: same logic as when updated at runtime
  38439. this._effectiveWeight = this.enabled ? weight : 0;
  38440. return this.stopFading();
  38441. }
  38442. /**
  38443. * Returns the effective weight of this action.
  38444. *
  38445. * @return {number} The effective weight.
  38446. */
  38447. getEffectiveWeight() {
  38448. return this._effectiveWeight;
  38449. }
  38450. /**
  38451. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38452. * within the passed time interval.
  38453. *
  38454. * @param {number} duration - The duration of the fade.
  38455. * @return {AnimationAction} A reference to this animation action.
  38456. */
  38457. fadeIn( duration ) {
  38458. return this._scheduleFading( duration, 0, 1 );
  38459. }
  38460. /**
  38461. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38462. * within the passed time interval.
  38463. *
  38464. * @param {number} duration - The duration of the fade.
  38465. * @return {AnimationAction} A reference to this animation action.
  38466. */
  38467. fadeOut( duration ) {
  38468. return this._scheduleFading( duration, 1, 0 );
  38469. }
  38470. /**
  38471. * Causes this action to fade in and the given action to fade out,
  38472. * within the passed time interval.
  38473. *
  38474. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38475. * @param {number} duration - The duration of the fade.
  38476. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38477. * @return {AnimationAction} A reference to this animation action.
  38478. */
  38479. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38480. fadeOutAction.fadeOut( duration );
  38481. this.fadeIn( duration );
  38482. if ( warp === true ) {
  38483. const fadeInDuration = this._clip.duration,
  38484. fadeOutDuration = fadeOutAction._clip.duration,
  38485. startEndRatio = fadeOutDuration / fadeInDuration,
  38486. endStartRatio = fadeInDuration / fadeOutDuration;
  38487. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38488. this.warp( endStartRatio, 1.0, duration );
  38489. }
  38490. return this;
  38491. }
  38492. /**
  38493. * Causes this action to fade out and the given action to fade in,
  38494. * within the passed time interval.
  38495. *
  38496. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38497. * @param {number} duration - The duration of the fade.
  38498. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38499. * @return {AnimationAction} A reference to this animation action.
  38500. */
  38501. crossFadeTo( fadeInAction, duration, warp = false ) {
  38502. return fadeInAction.crossFadeFrom( this, duration, warp );
  38503. }
  38504. /**
  38505. * Stops any fading which is applied to this action.
  38506. *
  38507. * @return {AnimationAction} A reference to this animation action.
  38508. */
  38509. stopFading() {
  38510. const weightInterpolant = this._weightInterpolant;
  38511. if ( weightInterpolant !== null ) {
  38512. this._weightInterpolant = null;
  38513. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38514. }
  38515. return this;
  38516. }
  38517. /**
  38518. * Sets the effective time scale of this action.
  38519. *
  38520. * An action has no effect and thus an effective time scale of zero when the
  38521. * action is paused.
  38522. *
  38523. * @param {number} timeScale - The time scale to set.
  38524. * @return {AnimationAction} A reference to this animation action.
  38525. */
  38526. setEffectiveTimeScale( timeScale ) {
  38527. this.timeScale = timeScale;
  38528. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38529. return this.stopWarping();
  38530. }
  38531. /**
  38532. * Returns the effective time scale of this action.
  38533. *
  38534. * @return {number} The effective time scale.
  38535. */
  38536. getEffectiveTimeScale() {
  38537. return this._effectiveTimeScale;
  38538. }
  38539. /**
  38540. * Sets the duration for a single loop of this action.
  38541. *
  38542. * @param {number} duration - The duration to set.
  38543. * @return {AnimationAction} A reference to this animation action.
  38544. */
  38545. setDuration( duration ) {
  38546. this.timeScale = this._clip.duration / duration;
  38547. return this.stopWarping();
  38548. }
  38549. /**
  38550. * Synchronizes this action with the passed other action.
  38551. *
  38552. * @param {AnimationAction} action - The action to sync with.
  38553. * @return {AnimationAction} A reference to this animation action.
  38554. */
  38555. syncWith( action ) {
  38556. this.time = action.time;
  38557. this.timeScale = action.timeScale;
  38558. return this.stopWarping();
  38559. }
  38560. /**
  38561. * Decelerates this animation's speed to `0` within the passed time interval.
  38562. *
  38563. * @param {number} duration - The duration.
  38564. * @return {AnimationAction} A reference to this animation action.
  38565. */
  38566. halt( duration ) {
  38567. return this.warp( this._effectiveTimeScale, 0, duration );
  38568. }
  38569. /**
  38570. * Changes the playback speed, within the passed time interval, by modifying
  38571. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38572. * `endTimeScale`.
  38573. *
  38574. * @param {number} startTimeScale - The start time scale.
  38575. * @param {number} endTimeScale - The end time scale.
  38576. * @param {number} duration - The duration.
  38577. * @return {AnimationAction} A reference to this animation action.
  38578. */
  38579. warp( startTimeScale, endTimeScale, duration ) {
  38580. const mixer = this._mixer,
  38581. now = mixer.time,
  38582. timeScale = this.timeScale;
  38583. let interpolant = this._timeScaleInterpolant;
  38584. if ( interpolant === null ) {
  38585. interpolant = mixer._lendControlInterpolant();
  38586. this._timeScaleInterpolant = interpolant;
  38587. }
  38588. const times = interpolant.parameterPositions,
  38589. values = interpolant.sampleValues;
  38590. times[ 0 ] = now;
  38591. times[ 1 ] = now + duration;
  38592. values[ 0 ] = startTimeScale / timeScale;
  38593. values[ 1 ] = endTimeScale / timeScale;
  38594. return this;
  38595. }
  38596. /**
  38597. * Stops any scheduled warping which is applied to this action.
  38598. *
  38599. * @return {AnimationAction} A reference to this animation action.
  38600. */
  38601. stopWarping() {
  38602. const timeScaleInterpolant = this._timeScaleInterpolant;
  38603. if ( timeScaleInterpolant !== null ) {
  38604. this._timeScaleInterpolant = null;
  38605. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38606. }
  38607. return this;
  38608. }
  38609. /**
  38610. * Returns the animation mixer of this animation action.
  38611. *
  38612. * @return {AnimationMixer} The animation mixer.
  38613. */
  38614. getMixer() {
  38615. return this._mixer;
  38616. }
  38617. /**
  38618. * Returns the animation clip of this animation action.
  38619. *
  38620. * @return {AnimationClip} The animation clip.
  38621. */
  38622. getClip() {
  38623. return this._clip;
  38624. }
  38625. /**
  38626. * Returns the root object of this animation action.
  38627. *
  38628. * @return {Object3D} The root object.
  38629. */
  38630. getRoot() {
  38631. return this._localRoot || this._mixer._root;
  38632. }
  38633. // Interna
  38634. _update( time, deltaTime, timeDirection, accuIndex ) {
  38635. // called by the mixer
  38636. if ( ! this.enabled ) {
  38637. // call ._updateWeight() to update ._effectiveWeight
  38638. this._updateWeight( time );
  38639. return;
  38640. }
  38641. const startTime = this._startTime;
  38642. if ( startTime !== null ) {
  38643. // check for scheduled start of action
  38644. const timeRunning = ( time - startTime ) * timeDirection;
  38645. if ( timeRunning < 0 || timeDirection === 0 ) {
  38646. deltaTime = 0;
  38647. } else {
  38648. this._startTime = null; // unschedule
  38649. deltaTime = timeDirection * timeRunning;
  38650. }
  38651. }
  38652. // apply time scale and advance time
  38653. deltaTime *= this._updateTimeScale( time );
  38654. const clipTime = this._updateTime( deltaTime );
  38655. // note: _updateTime may disable the action resulting in
  38656. // an effective weight of 0
  38657. const weight = this._updateWeight( time );
  38658. if ( weight > 0 ) {
  38659. const interpolants = this._interpolants;
  38660. const propertyMixers = this._propertyBindings;
  38661. switch ( this.blendMode ) {
  38662. case AdditiveAnimationBlendMode:
  38663. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38664. interpolants[ j ].evaluate( clipTime );
  38665. propertyMixers[ j ].accumulateAdditive( weight );
  38666. }
  38667. break;
  38668. case NormalAnimationBlendMode:
  38669. default:
  38670. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38671. interpolants[ j ].evaluate( clipTime );
  38672. propertyMixers[ j ].accumulate( accuIndex, weight );
  38673. }
  38674. }
  38675. }
  38676. }
  38677. _updateWeight( time ) {
  38678. let weight = 0;
  38679. if ( this.enabled ) {
  38680. weight = this.weight;
  38681. const interpolant = this._weightInterpolant;
  38682. if ( interpolant !== null ) {
  38683. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38684. weight *= interpolantValue;
  38685. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38686. this.stopFading();
  38687. if ( interpolantValue === 0 ) {
  38688. // faded out, disable
  38689. this.enabled = false;
  38690. }
  38691. }
  38692. }
  38693. }
  38694. this._effectiveWeight = weight;
  38695. return weight;
  38696. }
  38697. _updateTimeScale( time ) {
  38698. let timeScale = 0;
  38699. if ( ! this.paused ) {
  38700. timeScale = this.timeScale;
  38701. const interpolant = this._timeScaleInterpolant;
  38702. if ( interpolant !== null ) {
  38703. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38704. timeScale *= interpolantValue;
  38705. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38706. this.stopWarping();
  38707. if ( timeScale === 0 ) {
  38708. // motion has halted, pause
  38709. this.paused = true;
  38710. } else {
  38711. // warp done - apply final time scale
  38712. this.timeScale = timeScale;
  38713. }
  38714. }
  38715. }
  38716. }
  38717. this._effectiveTimeScale = timeScale;
  38718. return timeScale;
  38719. }
  38720. _updateTime( deltaTime ) {
  38721. const duration = this._clip.duration;
  38722. const loop = this.loop;
  38723. let time = this.time + deltaTime;
  38724. let loopCount = this._loopCount;
  38725. const pingPong = ( loop === LoopPingPong );
  38726. if ( deltaTime === 0 ) {
  38727. if ( loopCount === -1 ) return time;
  38728. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38729. }
  38730. if ( loop === LoopOnce ) {
  38731. if ( loopCount === -1 ) {
  38732. // just started
  38733. this._loopCount = 0;
  38734. this._setEndings( true, true, false );
  38735. }
  38736. handle_stop: {
  38737. if ( time >= duration ) {
  38738. time = duration;
  38739. } else if ( time < 0 ) {
  38740. time = 0;
  38741. } else {
  38742. this.time = time;
  38743. break handle_stop;
  38744. }
  38745. if ( this.clampWhenFinished ) this.paused = true;
  38746. else this.enabled = false;
  38747. this.time = time;
  38748. this._mixer.dispatchEvent( {
  38749. type: 'finished', action: this,
  38750. direction: deltaTime < 0 ? -1 : 1
  38751. } );
  38752. }
  38753. } else { // repetitive Repeat or PingPong
  38754. if ( loopCount === -1 ) {
  38755. // just started
  38756. if ( deltaTime >= 0 ) {
  38757. loopCount = 0;
  38758. this._setEndings( true, this.repetitions === 0, pingPong );
  38759. } else {
  38760. // when looping in reverse direction, the initial
  38761. // transition through zero counts as a repetition,
  38762. // so leave loopCount at -1
  38763. this._setEndings( this.repetitions === 0, true, pingPong );
  38764. }
  38765. }
  38766. if ( time >= duration || time < 0 ) {
  38767. // wrap around
  38768. const loopDelta = Math.floor( time / duration ); // signed
  38769. time -= duration * loopDelta;
  38770. loopCount += Math.abs( loopDelta );
  38771. const pending = this.repetitions - loopCount;
  38772. if ( pending <= 0 ) {
  38773. // have to stop (switch state, clamp time, fire event)
  38774. if ( this.clampWhenFinished ) this.paused = true;
  38775. else this.enabled = false;
  38776. time = deltaTime > 0 ? duration : 0;
  38777. this.time = time;
  38778. this._mixer.dispatchEvent( {
  38779. type: 'finished', action: this,
  38780. direction: deltaTime > 0 ? 1 : -1
  38781. } );
  38782. } else {
  38783. // keep running
  38784. if ( pending === 1 ) {
  38785. // entering the last round
  38786. const atStart = deltaTime < 0;
  38787. this._setEndings( atStart, ! atStart, pingPong );
  38788. } else {
  38789. this._setEndings( false, false, pingPong );
  38790. }
  38791. this._loopCount = loopCount;
  38792. this.time = time;
  38793. this._mixer.dispatchEvent( {
  38794. type: 'loop', action: this, loopDelta: loopDelta
  38795. } );
  38796. }
  38797. } else {
  38798. this.time = time;
  38799. }
  38800. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38801. // invert time for the "pong round"
  38802. return duration - time;
  38803. }
  38804. }
  38805. return time;
  38806. }
  38807. _setEndings( atStart, atEnd, pingPong ) {
  38808. const settings = this._interpolantSettings;
  38809. if ( pingPong ) {
  38810. settings.endingStart = ZeroSlopeEnding;
  38811. settings.endingEnd = ZeroSlopeEnding;
  38812. } else {
  38813. // assuming for LoopOnce atStart == atEnd == true
  38814. if ( atStart ) {
  38815. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38816. } else {
  38817. settings.endingStart = WrapAroundEnding;
  38818. }
  38819. if ( atEnd ) {
  38820. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38821. } else {
  38822. settings.endingEnd = WrapAroundEnding;
  38823. }
  38824. }
  38825. }
  38826. _scheduleFading( duration, weightNow, weightThen ) {
  38827. const mixer = this._mixer, now = mixer.time;
  38828. let interpolant = this._weightInterpolant;
  38829. if ( interpolant === null ) {
  38830. interpolant = mixer._lendControlInterpolant();
  38831. this._weightInterpolant = interpolant;
  38832. }
  38833. const times = interpolant.parameterPositions,
  38834. values = interpolant.sampleValues;
  38835. times[ 0 ] = now;
  38836. values[ 0 ] = weightNow;
  38837. times[ 1 ] = now + duration;
  38838. values[ 1 ] = weightThen;
  38839. return this;
  38840. }
  38841. }
  38842. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38843. /**
  38844. * `AnimationMixer` is a player for animations on a particular object in
  38845. * the scene. When multiple objects in the scene are animated independently,
  38846. * one `AnimationMixer` may be used for each object.
  38847. */
  38848. class AnimationMixer extends EventDispatcher {
  38849. /**
  38850. * Constructs a new animation mixer.
  38851. *
  38852. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38853. */
  38854. constructor( root ) {
  38855. super();
  38856. this._root = root;
  38857. this._initMemoryManager();
  38858. this._accuIndex = 0;
  38859. /**
  38860. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38861. *
  38862. * @type {number}
  38863. * @default 0
  38864. */
  38865. this.time = 0;
  38866. /**
  38867. * A scaling factor for the global time.
  38868. *
  38869. * Note: Setting this member to `0` and later back to `1` is a
  38870. * possibility to pause/unpause all actions that are controlled by this
  38871. * mixer.
  38872. *
  38873. * @type {number}
  38874. * @default 1
  38875. */
  38876. this.timeScale = 1.0;
  38877. }
  38878. _bindAction( action, prototypeAction ) {
  38879. const root = action._localRoot || this._root,
  38880. tracks = action._clip.tracks,
  38881. nTracks = tracks.length,
  38882. bindings = action._propertyBindings,
  38883. interpolants = action._interpolants,
  38884. rootUuid = root.uuid,
  38885. bindingsByRoot = this._bindingsByRootAndName;
  38886. let bindingsByName = bindingsByRoot[ rootUuid ];
  38887. if ( bindingsByName === undefined ) {
  38888. bindingsByName = {};
  38889. bindingsByRoot[ rootUuid ] = bindingsByName;
  38890. }
  38891. for ( let i = 0; i !== nTracks; ++ i ) {
  38892. const track = tracks[ i ],
  38893. trackName = track.name;
  38894. let binding = bindingsByName[ trackName ];
  38895. if ( binding !== undefined ) {
  38896. ++ binding.referenceCount;
  38897. bindings[ i ] = binding;
  38898. } else {
  38899. binding = bindings[ i ];
  38900. if ( binding !== undefined ) {
  38901. // existing binding, make sure the cache knows
  38902. if ( binding._cacheIndex === null ) {
  38903. ++ binding.referenceCount;
  38904. this._addInactiveBinding( binding, rootUuid, trackName );
  38905. }
  38906. continue;
  38907. }
  38908. const path = prototypeAction && prototypeAction.
  38909. _propertyBindings[ i ].binding.parsedPath;
  38910. binding = new PropertyMixer(
  38911. PropertyBinding.create( root, trackName, path ),
  38912. track.ValueTypeName, track.getValueSize() );
  38913. ++ binding.referenceCount;
  38914. this._addInactiveBinding( binding, rootUuid, trackName );
  38915. bindings[ i ] = binding;
  38916. }
  38917. interpolants[ i ].resultBuffer = binding.buffer;
  38918. }
  38919. }
  38920. _activateAction( action ) {
  38921. if ( ! this._isActiveAction( action ) ) {
  38922. if ( action._cacheIndex === null ) {
  38923. // this action has been forgotten by the cache, but the user
  38924. // appears to be still using it -> rebind
  38925. const rootUuid = ( action._localRoot || this._root ).uuid,
  38926. clipUuid = action._clip.uuid,
  38927. actionsForClip = this._actionsByClip[ clipUuid ];
  38928. this._bindAction( action,
  38929. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38930. this._addInactiveAction( action, clipUuid, rootUuid );
  38931. }
  38932. const bindings = action._propertyBindings;
  38933. // increment reference counts / sort out state
  38934. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38935. const binding = bindings[ i ];
  38936. if ( binding.useCount ++ === 0 ) {
  38937. this._lendBinding( binding );
  38938. binding.saveOriginalState();
  38939. }
  38940. }
  38941. this._lendAction( action );
  38942. }
  38943. }
  38944. _deactivateAction( action ) {
  38945. if ( this._isActiveAction( action ) ) {
  38946. const bindings = action._propertyBindings;
  38947. // decrement reference counts / sort out state
  38948. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38949. const binding = bindings[ i ];
  38950. if ( -- binding.useCount === 0 ) {
  38951. binding.restoreOriginalState();
  38952. this._takeBackBinding( binding );
  38953. }
  38954. }
  38955. this._takeBackAction( action );
  38956. }
  38957. }
  38958. // Memory manager
  38959. _initMemoryManager() {
  38960. this._actions = []; // 'nActiveActions' followed by inactive ones
  38961. this._nActiveActions = 0;
  38962. this._actionsByClip = {};
  38963. // inside:
  38964. // {
  38965. // knownActions: Array< AnimationAction > - used as prototypes
  38966. // actionByRoot: AnimationAction - lookup
  38967. // }
  38968. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38969. this._nActiveBindings = 0;
  38970. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38971. this._controlInterpolants = []; // same game as above
  38972. this._nActiveControlInterpolants = 0;
  38973. const scope = this;
  38974. this.stats = {
  38975. actions: {
  38976. get total() {
  38977. return scope._actions.length;
  38978. },
  38979. get inUse() {
  38980. return scope._nActiveActions;
  38981. }
  38982. },
  38983. bindings: {
  38984. get total() {
  38985. return scope._bindings.length;
  38986. },
  38987. get inUse() {
  38988. return scope._nActiveBindings;
  38989. }
  38990. },
  38991. controlInterpolants: {
  38992. get total() {
  38993. return scope._controlInterpolants.length;
  38994. },
  38995. get inUse() {
  38996. return scope._nActiveControlInterpolants;
  38997. }
  38998. }
  38999. };
  39000. }
  39001. // Memory management for AnimationAction objects
  39002. _isActiveAction( action ) {
  39003. const index = action._cacheIndex;
  39004. return index !== null && index < this._nActiveActions;
  39005. }
  39006. _addInactiveAction( action, clipUuid, rootUuid ) {
  39007. const actions = this._actions,
  39008. actionsByClip = this._actionsByClip;
  39009. let actionsForClip = actionsByClip[ clipUuid ];
  39010. if ( actionsForClip === undefined ) {
  39011. actionsForClip = {
  39012. knownActions: [ action ],
  39013. actionByRoot: {}
  39014. };
  39015. action._byClipCacheIndex = 0;
  39016. actionsByClip[ clipUuid ] = actionsForClip;
  39017. } else {
  39018. const knownActions = actionsForClip.knownActions;
  39019. action._byClipCacheIndex = knownActions.length;
  39020. knownActions.push( action );
  39021. }
  39022. action._cacheIndex = actions.length;
  39023. actions.push( action );
  39024. actionsForClip.actionByRoot[ rootUuid ] = action;
  39025. }
  39026. _removeInactiveAction( action ) {
  39027. const actions = this._actions,
  39028. lastInactiveAction = actions[ actions.length - 1 ],
  39029. cacheIndex = action._cacheIndex;
  39030. lastInactiveAction._cacheIndex = cacheIndex;
  39031. actions[ cacheIndex ] = lastInactiveAction;
  39032. actions.pop();
  39033. action._cacheIndex = null;
  39034. const clipUuid = action._clip.uuid,
  39035. actionsByClip = this._actionsByClip,
  39036. actionsForClip = actionsByClip[ clipUuid ],
  39037. knownActionsForClip = actionsForClip.knownActions,
  39038. lastKnownAction =
  39039. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39040. byClipCacheIndex = action._byClipCacheIndex;
  39041. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39042. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39043. knownActionsForClip.pop();
  39044. action._byClipCacheIndex = null;
  39045. const actionByRoot = actionsForClip.actionByRoot,
  39046. rootUuid = ( action._localRoot || this._root ).uuid;
  39047. delete actionByRoot[ rootUuid ];
  39048. if ( knownActionsForClip.length === 0 ) {
  39049. delete actionsByClip[ clipUuid ];
  39050. }
  39051. this._removeInactiveBindingsForAction( action );
  39052. }
  39053. _removeInactiveBindingsForAction( action ) {
  39054. const bindings = action._propertyBindings;
  39055. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39056. const binding = bindings[ i ];
  39057. if ( -- binding.referenceCount === 0 ) {
  39058. this._removeInactiveBinding( binding );
  39059. }
  39060. }
  39061. }
  39062. _lendAction( action ) {
  39063. // [ active actions | inactive actions ]
  39064. // [ active actions >| inactive actions ]
  39065. // s a
  39066. // <-swap->
  39067. // a s
  39068. const actions = this._actions,
  39069. prevIndex = action._cacheIndex,
  39070. lastActiveIndex = this._nActiveActions ++,
  39071. firstInactiveAction = actions[ lastActiveIndex ];
  39072. action._cacheIndex = lastActiveIndex;
  39073. actions[ lastActiveIndex ] = action;
  39074. firstInactiveAction._cacheIndex = prevIndex;
  39075. actions[ prevIndex ] = firstInactiveAction;
  39076. }
  39077. _takeBackAction( action ) {
  39078. // [ active actions | inactive actions ]
  39079. // [ active actions |< inactive actions ]
  39080. // a s
  39081. // <-swap->
  39082. // s a
  39083. const actions = this._actions,
  39084. prevIndex = action._cacheIndex,
  39085. firstInactiveIndex = -- this._nActiveActions,
  39086. lastActiveAction = actions[ firstInactiveIndex ];
  39087. action._cacheIndex = firstInactiveIndex;
  39088. actions[ firstInactiveIndex ] = action;
  39089. lastActiveAction._cacheIndex = prevIndex;
  39090. actions[ prevIndex ] = lastActiveAction;
  39091. }
  39092. // Memory management for PropertyMixer objects
  39093. _addInactiveBinding( binding, rootUuid, trackName ) {
  39094. const bindingsByRoot = this._bindingsByRootAndName,
  39095. bindings = this._bindings;
  39096. let bindingByName = bindingsByRoot[ rootUuid ];
  39097. if ( bindingByName === undefined ) {
  39098. bindingByName = {};
  39099. bindingsByRoot[ rootUuid ] = bindingByName;
  39100. }
  39101. bindingByName[ trackName ] = binding;
  39102. binding._cacheIndex = bindings.length;
  39103. bindings.push( binding );
  39104. }
  39105. _removeInactiveBinding( binding ) {
  39106. const bindings = this._bindings,
  39107. propBinding = binding.binding,
  39108. rootUuid = propBinding.rootNode.uuid,
  39109. trackName = propBinding.path,
  39110. bindingsByRoot = this._bindingsByRootAndName,
  39111. bindingByName = bindingsByRoot[ rootUuid ],
  39112. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39113. cacheIndex = binding._cacheIndex;
  39114. lastInactiveBinding._cacheIndex = cacheIndex;
  39115. bindings[ cacheIndex ] = lastInactiveBinding;
  39116. bindings.pop();
  39117. delete bindingByName[ trackName ];
  39118. if ( Object.keys( bindingByName ).length === 0 ) {
  39119. delete bindingsByRoot[ rootUuid ];
  39120. }
  39121. }
  39122. _lendBinding( binding ) {
  39123. const bindings = this._bindings,
  39124. prevIndex = binding._cacheIndex,
  39125. lastActiveIndex = this._nActiveBindings ++,
  39126. firstInactiveBinding = bindings[ lastActiveIndex ];
  39127. binding._cacheIndex = lastActiveIndex;
  39128. bindings[ lastActiveIndex ] = binding;
  39129. firstInactiveBinding._cacheIndex = prevIndex;
  39130. bindings[ prevIndex ] = firstInactiveBinding;
  39131. }
  39132. _takeBackBinding( binding ) {
  39133. const bindings = this._bindings,
  39134. prevIndex = binding._cacheIndex,
  39135. firstInactiveIndex = -- this._nActiveBindings,
  39136. lastActiveBinding = bindings[ firstInactiveIndex ];
  39137. binding._cacheIndex = firstInactiveIndex;
  39138. bindings[ firstInactiveIndex ] = binding;
  39139. lastActiveBinding._cacheIndex = prevIndex;
  39140. bindings[ prevIndex ] = lastActiveBinding;
  39141. }
  39142. // Memory management of Interpolants for weight and time scale
  39143. _lendControlInterpolant() {
  39144. const interpolants = this._controlInterpolants,
  39145. lastActiveIndex = this._nActiveControlInterpolants ++;
  39146. let interpolant = interpolants[ lastActiveIndex ];
  39147. if ( interpolant === undefined ) {
  39148. interpolant = new LinearInterpolant(
  39149. new Float32Array( 2 ), new Float32Array( 2 ),
  39150. 1, _controlInterpolantsResultBuffer );
  39151. interpolant.__cacheIndex = lastActiveIndex;
  39152. interpolants[ lastActiveIndex ] = interpolant;
  39153. }
  39154. return interpolant;
  39155. }
  39156. _takeBackControlInterpolant( interpolant ) {
  39157. const interpolants = this._controlInterpolants,
  39158. prevIndex = interpolant.__cacheIndex,
  39159. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39160. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39161. interpolant.__cacheIndex = firstInactiveIndex;
  39162. interpolants[ firstInactiveIndex ] = interpolant;
  39163. lastActiveInterpolant.__cacheIndex = prevIndex;
  39164. interpolants[ prevIndex ] = lastActiveInterpolant;
  39165. }
  39166. /**
  39167. * Returns an instance of {@link AnimationAction} for the passed clip.
  39168. *
  39169. * If an action fitting the clip and root parameters doesn't yet exist, it
  39170. * will be created by this method. Calling this method several times with the
  39171. * same clip and root parameters always returns the same action.
  39172. *
  39173. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39174. * @param {Object3D} [optionalRoot] - An alternative root object.
  39175. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39176. * @return {?AnimationAction} The animation action.
  39177. */
  39178. clipAction( clip, optionalRoot, blendMode ) {
  39179. const root = optionalRoot || this._root,
  39180. rootUuid = root.uuid;
  39181. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39182. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39183. const actionsForClip = this._actionsByClip[ clipUuid ];
  39184. let prototypeAction = null;
  39185. if ( blendMode === undefined ) {
  39186. if ( clipObject !== null ) {
  39187. blendMode = clipObject.blendMode;
  39188. } else {
  39189. blendMode = NormalAnimationBlendMode;
  39190. }
  39191. }
  39192. if ( actionsForClip !== undefined ) {
  39193. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39194. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39195. return existingAction;
  39196. }
  39197. // we know the clip, so we don't have to parse all
  39198. // the bindings again but can just copy
  39199. prototypeAction = actionsForClip.knownActions[ 0 ];
  39200. // also, take the clip from the prototype action
  39201. if ( clipObject === null )
  39202. clipObject = prototypeAction._clip;
  39203. }
  39204. // clip must be known when specified via string
  39205. if ( clipObject === null ) return null;
  39206. // allocate all resources required to run it
  39207. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39208. this._bindAction( newAction, prototypeAction );
  39209. // and make the action known to the memory manager
  39210. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39211. return newAction;
  39212. }
  39213. /**
  39214. * Returns an existing animation action for the passed clip.
  39215. *
  39216. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39217. * @param {Object3D} [optionalRoot] - An alternative root object.
  39218. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39219. */
  39220. existingAction( clip, optionalRoot ) {
  39221. const root = optionalRoot || this._root,
  39222. rootUuid = root.uuid,
  39223. clipObject = typeof clip === 'string' ?
  39224. AnimationClip.findByName( root, clip ) : clip,
  39225. clipUuid = clipObject ? clipObject.uuid : clip,
  39226. actionsForClip = this._actionsByClip[ clipUuid ];
  39227. if ( actionsForClip !== undefined ) {
  39228. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39229. }
  39230. return null;
  39231. }
  39232. /**
  39233. * Deactivates all previously scheduled actions on this mixer.
  39234. *
  39235. * @return {AnimationMixer} A reference to this animation mixer.
  39236. */
  39237. stopAllAction() {
  39238. const actions = this._actions,
  39239. nActions = this._nActiveActions;
  39240. for ( let i = nActions - 1; i >= 0; -- i ) {
  39241. actions[ i ].stop();
  39242. }
  39243. return this;
  39244. }
  39245. /**
  39246. * Advances the global mixer time and updates the animation.
  39247. *
  39248. * This is usually done in the render loop by passing the delta
  39249. * time from {@link Clock} or {@link Timer}.
  39250. *
  39251. * @param {number} deltaTime - The delta time in seconds.
  39252. * @return {AnimationMixer} A reference to this animation mixer.
  39253. */
  39254. update( deltaTime ) {
  39255. deltaTime *= this.timeScale;
  39256. const actions = this._actions,
  39257. nActions = this._nActiveActions,
  39258. time = this.time += deltaTime,
  39259. timeDirection = Math.sign( deltaTime ),
  39260. accuIndex = this._accuIndex ^= 1;
  39261. // run active actions
  39262. for ( let i = 0; i !== nActions; ++ i ) {
  39263. const action = actions[ i ];
  39264. action._update( time, deltaTime, timeDirection, accuIndex );
  39265. }
  39266. // update scene graph
  39267. const bindings = this._bindings,
  39268. nBindings = this._nActiveBindings;
  39269. for ( let i = 0; i !== nBindings; ++ i ) {
  39270. bindings[ i ].apply( accuIndex );
  39271. }
  39272. return this;
  39273. }
  39274. /**
  39275. * Sets the global mixer to a specific time and updates the animation accordingly.
  39276. *
  39277. * This is useful when you need to jump to an exact time in an animation. The
  39278. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39279. *
  39280. * @param {number} time - The time to set in seconds.
  39281. * @return {AnimationMixer} A reference to this animation mixer.
  39282. */
  39283. setTime( time ) {
  39284. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39285. for ( let i = 0; i < this._actions.length; i ++ ) {
  39286. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39287. }
  39288. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39289. }
  39290. /**
  39291. * Returns this mixer's root object.
  39292. *
  39293. * @return {Object3D} The mixer's root object.
  39294. */
  39295. getRoot() {
  39296. return this._root;
  39297. }
  39298. /**
  39299. * Deallocates all memory resources for a clip. Before using this method make
  39300. * sure to call {@link AnimationAction#stop} for all related actions.
  39301. *
  39302. * @param {AnimationClip} clip - The clip to uncache.
  39303. */
  39304. uncacheClip( clip ) {
  39305. const actions = this._actions,
  39306. clipUuid = clip.uuid,
  39307. actionsByClip = this._actionsByClip,
  39308. actionsForClip = actionsByClip[ clipUuid ];
  39309. if ( actionsForClip !== undefined ) {
  39310. // note: just calling _removeInactiveAction would mess up the
  39311. // iteration state and also require updating the state we can
  39312. // just throw away
  39313. const actionsToRemove = actionsForClip.knownActions;
  39314. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39315. const action = actionsToRemove[ i ];
  39316. this._deactivateAction( action );
  39317. const cacheIndex = action._cacheIndex,
  39318. lastInactiveAction = actions[ actions.length - 1 ];
  39319. action._cacheIndex = null;
  39320. action._byClipCacheIndex = null;
  39321. lastInactiveAction._cacheIndex = cacheIndex;
  39322. actions[ cacheIndex ] = lastInactiveAction;
  39323. actions.pop();
  39324. this._removeInactiveBindingsForAction( action );
  39325. }
  39326. delete actionsByClip[ clipUuid ];
  39327. }
  39328. }
  39329. /**
  39330. * Deallocates all memory resources for a root object. Before using this
  39331. * method make sure to call {@link AnimationAction#stop} for all related
  39332. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39333. * mixer operates on a single root.
  39334. *
  39335. * @param {Object3D} root - The root object to uncache.
  39336. */
  39337. uncacheRoot( root ) {
  39338. const rootUuid = root.uuid,
  39339. actionsByClip = this._actionsByClip;
  39340. for ( const clipUuid in actionsByClip ) {
  39341. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39342. action = actionByRoot[ rootUuid ];
  39343. if ( action !== undefined ) {
  39344. this._deactivateAction( action );
  39345. this._removeInactiveAction( action );
  39346. }
  39347. }
  39348. const bindingsByRoot = this._bindingsByRootAndName,
  39349. bindingByName = bindingsByRoot[ rootUuid ];
  39350. if ( bindingByName !== undefined ) {
  39351. for ( const trackName in bindingByName ) {
  39352. const binding = bindingByName[ trackName ];
  39353. binding.restoreOriginalState();
  39354. this._removeInactiveBinding( binding );
  39355. }
  39356. }
  39357. }
  39358. /**
  39359. * Deallocates all memory resources for an action. The action is identified by the
  39360. * given clip and an optional root object. Before using this method make
  39361. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39362. *
  39363. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39364. * @param {Object3D} [optionalRoot] - An alternative root object.
  39365. */
  39366. uncacheAction( clip, optionalRoot ) {
  39367. const action = this.existingAction( clip, optionalRoot );
  39368. if ( action !== null ) {
  39369. this._deactivateAction( action );
  39370. this._removeInactiveAction( action );
  39371. }
  39372. }
  39373. }
  39374. /**
  39375. * Represents a 3D render target.
  39376. *
  39377. * @augments RenderTarget
  39378. */
  39379. class RenderTarget3D extends RenderTarget {
  39380. /**
  39381. * Constructs a new 3D render target.
  39382. *
  39383. * @param {number} [width=1] - The width of the render target.
  39384. * @param {number} [height=1] - The height of the render target.
  39385. * @param {number} [depth=1] - The height of the render target.
  39386. * @param {RenderTarget~Options} [options] - The configuration object.
  39387. */
  39388. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39389. super( width, height, options );
  39390. /**
  39391. * This flag can be used for type testing.
  39392. *
  39393. * @type {boolean}
  39394. * @readonly
  39395. * @default true
  39396. */
  39397. this.isRenderTarget3D = true;
  39398. this.depth = depth;
  39399. /**
  39400. * Overwritten with a different texture type.
  39401. *
  39402. * @type {Data3DTexture}
  39403. */
  39404. this.texture = new Data3DTexture( null, width, height, depth );
  39405. this._setTextureOptions( options );
  39406. this.texture.isRenderTargetTexture = true;
  39407. }
  39408. }
  39409. /**
  39410. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39411. *
  39412. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39413. * ```js
  39414. * uniforms: {
  39415. * time: { value: 1.0 },
  39416. * resolution: new Uniform( new Vector2() )
  39417. * };
  39418. * ```
  39419. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39420. * in {@link WebGLRenderer}.
  39421. */
  39422. class Uniform {
  39423. /**
  39424. * Constructs a new uniform.
  39425. *
  39426. * @param {any} value - The uniform value.
  39427. */
  39428. constructor( value ) {
  39429. /**
  39430. * The uniform value.
  39431. *
  39432. * @type {any}
  39433. */
  39434. this.value = value;
  39435. }
  39436. /**
  39437. * Returns a new uniform with copied values from this instance.
  39438. * If the value has a `clone()` method, the value is cloned as well.
  39439. *
  39440. * @return {Uniform} A clone of this instance.
  39441. */
  39442. clone() {
  39443. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39444. }
  39445. }
  39446. let _id$1 = 0;
  39447. /**
  39448. * A class for managing multiple uniforms in a single group. The renderer will process
  39449. * such a definition as a single UBO.
  39450. *
  39451. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39452. * in {@link WebGLRenderer}.
  39453. *
  39454. * @augments EventDispatcher
  39455. */
  39456. class UniformsGroup extends EventDispatcher {
  39457. /**
  39458. * Constructs a new uniforms group.
  39459. */
  39460. constructor() {
  39461. super();
  39462. /**
  39463. * This flag can be used for type testing.
  39464. *
  39465. * @type {boolean}
  39466. * @readonly
  39467. * @default true
  39468. */
  39469. this.isUniformsGroup = true;
  39470. /**
  39471. * The ID of the 3D object.
  39472. *
  39473. * @name UniformsGroup#id
  39474. * @type {number}
  39475. * @readonly
  39476. */
  39477. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39478. /**
  39479. * The name of the uniforms group.
  39480. *
  39481. * @type {string}
  39482. */
  39483. this.name = '';
  39484. /**
  39485. * The buffer usage.
  39486. *
  39487. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39488. * @default StaticDrawUsage
  39489. */
  39490. this.usage = StaticDrawUsage;
  39491. /**
  39492. * An array holding the uniforms.
  39493. *
  39494. * @type {Array<Uniform>}
  39495. */
  39496. this.uniforms = [];
  39497. }
  39498. /**
  39499. * Adds the given uniform to this uniforms group.
  39500. *
  39501. * @param {Uniform} uniform - The uniform to add.
  39502. * @return {UniformsGroup} A reference to this uniforms group.
  39503. */
  39504. add( uniform ) {
  39505. this.uniforms.push( uniform );
  39506. return this;
  39507. }
  39508. /**
  39509. * Removes the given uniform from this uniforms group.
  39510. *
  39511. * @param {Uniform} uniform - The uniform to remove.
  39512. * @return {UniformsGroup} A reference to this uniforms group.
  39513. */
  39514. remove( uniform ) {
  39515. const index = this.uniforms.indexOf( uniform );
  39516. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39517. return this;
  39518. }
  39519. /**
  39520. * Sets the name of this uniforms group.
  39521. *
  39522. * @param {string} name - The name to set.
  39523. * @return {UniformsGroup} A reference to this uniforms group.
  39524. */
  39525. setName( name ) {
  39526. this.name = name;
  39527. return this;
  39528. }
  39529. /**
  39530. * Sets the usage of this uniforms group.
  39531. *
  39532. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39533. * @return {UniformsGroup} A reference to this uniforms group.
  39534. */
  39535. setUsage( value ) {
  39536. this.usage = value;
  39537. return this;
  39538. }
  39539. /**
  39540. * Frees the GPU-related resources allocated by this instance. Call this
  39541. * method whenever this instance is no longer used in your app.
  39542. *
  39543. * @fires Texture#dispose
  39544. */
  39545. dispose() {
  39546. this.dispatchEvent( { type: 'dispose' } );
  39547. }
  39548. /**
  39549. * Copies the values of the given uniforms group to this instance.
  39550. *
  39551. * @param {UniformsGroup} source - The uniforms group to copy.
  39552. * @return {UniformsGroup} A reference to this uniforms group.
  39553. */
  39554. copy( source ) {
  39555. this.name = source.name;
  39556. this.usage = source.usage;
  39557. const uniformsSource = source.uniforms;
  39558. this.uniforms.length = 0;
  39559. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39560. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39561. for ( let j = 0; j < uniforms.length; j ++ ) {
  39562. this.uniforms.push( uniforms[ j ].clone() );
  39563. }
  39564. }
  39565. return this;
  39566. }
  39567. /**
  39568. * Returns a new uniforms group with copied values from this instance.
  39569. *
  39570. * @return {UniformsGroup} A clone of this instance.
  39571. */
  39572. clone() {
  39573. return new this.constructor().copy( this );
  39574. }
  39575. }
  39576. /**
  39577. * An instanced version of an interleaved buffer.
  39578. *
  39579. * @augments InterleavedBuffer
  39580. */
  39581. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39582. /**
  39583. * Constructs a new instanced interleaved buffer.
  39584. *
  39585. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39586. * @param {number} stride - The number of typed-array elements per vertex.
  39587. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39588. */
  39589. constructor( array, stride, meshPerAttribute = 1 ) {
  39590. super( array, stride );
  39591. /**
  39592. * This flag can be used for type testing.
  39593. *
  39594. * @type {boolean}
  39595. * @readonly
  39596. * @default true
  39597. */
  39598. this.isInstancedInterleavedBuffer = true;
  39599. /**
  39600. * Defines how often a value of this buffer attribute should be repeated,
  39601. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39602. *
  39603. * @type {number}
  39604. * @default 1
  39605. */
  39606. this.meshPerAttribute = meshPerAttribute;
  39607. }
  39608. copy( source ) {
  39609. super.copy( source );
  39610. this.meshPerAttribute = source.meshPerAttribute;
  39611. return this;
  39612. }
  39613. clone( data ) {
  39614. const ib = super.clone( data );
  39615. ib.meshPerAttribute = this.meshPerAttribute;
  39616. return ib;
  39617. }
  39618. toJSON( data ) {
  39619. const json = super.toJSON( data );
  39620. json.isInstancedInterleavedBuffer = true;
  39621. json.meshPerAttribute = this.meshPerAttribute;
  39622. return json;
  39623. }
  39624. }
  39625. /**
  39626. * An alternative version of a buffer attribute with more control over the VBO.
  39627. *
  39628. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39629. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39630. *
  39631. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39632. * or even produces the VBOs in question.
  39633. *
  39634. * Notice that this class can only be used with {@link WebGLRenderer}.
  39635. */
  39636. class GLBufferAttribute {
  39637. /**
  39638. * Constructs a new GL buffer attribute.
  39639. *
  39640. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39641. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39642. * @param {number} itemSize - The item size.
  39643. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39644. * @param {number} count - The expected number of vertices in VBO.
  39645. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39646. */
  39647. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39648. /**
  39649. * This flag can be used for type testing.
  39650. *
  39651. * @type {boolean}
  39652. * @readonly
  39653. * @default true
  39654. */
  39655. this.isGLBufferAttribute = true;
  39656. /**
  39657. * The name of the buffer attribute.
  39658. *
  39659. * @type {string}
  39660. */
  39661. this.name = '';
  39662. /**
  39663. * The native WebGL buffer.
  39664. *
  39665. * @type {WebGLBuffer}
  39666. */
  39667. this.buffer = buffer;
  39668. /**
  39669. * The native data type.
  39670. *
  39671. * @type {number}
  39672. */
  39673. this.type = type;
  39674. /**
  39675. * The item size, see {@link BufferAttribute#itemSize}.
  39676. *
  39677. * @type {number}
  39678. */
  39679. this.itemSize = itemSize;
  39680. /**
  39681. * The corresponding size (in bytes) for the given `type` parameter.
  39682. *
  39683. * @type {number}
  39684. */
  39685. this.elementSize = elementSize;
  39686. /**
  39687. * The expected number of vertices in VBO.
  39688. *
  39689. * @type {number}
  39690. */
  39691. this.count = count;
  39692. /**
  39693. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39694. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39695. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39696. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39697. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39698. *
  39699. * @type {boolean}
  39700. */
  39701. this.normalized = normalized;
  39702. /**
  39703. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39704. *
  39705. * @type {number}
  39706. */
  39707. this.version = 0;
  39708. }
  39709. /**
  39710. * Flag to indicate that this attribute has changed and should be re-sent to
  39711. * the GPU. Set this to `true` when you modify the value of the array.
  39712. *
  39713. * @type {number}
  39714. * @default false
  39715. * @param {boolean} value
  39716. */
  39717. set needsUpdate( value ) {
  39718. if ( value === true ) this.version ++;
  39719. }
  39720. /**
  39721. * Sets the given native WebGL buffer.
  39722. *
  39723. * @param {WebGLBuffer} buffer - The buffer to set.
  39724. * @return {BufferAttribute} A reference to this instance.
  39725. */
  39726. setBuffer( buffer ) {
  39727. this.buffer = buffer;
  39728. return this;
  39729. }
  39730. /**
  39731. * Sets the given native data type and element size.
  39732. *
  39733. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39734. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39735. * @return {BufferAttribute} A reference to this instance.
  39736. */
  39737. setType( type, elementSize ) {
  39738. this.type = type;
  39739. this.elementSize = elementSize;
  39740. return this;
  39741. }
  39742. /**
  39743. * Sets the item size.
  39744. *
  39745. * @param {number} itemSize - The item size.
  39746. * @return {BufferAttribute} A reference to this instance.
  39747. */
  39748. setItemSize( itemSize ) {
  39749. this.itemSize = itemSize;
  39750. return this;
  39751. }
  39752. /**
  39753. * Sets the count (the expected number of vertices in VBO).
  39754. *
  39755. * @param {number} count - The count.
  39756. * @return {BufferAttribute} A reference to this instance.
  39757. */
  39758. setCount( count ) {
  39759. this.count = count;
  39760. return this;
  39761. }
  39762. }
  39763. const _matrix = /*@__PURE__*/ new Matrix4();
  39764. /**
  39765. * This class is designed to assist with raycasting. Raycasting is used for
  39766. * mouse picking (working out what objects in the 3d space the mouse is over)
  39767. * amongst other things.
  39768. */
  39769. class Raycaster {
  39770. /**
  39771. * Constructs a new raycaster.
  39772. *
  39773. * @param {Vector3} origin - The origin vector where the ray casts from.
  39774. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39775. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39776. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39777. */
  39778. constructor( origin, direction, near = 0, far = Infinity ) {
  39779. /**
  39780. * The ray used for raycasting.
  39781. *
  39782. * @type {Ray}
  39783. */
  39784. this.ray = new Ray( origin, direction );
  39785. /**
  39786. * All results returned are further away than near. Near can't be negative.
  39787. *
  39788. * @type {number}
  39789. * @default 0
  39790. */
  39791. this.near = near;
  39792. /**
  39793. * All results returned are closer than far. Far can't be lower than near.
  39794. *
  39795. * @type {number}
  39796. * @default Infinity
  39797. */
  39798. this.far = far;
  39799. /**
  39800. * The camera to use when raycasting against view-dependent objects such as
  39801. * billboarded objects like sprites. This field can be set manually or
  39802. * is set when calling `setFromCamera()`.
  39803. *
  39804. * @type {?Camera}
  39805. * @default null
  39806. */
  39807. this.camera = null;
  39808. /**
  39809. * Allows to selectively ignore 3D objects when performing intersection tests.
  39810. * The following code example ensures that only 3D objects on layer `1` will be
  39811. * honored by raycaster.
  39812. * ```js
  39813. * raycaster.layers.set( 1 );
  39814. * object.layers.enable( 1 );
  39815. * ```
  39816. *
  39817. * @type {Layers}
  39818. */
  39819. this.layers = new Layers();
  39820. /**
  39821. * A parameter object that configures the raycasting. It has the structure:
  39822. *
  39823. * ```
  39824. * {
  39825. * Mesh: {},
  39826. * Line: { threshold: 1 },
  39827. * LOD: {},
  39828. * Points: { threshold: 1 },
  39829. * Sprite: {}
  39830. * }
  39831. * ```
  39832. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39833. *
  39834. * @type {Object}
  39835. */
  39836. this.params = {
  39837. Mesh: {},
  39838. Line: { threshold: 1 },
  39839. LOD: {},
  39840. Points: { threshold: 1 },
  39841. Sprite: {}
  39842. };
  39843. }
  39844. /**
  39845. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39846. *
  39847. * @param {Vector3} origin - The origin vector where the ray casts from.
  39848. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39849. */
  39850. set( origin, direction ) {
  39851. // direction is assumed to be normalized (for accurate distance calculations)
  39852. this.ray.set( origin, direction );
  39853. }
  39854. /**
  39855. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39856. *
  39857. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39858. * X and Y components should be between `-1` and `1`.
  39859. * @param {Camera} camera - The camera from which the ray should originate.
  39860. */
  39861. setFromCamera( coords, camera ) {
  39862. if ( camera.isPerspectiveCamera ) {
  39863. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39864. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39865. this.camera = camera;
  39866. } else if ( camera.isOrthographicCamera ) {
  39867. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39868. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39869. this.camera = camera;
  39870. } else {
  39871. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  39872. }
  39873. }
  39874. /**
  39875. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39876. *
  39877. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39878. * @return {Raycaster} A reference to this raycaster.
  39879. */
  39880. setFromXRController( controller ) {
  39881. _matrix.identity().extractRotation( controller.matrixWorld );
  39882. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39883. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39884. return this;
  39885. }
  39886. /**
  39887. * The intersection point of a raycaster intersection test.
  39888. * @typedef {Object} Raycaster~Intersection
  39889. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39890. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39891. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39892. * @property {Vector3} point - The intersection point, in world coordinates.
  39893. * @property {Object} face - The face that has been intersected.
  39894. * @property {number} faceIndex - The face index.
  39895. * @property {Object3D} object - The 3D object that has been intersected.
  39896. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39897. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39898. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  39899. * @property {number} instanceId - The index number of the instance where the ray
  39900. * intersects the {@link InstancedMesh}.
  39901. */
  39902. /**
  39903. * Checks all intersection between the ray and the object with or without the
  39904. * descendants. Intersections are returned sorted by distance, closest first.
  39905. *
  39906. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39907. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39908. * differently to ray casting than lines or points.
  39909. *
  39910. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39911. * to be detected; intersections of the ray passing through the back of a face will not
  39912. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39913. * to `THREE.DoubleSide`.
  39914. *
  39915. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39916. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39917. * Otherwise it only checks intersection with the object.
  39918. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39919. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39920. */
  39921. intersectObject( object, recursive = true, intersects = [] ) {
  39922. intersect( object, this, intersects, recursive );
  39923. intersects.sort( ascSort );
  39924. return intersects;
  39925. }
  39926. /**
  39927. * Checks all intersection between the ray and the objects with or without
  39928. * the descendants. Intersections are returned sorted by distance, closest first.
  39929. *
  39930. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39931. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39932. * Otherwise it only checks intersection with the object.
  39933. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39934. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39935. */
  39936. intersectObjects( objects, recursive = true, intersects = [] ) {
  39937. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39938. intersect( objects[ i ], this, intersects, recursive );
  39939. }
  39940. intersects.sort( ascSort );
  39941. return intersects;
  39942. }
  39943. }
  39944. function ascSort( a, b ) {
  39945. return a.distance - b.distance;
  39946. }
  39947. function intersect( object, raycaster, intersects, recursive ) {
  39948. let propagate = true;
  39949. if ( object.layers.test( raycaster.layers ) ) {
  39950. const result = object.raycast( raycaster, intersects );
  39951. if ( result === false ) propagate = false;
  39952. }
  39953. if ( propagate === true && recursive === true ) {
  39954. const children = object.children;
  39955. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39956. intersect( children[ i ], raycaster, intersects, true );
  39957. }
  39958. }
  39959. }
  39960. /**
  39961. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39962. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39963. *
  39964. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39965. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39966. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39967. * is inactive (e.g. tab switched or browser hidden).
  39968. *
  39969. * ```js
  39970. * const timer = new Timer();
  39971. * timer.connect( document ); // use Page Visibility API
  39972. * ```
  39973. */
  39974. class Timer {
  39975. /**
  39976. * Constructs a new timer.
  39977. */
  39978. constructor() {
  39979. this._previousTime = 0;
  39980. this._currentTime = 0;
  39981. this._startTime = performance.now();
  39982. this._delta = 0;
  39983. this._elapsed = 0;
  39984. this._timescale = 1;
  39985. this._document = null;
  39986. this._pageVisibilityHandler = null;
  39987. }
  39988. /**
  39989. * Connect the timer to the given document.Calling this method is not mandatory to
  39990. * use the timer but enables the usage of the Page Visibility API to avoid large time
  39991. * delta values.
  39992. *
  39993. * @param {Document} document - The document.
  39994. */
  39995. connect( document ) {
  39996. this._document = document;
  39997. // use Page Visibility API to avoid large time delta values
  39998. if ( document.hidden !== undefined ) {
  39999. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40000. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40001. }
  40002. }
  40003. /**
  40004. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40005. */
  40006. disconnect() {
  40007. if ( this._pageVisibilityHandler !== null ) {
  40008. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40009. this._pageVisibilityHandler = null;
  40010. }
  40011. this._document = null;
  40012. }
  40013. /**
  40014. * Returns the time delta in seconds.
  40015. *
  40016. * @return {number} The time delta in second.
  40017. */
  40018. getDelta() {
  40019. return this._delta / 1000;
  40020. }
  40021. /**
  40022. * Returns the elapsed time in seconds.
  40023. *
  40024. * @return {number} The elapsed time in second.
  40025. */
  40026. getElapsed() {
  40027. return this._elapsed / 1000;
  40028. }
  40029. /**
  40030. * Returns the timescale.
  40031. *
  40032. * @return {number} The timescale.
  40033. */
  40034. getTimescale() {
  40035. return this._timescale;
  40036. }
  40037. /**
  40038. * Sets the given timescale which scale the time delta computation
  40039. * in `update()`.
  40040. *
  40041. * @param {number} timescale - The timescale to set.
  40042. * @return {Timer} A reference to this timer.
  40043. */
  40044. setTimescale( timescale ) {
  40045. this._timescale = timescale;
  40046. return this;
  40047. }
  40048. /**
  40049. * Resets the time computation for the current simulation step.
  40050. *
  40051. * @return {Timer} A reference to this timer.
  40052. */
  40053. reset() {
  40054. this._currentTime = performance.now() - this._startTime;
  40055. return this;
  40056. }
  40057. /**
  40058. * Can be used to free all internal resources. Usually called when
  40059. * the timer instance isn't required anymore.
  40060. */
  40061. dispose() {
  40062. this.disconnect();
  40063. }
  40064. /**
  40065. * Updates the internal state of the timer. This method should be called
  40066. * once per simulation step and before you perform queries against the timer
  40067. * (e.g. via `getDelta()`).
  40068. *
  40069. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40070. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40071. * time will be determined with `performance.now`.
  40072. * @return {Timer} A reference to this timer.
  40073. */
  40074. update( timestamp ) {
  40075. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40076. this._delta = 0;
  40077. } else {
  40078. this._previousTime = this._currentTime;
  40079. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40080. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40081. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40082. }
  40083. return this;
  40084. }
  40085. }
  40086. function handleVisibilityChange() {
  40087. if ( this._document.hidden === false ) this.reset();
  40088. }
  40089. /**
  40090. * This class can be used to represent points in 3D space as
  40091. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40092. */
  40093. class Spherical {
  40094. /**
  40095. * Constructs a new spherical.
  40096. *
  40097. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40098. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40099. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40100. */
  40101. constructor( radius = 1, phi = 0, theta = 0 ) {
  40102. /**
  40103. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40104. *
  40105. * @type {number}
  40106. * @default 1
  40107. */
  40108. this.radius = radius;
  40109. /**
  40110. * The polar angle in radians from the y (up) axis.
  40111. *
  40112. * @type {number}
  40113. * @default 0
  40114. */
  40115. this.phi = phi;
  40116. /**
  40117. * The equator/azimuthal angle in radians around the y (up) axis.
  40118. *
  40119. * @type {number}
  40120. * @default 0
  40121. */
  40122. this.theta = theta;
  40123. }
  40124. /**
  40125. * Sets the spherical components by copying the given values.
  40126. *
  40127. * @param {number} radius - The radius.
  40128. * @param {number} phi - The polar angle.
  40129. * @param {number} theta - The azimuthal angle.
  40130. * @return {Spherical} A reference to this spherical.
  40131. */
  40132. set( radius, phi, theta ) {
  40133. this.radius = radius;
  40134. this.phi = phi;
  40135. this.theta = theta;
  40136. return this;
  40137. }
  40138. /**
  40139. * Copies the values of the given spherical to this instance.
  40140. *
  40141. * @param {Spherical} other - The spherical to copy.
  40142. * @return {Spherical} A reference to this spherical.
  40143. */
  40144. copy( other ) {
  40145. this.radius = other.radius;
  40146. this.phi = other.phi;
  40147. this.theta = other.theta;
  40148. return this;
  40149. }
  40150. /**
  40151. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40152. * `0.000001`.
  40153. *
  40154. * @return {Spherical} A reference to this spherical.
  40155. */
  40156. makeSafe() {
  40157. const EPS = 0.000001;
  40158. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40159. return this;
  40160. }
  40161. /**
  40162. * Sets the spherical components from the given vector which is assumed to hold
  40163. * Cartesian coordinates.
  40164. *
  40165. * @param {Vector3} v - The vector to set.
  40166. * @return {Spherical} A reference to this spherical.
  40167. */
  40168. setFromVector3( v ) {
  40169. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40170. }
  40171. /**
  40172. * Sets the spherical components from the given Cartesian coordinates.
  40173. *
  40174. * @param {number} x - The x value.
  40175. * @param {number} y - The y value.
  40176. * @param {number} z - The z value.
  40177. * @return {Spherical} A reference to this spherical.
  40178. */
  40179. setFromCartesianCoords( x, y, z ) {
  40180. this.radius = Math.sqrt( x * x + y * y + z * z );
  40181. if ( this.radius === 0 ) {
  40182. this.theta = 0;
  40183. this.phi = 0;
  40184. } else {
  40185. this.theta = Math.atan2( x, z );
  40186. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40187. }
  40188. return this;
  40189. }
  40190. /**
  40191. * Returns a new spherical with copied values from this instance.
  40192. *
  40193. * @return {Spherical} A clone of this instance.
  40194. */
  40195. clone() {
  40196. return new this.constructor().copy( this );
  40197. }
  40198. }
  40199. /**
  40200. * This class can be used to represent points in 3D space as
  40201. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40202. */
  40203. class Cylindrical {
  40204. /**
  40205. * Constructs a new cylindrical.
  40206. *
  40207. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40208. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40209. * @param {number} [y=0] - The height above the x-z plane.
  40210. */
  40211. constructor( radius = 1, theta = 0, y = 0 ) {
  40212. /**
  40213. * The distance from the origin to a point in the x-z plane.
  40214. *
  40215. * @type {number}
  40216. * @default 1
  40217. */
  40218. this.radius = radius;
  40219. /**
  40220. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40221. *
  40222. * @type {number}
  40223. * @default 0
  40224. */
  40225. this.theta = theta;
  40226. /**
  40227. * The height above the x-z plane.
  40228. *
  40229. * @type {number}
  40230. * @default 0
  40231. */
  40232. this.y = y;
  40233. }
  40234. /**
  40235. * Sets the cylindrical components by copying the given values.
  40236. *
  40237. * @param {number} radius - The radius.
  40238. * @param {number} theta - The theta angle.
  40239. * @param {number} y - The height value.
  40240. * @return {Cylindrical} A reference to this cylindrical.
  40241. */
  40242. set( radius, theta, y ) {
  40243. this.radius = radius;
  40244. this.theta = theta;
  40245. this.y = y;
  40246. return this;
  40247. }
  40248. /**
  40249. * Copies the values of the given cylindrical to this instance.
  40250. *
  40251. * @param {Cylindrical} other - The cylindrical to copy.
  40252. * @return {Cylindrical} A reference to this cylindrical.
  40253. */
  40254. copy( other ) {
  40255. this.radius = other.radius;
  40256. this.theta = other.theta;
  40257. this.y = other.y;
  40258. return this;
  40259. }
  40260. /**
  40261. * Sets the cylindrical components from the given vector which is assumed to hold
  40262. * Cartesian coordinates.
  40263. *
  40264. * @param {Vector3} v - The vector to set.
  40265. * @return {Cylindrical} A reference to this cylindrical.
  40266. */
  40267. setFromVector3( v ) {
  40268. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40269. }
  40270. /**
  40271. * Sets the cylindrical components from the given Cartesian coordinates.
  40272. *
  40273. * @param {number} x - The x value.
  40274. * @param {number} y - The x value.
  40275. * @param {number} z - The x value.
  40276. * @return {Cylindrical} A reference to this cylindrical.
  40277. */
  40278. setFromCartesianCoords( x, y, z ) {
  40279. this.radius = Math.sqrt( x * x + z * z );
  40280. this.theta = Math.atan2( x, z );
  40281. this.y = y;
  40282. return this;
  40283. }
  40284. /**
  40285. * Returns a new cylindrical with copied values from this instance.
  40286. *
  40287. * @return {Cylindrical} A clone of this instance.
  40288. */
  40289. clone() {
  40290. return new this.constructor().copy( this );
  40291. }
  40292. }
  40293. /**
  40294. * Represents a 2x2 matrix.
  40295. *
  40296. * A Note on Row-Major and Column-Major Ordering:
  40297. *
  40298. * The constructor and {@link Matrix2#set} method take arguments in
  40299. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40300. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40301. * This means that calling:
  40302. * ```js
  40303. * const m = new THREE.Matrix2();
  40304. * m.set( 11, 12,
  40305. * 21, 22 );
  40306. * ```
  40307. * will result in the elements array containing:
  40308. * ```js
  40309. * m.elements = [ 11, 21,
  40310. * 12, 22 ];
  40311. * ```
  40312. * and internally all calculations are performed using column-major ordering.
  40313. * However, as the actual ordering makes no difference mathematically and
  40314. * most people are used to thinking about matrices in row-major order, the
  40315. * three.js documentation shows matrices in row-major order. Just bear in
  40316. * mind that if you are reading the source code, you'll have to take the
  40317. * transpose of any matrices outlined here to make sense of the calculations.
  40318. */
  40319. class Matrix2 {
  40320. /**
  40321. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40322. * in row-major order. If no arguments are provided, the constructor
  40323. * initializes the matrix as an identity matrix.
  40324. *
  40325. * @param {number} [n11] - 1-1 matrix element.
  40326. * @param {number} [n12] - 1-2 matrix element.
  40327. * @param {number} [n21] - 2-1 matrix element.
  40328. * @param {number} [n22] - 2-2 matrix element.
  40329. */
  40330. constructor( n11, n12, n21, n22 ) {
  40331. /**
  40332. * This flag can be used for type testing.
  40333. *
  40334. * @type {boolean}
  40335. * @readonly
  40336. * @default true
  40337. */
  40338. Matrix2.prototype.isMatrix2 = true;
  40339. /**
  40340. * A column-major list of matrix values.
  40341. *
  40342. * @type {Array<number>}
  40343. */
  40344. this.elements = [
  40345. 1, 0,
  40346. 0, 1,
  40347. ];
  40348. if ( n11 !== undefined ) {
  40349. this.set( n11, n12, n21, n22 );
  40350. }
  40351. }
  40352. /**
  40353. * Sets this matrix to the 2x2 identity matrix.
  40354. *
  40355. * @return {Matrix2} A reference to this matrix.
  40356. */
  40357. identity() {
  40358. this.set(
  40359. 1, 0,
  40360. 0, 1,
  40361. );
  40362. return this;
  40363. }
  40364. /**
  40365. * Sets the elements of the matrix from the given array.
  40366. *
  40367. * @param {Array<number>} array - The matrix elements in column-major order.
  40368. * @param {number} [offset=0] - Index of the first element in the array.
  40369. * @return {Matrix2} A reference to this matrix.
  40370. */
  40371. fromArray( array, offset = 0 ) {
  40372. for ( let i = 0; i < 4; i ++ ) {
  40373. this.elements[ i ] = array[ i + offset ];
  40374. }
  40375. return this;
  40376. }
  40377. /**
  40378. * Sets the elements of the matrix.The arguments are supposed to be
  40379. * in row-major order.
  40380. *
  40381. * @param {number} n11 - 1-1 matrix element.
  40382. * @param {number} n12 - 1-2 matrix element.
  40383. * @param {number} n21 - 2-1 matrix element.
  40384. * @param {number} n22 - 2-2 matrix element.
  40385. * @return {Matrix2} A reference to this matrix.
  40386. */
  40387. set( n11, n12, n21, n22 ) {
  40388. const te = this.elements;
  40389. te[ 0 ] = n11; te[ 2 ] = n12;
  40390. te[ 1 ] = n21; te[ 3 ] = n22;
  40391. return this;
  40392. }
  40393. }
  40394. const _vector$4 = /*@__PURE__*/ new Vector2();
  40395. /**
  40396. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40397. */
  40398. class Box2 {
  40399. /**
  40400. * Constructs a new bounding box.
  40401. *
  40402. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40403. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40404. */
  40405. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40406. /**
  40407. * This flag can be used for type testing.
  40408. *
  40409. * @type {boolean}
  40410. * @readonly
  40411. * @default true
  40412. */
  40413. this.isBox2 = true;
  40414. /**
  40415. * The lower boundary of the box.
  40416. *
  40417. * @type {Vector2}
  40418. */
  40419. this.min = min;
  40420. /**
  40421. * The upper boundary of the box.
  40422. *
  40423. * @type {Vector2}
  40424. */
  40425. this.max = max;
  40426. }
  40427. /**
  40428. * Sets the lower and upper boundaries of this box.
  40429. * Please note that this method only copies the values from the given objects.
  40430. *
  40431. * @param {Vector2} min - The lower boundary of the box.
  40432. * @param {Vector2} max - The upper boundary of the box.
  40433. * @return {Box2} A reference to this bounding box.
  40434. */
  40435. set( min, max ) {
  40436. this.min.copy( min );
  40437. this.max.copy( max );
  40438. return this;
  40439. }
  40440. /**
  40441. * Sets the upper and lower bounds of this box so it encloses the position data
  40442. * in the given array.
  40443. *
  40444. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40445. * @return {Box2} A reference to this bounding box.
  40446. */
  40447. setFromPoints( points ) {
  40448. this.makeEmpty();
  40449. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40450. this.expandByPoint( points[ i ] );
  40451. }
  40452. return this;
  40453. }
  40454. /**
  40455. * Centers this box on the given center vector and sets this box's width, height and
  40456. * depth to the given size values.
  40457. *
  40458. * @param {Vector2} center - The center of the box.
  40459. * @param {Vector2} size - The x and y dimensions of the box.
  40460. * @return {Box2} A reference to this bounding box.
  40461. */
  40462. setFromCenterAndSize( center, size ) {
  40463. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40464. this.min.copy( center ).sub( halfSize );
  40465. this.max.copy( center ).add( halfSize );
  40466. return this;
  40467. }
  40468. /**
  40469. * Returns a new box with copied values from this instance.
  40470. *
  40471. * @return {Box2} A clone of this instance.
  40472. */
  40473. clone() {
  40474. return new this.constructor().copy( this );
  40475. }
  40476. /**
  40477. * Copies the values of the given box to this instance.
  40478. *
  40479. * @param {Box2} box - The box to copy.
  40480. * @return {Box2} A reference to this bounding box.
  40481. */
  40482. copy( box ) {
  40483. this.min.copy( box.min );
  40484. this.max.copy( box.max );
  40485. return this;
  40486. }
  40487. /**
  40488. * Makes this box empty which means in encloses a zero space in 2D.
  40489. *
  40490. * @return {Box2} A reference to this bounding box.
  40491. */
  40492. makeEmpty() {
  40493. this.min.x = this.min.y = + Infinity;
  40494. this.max.x = this.max.y = - Infinity;
  40495. return this;
  40496. }
  40497. /**
  40498. * Returns true if this box includes zero points within its bounds.
  40499. * Note that a box with equal lower and upper bounds still includes one
  40500. * point, the one both bounds share.
  40501. *
  40502. * @return {boolean} Whether this box is empty or not.
  40503. */
  40504. isEmpty() {
  40505. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40506. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40507. }
  40508. /**
  40509. * Returns the center point of this box.
  40510. *
  40511. * @param {Vector2} target - The target vector that is used to store the method's result.
  40512. * @return {Vector2} The center point.
  40513. */
  40514. getCenter( target ) {
  40515. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40516. }
  40517. /**
  40518. * Returns the dimensions of this box.
  40519. *
  40520. * @param {Vector2} target - The target vector that is used to store the method's result.
  40521. * @return {Vector2} The size.
  40522. */
  40523. getSize( target ) {
  40524. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40525. }
  40526. /**
  40527. * Expands the boundaries of this box to include the given point.
  40528. *
  40529. * @param {Vector2} point - The point that should be included by the bounding box.
  40530. * @return {Box2} A reference to this bounding box.
  40531. */
  40532. expandByPoint( point ) {
  40533. this.min.min( point );
  40534. this.max.max( point );
  40535. return this;
  40536. }
  40537. /**
  40538. * Expands this box equilaterally by the given vector. The width of this
  40539. * box will be expanded by the x component of the vector in both
  40540. * directions. The height of this box will be expanded by the y component of
  40541. * the vector in both directions.
  40542. *
  40543. * @param {Vector2} vector - The vector that should expand the bounding box.
  40544. * @return {Box2} A reference to this bounding box.
  40545. */
  40546. expandByVector( vector ) {
  40547. this.min.sub( vector );
  40548. this.max.add( vector );
  40549. return this;
  40550. }
  40551. /**
  40552. * Expands each dimension of the box by the given scalar. If negative, the
  40553. * dimensions of the box will be contracted.
  40554. *
  40555. * @param {number} scalar - The scalar value that should expand the bounding box.
  40556. * @return {Box2} A reference to this bounding box.
  40557. */
  40558. expandByScalar( scalar ) {
  40559. this.min.addScalar( - scalar );
  40560. this.max.addScalar( scalar );
  40561. return this;
  40562. }
  40563. /**
  40564. * Returns `true` if the given point lies within or on the boundaries of this box.
  40565. *
  40566. * @param {Vector2} point - The point to test.
  40567. * @return {boolean} Whether the bounding box contains the given point or not.
  40568. */
  40569. containsPoint( point ) {
  40570. return point.x >= this.min.x && point.x <= this.max.x &&
  40571. point.y >= this.min.y && point.y <= this.max.y;
  40572. }
  40573. /**
  40574. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40575. * If this box and the given one are identical, this function also returns `true`.
  40576. *
  40577. * @param {Box2} box - The bounding box to test.
  40578. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40579. */
  40580. containsBox( box ) {
  40581. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40582. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40583. }
  40584. /**
  40585. * Returns a point as a proportion of this box's width and height.
  40586. *
  40587. * @param {Vector2} point - A point in 2D space.
  40588. * @param {Vector2} target - The target vector that is used to store the method's result.
  40589. * @return {Vector2} A point as a proportion of this box's width and height.
  40590. */
  40591. getParameter( point, target ) {
  40592. // This can potentially have a divide by zero if the box
  40593. // has a size dimension of 0.
  40594. return target.set(
  40595. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40596. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40597. );
  40598. }
  40599. /**
  40600. * Returns `true` if the given bounding box intersects with this bounding box.
  40601. *
  40602. * @param {Box2} box - The bounding box to test.
  40603. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40604. */
  40605. intersectsBox( box ) {
  40606. // using 4 splitting planes to rule out intersections
  40607. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40608. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40609. }
  40610. /**
  40611. * Clamps the given point within the bounds of this box.
  40612. *
  40613. * @param {Vector2} point - The point to clamp.
  40614. * @param {Vector2} target - The target vector that is used to store the method's result.
  40615. * @return {Vector2} The clamped point.
  40616. */
  40617. clampPoint( point, target ) {
  40618. return target.copy( point ).clamp( this.min, this.max );
  40619. }
  40620. /**
  40621. * Returns the euclidean distance from any edge of this box to the specified point. If
  40622. * the given point lies inside of this box, the distance will be `0`.
  40623. *
  40624. * @param {Vector2} point - The point to compute the distance to.
  40625. * @return {number} The euclidean distance.
  40626. */
  40627. distanceToPoint( point ) {
  40628. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40629. }
  40630. /**
  40631. * Computes the intersection of this bounding box and the given one, setting the upper
  40632. * bound of this box to the lesser of the two boxes' upper bounds and the
  40633. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40634. * there's no overlap, makes this box empty.
  40635. *
  40636. * @param {Box2} box - The bounding box to intersect with.
  40637. * @return {Box2} A reference to this bounding box.
  40638. */
  40639. intersect( box ) {
  40640. this.min.max( box.min );
  40641. this.max.min( box.max );
  40642. if ( this.isEmpty() ) this.makeEmpty();
  40643. return this;
  40644. }
  40645. /**
  40646. * Computes the union of this box and another and the given one, setting the upper
  40647. * bound of this box to the greater of the two boxes' upper bounds and the
  40648. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40649. *
  40650. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40651. * @return {Box2} A reference to this bounding box.
  40652. */
  40653. union( box ) {
  40654. this.min.min( box.min );
  40655. this.max.max( box.max );
  40656. return this;
  40657. }
  40658. /**
  40659. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40660. * effectively moving it in 2D space.
  40661. *
  40662. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40663. * @return {Box2} A reference to this bounding box.
  40664. */
  40665. translate( offset ) {
  40666. this.min.add( offset );
  40667. this.max.add( offset );
  40668. return this;
  40669. }
  40670. /**
  40671. * Returns `true` if this bounding box is equal with the given one.
  40672. *
  40673. * @param {Box2} box - The box to test for equality.
  40674. * @return {boolean} Whether this bounding box is equal with the given one.
  40675. */
  40676. equals( box ) {
  40677. return box.min.equals( this.min ) && box.max.equals( this.max );
  40678. }
  40679. }
  40680. const _startP = /*@__PURE__*/ new Vector3();
  40681. const _startEnd = /*@__PURE__*/ new Vector3();
  40682. const _d1 = /*@__PURE__*/ new Vector3();
  40683. const _d2 = /*@__PURE__*/ new Vector3();
  40684. const _r = /*@__PURE__*/ new Vector3();
  40685. const _c1 = /*@__PURE__*/ new Vector3();
  40686. const _c2 = /*@__PURE__*/ new Vector3();
  40687. /**
  40688. * An analytical line segment in 3D space represented by a start and end point.
  40689. */
  40690. class Line3 {
  40691. /**
  40692. * Constructs a new line segment.
  40693. *
  40694. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40695. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40696. */
  40697. constructor( start = new Vector3(), end = new Vector3() ) {
  40698. /**
  40699. * Start of the line segment.
  40700. *
  40701. * @type {Vector3}
  40702. */
  40703. this.start = start;
  40704. /**
  40705. * End of the line segment.
  40706. *
  40707. * @type {Vector3}
  40708. */
  40709. this.end = end;
  40710. }
  40711. /**
  40712. * Sets the start and end values by copying the given vectors.
  40713. *
  40714. * @param {Vector3} start - The start point.
  40715. * @param {Vector3} end - The end point.
  40716. * @return {Line3} A reference to this line segment.
  40717. */
  40718. set( start, end ) {
  40719. this.start.copy( start );
  40720. this.end.copy( end );
  40721. return this;
  40722. }
  40723. /**
  40724. * Copies the values of the given line segment to this instance.
  40725. *
  40726. * @param {Line3} line - The line segment to copy.
  40727. * @return {Line3} A reference to this line segment.
  40728. */
  40729. copy( line ) {
  40730. this.start.copy( line.start );
  40731. this.end.copy( line.end );
  40732. return this;
  40733. }
  40734. /**
  40735. * Returns the center of the line segment.
  40736. *
  40737. * @param {Vector3} target - The target vector that is used to store the method's result.
  40738. * @return {Vector3} The center point.
  40739. */
  40740. getCenter( target ) {
  40741. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40742. }
  40743. /**
  40744. * Returns the delta vector of the line segment's start and end point.
  40745. *
  40746. * @param {Vector3} target - The target vector that is used to store the method's result.
  40747. * @return {Vector3} The delta vector.
  40748. */
  40749. delta( target ) {
  40750. return target.subVectors( this.end, this.start );
  40751. }
  40752. /**
  40753. * Returns the squared Euclidean distance between the line' start and end point.
  40754. *
  40755. * @return {number} The squared Euclidean distance.
  40756. */
  40757. distanceSq() {
  40758. return this.start.distanceToSquared( this.end );
  40759. }
  40760. /**
  40761. * Returns the Euclidean distance between the line' start and end point.
  40762. *
  40763. * @return {number} The Euclidean distance.
  40764. */
  40765. distance() {
  40766. return this.start.distanceTo( this.end );
  40767. }
  40768. /**
  40769. * Returns a vector at a certain position along the line segment.
  40770. *
  40771. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40772. * @param {Vector3} target - The target vector that is used to store the method's result.
  40773. * @return {Vector3} The delta vector.
  40774. */
  40775. at( t, target ) {
  40776. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40777. }
  40778. /**
  40779. * Returns a point parameter based on the closest point as projected on the line segment.
  40780. *
  40781. * @param {Vector3} point - The point for which to return a point parameter.
  40782. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40783. * @return {number} The point parameter.
  40784. */
  40785. closestPointToPointParameter( point, clampToLine ) {
  40786. _startP.subVectors( point, this.start );
  40787. _startEnd.subVectors( this.end, this.start );
  40788. const startEnd2 = _startEnd.dot( _startEnd );
  40789. const startEnd_startP = _startEnd.dot( _startP );
  40790. let t = startEnd_startP / startEnd2;
  40791. if ( clampToLine ) {
  40792. t = clamp( t, 0, 1 );
  40793. }
  40794. return t;
  40795. }
  40796. /**
  40797. * Returns the closest point on the line for a given point.
  40798. *
  40799. * @param {Vector3} point - The point to compute the closest point on the line for.
  40800. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40801. * @param {Vector3} target - The target vector that is used to store the method's result.
  40802. * @return {Vector3} The closest point on the line.
  40803. */
  40804. closestPointToPoint( point, clampToLine, target ) {
  40805. const t = this.closestPointToPointParameter( point, clampToLine );
  40806. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40807. }
  40808. /**
  40809. * Returns the closest squared distance between this line segment and the given one.
  40810. *
  40811. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40812. * @param {Vector3} [c1] - The closest point on this line segment.
  40813. * @param {Vector3} [c2] - The closest point on the given line segment.
  40814. * @return {number} The squared distance between this line segment and the given one.
  40815. */
  40816. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40817. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40818. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40819. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40820. // distance between between S1(s) and S2(t)
  40821. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40822. let s, t;
  40823. const p1 = this.start;
  40824. const p2 = line.start;
  40825. const q1 = this.end;
  40826. const q2 = line.end;
  40827. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40828. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40829. _r.subVectors( p1, p2 );
  40830. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40831. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40832. const f = _d2.dot( _r );
  40833. // Check if either or both segments degenerate into points
  40834. if ( a <= EPSILON && e <= EPSILON ) {
  40835. // Both segments degenerate into points
  40836. c1.copy( p1 );
  40837. c2.copy( p2 );
  40838. c1.sub( c2 );
  40839. return c1.dot( c1 );
  40840. }
  40841. if ( a <= EPSILON ) {
  40842. // First segment degenerates into a point
  40843. s = 0;
  40844. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40845. t = clamp( t, 0, 1 );
  40846. } else {
  40847. const c = _d1.dot( _r );
  40848. if ( e <= EPSILON ) {
  40849. // Second segment degenerates into a point
  40850. t = 0;
  40851. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40852. } else {
  40853. // The general nondegenerate case starts here
  40854. const b = _d1.dot( _d2 );
  40855. const denom = a * e - b * b; // Always nonnegative
  40856. // If segments not parallel, compute closest point on L1 to L2 and
  40857. // clamp to segment S1. Else pick arbitrary s (here 0)
  40858. if ( denom !== 0 ) {
  40859. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40860. } else {
  40861. s = 0;
  40862. }
  40863. // Compute point on L2 closest to S1(s) using
  40864. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40865. t = ( b * s + f ) / e;
  40866. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40867. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40868. // and clamp s to [0, 1]
  40869. if ( t < 0 ) {
  40870. t = 0.;
  40871. s = clamp( - c / a, 0, 1 );
  40872. } else if ( t > 1 ) {
  40873. t = 1;
  40874. s = clamp( ( b - c ) / a, 0, 1 );
  40875. }
  40876. }
  40877. }
  40878. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40879. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40880. c1.sub( c2 );
  40881. return c1.dot( c1 );
  40882. }
  40883. /**
  40884. * Applies a 4x4 transformation matrix to this line segment.
  40885. *
  40886. * @param {Matrix4} matrix - The transformation matrix.
  40887. * @return {Line3} A reference to this line segment.
  40888. */
  40889. applyMatrix4( matrix ) {
  40890. this.start.applyMatrix4( matrix );
  40891. this.end.applyMatrix4( matrix );
  40892. return this;
  40893. }
  40894. /**
  40895. * Returns `true` if this line segment is equal with the given one.
  40896. *
  40897. * @param {Line3} line - The line segment to test for equality.
  40898. * @return {boolean} Whether this line segment is equal with the given one.
  40899. */
  40900. equals( line ) {
  40901. return line.start.equals( this.start ) && line.end.equals( this.end );
  40902. }
  40903. /**
  40904. * Returns a new line segment with copied values from this instance.
  40905. *
  40906. * @return {Line3} A clone of this instance.
  40907. */
  40908. clone() {
  40909. return new this.constructor().copy( this );
  40910. }
  40911. }
  40912. const _vector$3 = /*@__PURE__*/ new Vector3();
  40913. /**
  40914. * This displays a cone shaped helper object for a {@link SpotLight}.
  40915. *
  40916. * ```js
  40917. * const spotLight = new THREE.SpotLight( 0xffffff );
  40918. * spotLight.position.set( 10, 10, 10 );
  40919. * scene.add( spotLight );
  40920. *
  40921. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40922. * scene.add( spotLightHelper );
  40923. * ```
  40924. *
  40925. * @augments Object3D
  40926. */
  40927. class SpotLightHelper extends Object3D {
  40928. /**
  40929. * Constructs a new spot light helper.
  40930. *
  40931. * @param {HemisphereLight} light - The light to be visualized.
  40932. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40933. * the color of the light.
  40934. */
  40935. constructor( light, color ) {
  40936. super();
  40937. /**
  40938. * The light being visualized.
  40939. *
  40940. * @type {SpotLight}
  40941. */
  40942. this.light = light;
  40943. this.matrixAutoUpdate = false;
  40944. /**
  40945. * The color parameter passed in the constructor.
  40946. * If not set, the helper will take the color of the light.
  40947. *
  40948. * @type {number|Color|string}
  40949. */
  40950. this.color = color;
  40951. this.type = 'SpotLightHelper';
  40952. const geometry = new BufferGeometry();
  40953. const positions = [
  40954. 0, 0, 0, 0, 0, 1,
  40955. 0, 0, 0, 1, 0, 1,
  40956. 0, 0, 0, -1, 0, 1,
  40957. 0, 0, 0, 0, 1, 1,
  40958. 0, 0, 0, 0, -1, 1
  40959. ];
  40960. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40961. const p1 = ( i / l ) * Math.PI * 2;
  40962. const p2 = ( j / l ) * Math.PI * 2;
  40963. positions.push(
  40964. Math.cos( p1 ), Math.sin( p1 ), 1,
  40965. Math.cos( p2 ), Math.sin( p2 ), 1
  40966. );
  40967. }
  40968. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40969. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40970. this.cone = new LineSegments( geometry, material );
  40971. this.add( this.cone );
  40972. this.update();
  40973. }
  40974. /**
  40975. * Frees the GPU-related resources allocated by this instance. Call this
  40976. * method whenever this instance is no longer used in your app.
  40977. */
  40978. dispose() {
  40979. this.cone.geometry.dispose();
  40980. this.cone.material.dispose();
  40981. }
  40982. /**
  40983. * Updates the helper to match the position and direction of the
  40984. * light being visualized.
  40985. */
  40986. update() {
  40987. this.light.updateWorldMatrix( true, false );
  40988. this.light.target.updateWorldMatrix( true, false );
  40989. // update the local matrix based on the parent and light target transforms
  40990. if ( this.parent ) {
  40991. this.parent.updateWorldMatrix( true );
  40992. this.matrix
  40993. .copy( this.parent.matrixWorld )
  40994. .invert()
  40995. .multiply( this.light.matrixWorld );
  40996. } else {
  40997. this.matrix.copy( this.light.matrixWorld );
  40998. }
  40999. this.matrixWorld.copy( this.light.matrixWorld );
  41000. const coneLength = this.light.distance ? this.light.distance : 1000;
  41001. const coneWidth = coneLength * Math.tan( this.light.angle );
  41002. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41003. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41004. this.cone.lookAt( _vector$3 );
  41005. if ( this.color !== undefined ) {
  41006. this.cone.material.color.set( this.color );
  41007. } else {
  41008. this.cone.material.color.copy( this.light.color );
  41009. }
  41010. }
  41011. }
  41012. const _vector$2 = /*@__PURE__*/ new Vector3();
  41013. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41014. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41015. /**
  41016. * A helper object to assist with visualizing a {@link Skeleton}.
  41017. *
  41018. * ```js
  41019. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41020. * scene.add( helper );
  41021. * ```
  41022. *
  41023. * @augments LineSegments
  41024. */
  41025. class SkeletonHelper extends LineSegments {
  41026. /**
  41027. * Constructs a new skeleton helper.
  41028. *
  41029. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41030. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41031. */
  41032. constructor( object ) {
  41033. const bones = getBoneList( object );
  41034. const geometry = new BufferGeometry();
  41035. const vertices = [];
  41036. const colors = [];
  41037. for ( let i = 0; i < bones.length; i ++ ) {
  41038. const bone = bones[ i ];
  41039. if ( bone.parent && bone.parent.isBone ) {
  41040. vertices.push( 0, 0, 0 );
  41041. vertices.push( 0, 0, 0 );
  41042. colors.push( 0, 0, 0 );
  41043. colors.push( 0, 0, 0 );
  41044. }
  41045. }
  41046. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41047. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41048. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41049. super( geometry, material );
  41050. /**
  41051. * This flag can be used for type testing.
  41052. *
  41053. * @type {boolean}
  41054. * @readonly
  41055. * @default true
  41056. */
  41057. this.isSkeletonHelper = true;
  41058. this.type = 'SkeletonHelper';
  41059. /**
  41060. * The object being visualized.
  41061. *
  41062. * @type {Object3D}
  41063. */
  41064. this.root = object;
  41065. /**
  41066. * The list of bones that the helper visualizes.
  41067. *
  41068. * @type {Array<Bone>}
  41069. */
  41070. this.bones = bones;
  41071. this.matrix = object.matrixWorld;
  41072. this.matrixAutoUpdate = false;
  41073. // colors
  41074. const color1 = new Color( 0x0000ff );
  41075. const color2 = new Color( 0x00ff00 );
  41076. this.setColors( color1, color2 );
  41077. }
  41078. updateMatrixWorld( force ) {
  41079. const bones = this.bones;
  41080. const geometry = this.geometry;
  41081. const position = geometry.getAttribute( 'position' );
  41082. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41083. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41084. const bone = bones[ i ];
  41085. if ( bone.parent && bone.parent.isBone ) {
  41086. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41087. _vector$2.setFromMatrixPosition( _boneMatrix );
  41088. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41089. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41090. _vector$2.setFromMatrixPosition( _boneMatrix );
  41091. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41092. j += 2;
  41093. }
  41094. }
  41095. geometry.getAttribute( 'position' ).needsUpdate = true;
  41096. super.updateMatrixWorld( force );
  41097. }
  41098. /**
  41099. * Defines the colors of the helper.
  41100. *
  41101. * @param {Color} color1 - The first line color for each bone.
  41102. * @param {Color} color2 - The second line color for each bone.
  41103. * @return {SkeletonHelper} A reference to this helper.
  41104. */
  41105. setColors( color1, color2 ) {
  41106. const geometry = this.geometry;
  41107. const colorAttribute = geometry.getAttribute( 'color' );
  41108. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41109. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41110. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41111. }
  41112. colorAttribute.needsUpdate = true;
  41113. return this;
  41114. }
  41115. /**
  41116. * Frees the GPU-related resources allocated by this instance. Call this
  41117. * method whenever this instance is no longer used in your app.
  41118. */
  41119. dispose() {
  41120. this.geometry.dispose();
  41121. this.material.dispose();
  41122. }
  41123. }
  41124. function getBoneList( object ) {
  41125. const boneList = [];
  41126. if ( object.isBone === true ) {
  41127. boneList.push( object );
  41128. }
  41129. for ( let i = 0; i < object.children.length; i ++ ) {
  41130. boneList.push( ...getBoneList( object.children[ i ] ) );
  41131. }
  41132. return boneList;
  41133. }
  41134. /**
  41135. * This displays a helper object consisting of a spherical mesh for
  41136. * visualizing an instance of {@link PointLight}.
  41137. *
  41138. * ```js
  41139. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41140. * pointLight.position.set( 10, 10, 10 );
  41141. * scene.add( pointLight );
  41142. *
  41143. * const sphereSize = 1;
  41144. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41145. * scene.add( pointLightHelper );
  41146. * ```
  41147. *
  41148. * @augments Mesh
  41149. */
  41150. class PointLightHelper extends Mesh {
  41151. /**
  41152. * Constructs a new point light helper.
  41153. *
  41154. * @param {PointLight} light - The light to be visualized.
  41155. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41156. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41157. * the color of the light.
  41158. */
  41159. constructor( light, sphereSize, color ) {
  41160. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41161. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41162. super( geometry, material );
  41163. /**
  41164. * The light being visualized.
  41165. *
  41166. * @type {PointLight}
  41167. */
  41168. this.light = light;
  41169. /**
  41170. * The color parameter passed in the constructor.
  41171. * If not set, the helper will take the color of the light.
  41172. *
  41173. * @type {number|Color|string}
  41174. */
  41175. this.color = color;
  41176. this.type = 'PointLightHelper';
  41177. this.matrix = this.light.matrixWorld;
  41178. this.matrixAutoUpdate = false;
  41179. this.update();
  41180. /*
  41181. // TODO: delete this comment?
  41182. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41183. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41184. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41185. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41186. const d = light.distance;
  41187. if ( d === 0.0 ) {
  41188. this.lightDistance.visible = false;
  41189. } else {
  41190. this.lightDistance.scale.set( d, d, d );
  41191. }
  41192. this.add( this.lightDistance );
  41193. */
  41194. }
  41195. /**
  41196. * Frees the GPU-related resources allocated by this instance. Call this
  41197. * method whenever this instance is no longer used in your app.
  41198. */
  41199. dispose() {
  41200. this.geometry.dispose();
  41201. this.material.dispose();
  41202. }
  41203. /**
  41204. * Updates the helper to match the position of the
  41205. * light being visualized.
  41206. */
  41207. update() {
  41208. this.light.updateWorldMatrix( true, false );
  41209. if ( this.color !== undefined ) {
  41210. this.material.color.set( this.color );
  41211. } else {
  41212. this.material.color.copy( this.light.color );
  41213. }
  41214. /*
  41215. const d = this.light.distance;
  41216. if ( d === 0.0 ) {
  41217. this.lightDistance.visible = false;
  41218. } else {
  41219. this.lightDistance.visible = true;
  41220. this.lightDistance.scale.set( d, d, d );
  41221. }
  41222. */
  41223. }
  41224. }
  41225. const _vector$1 = /*@__PURE__*/ new Vector3();
  41226. const _color1 = /*@__PURE__*/ new Color();
  41227. const _color2 = /*@__PURE__*/ new Color();
  41228. /**
  41229. * Creates a visual aid consisting of a spherical mesh for a
  41230. * given {@link HemisphereLight}.
  41231. *
  41232. * ```js
  41233. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41234. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41235. * scene.add( helper );
  41236. * ```
  41237. *
  41238. * @augments Object3D
  41239. */
  41240. class HemisphereLightHelper extends Object3D {
  41241. /**
  41242. * Constructs a new hemisphere light helper.
  41243. *
  41244. * @param {HemisphereLight} light - The light to be visualized.
  41245. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41246. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41247. * the color of the light.
  41248. */
  41249. constructor( light, size, color ) {
  41250. super();
  41251. /**
  41252. * The light being visualized.
  41253. *
  41254. * @type {HemisphereLight}
  41255. */
  41256. this.light = light;
  41257. this.matrix = light.matrixWorld;
  41258. this.matrixAutoUpdate = false;
  41259. /**
  41260. * The color parameter passed in the constructor.
  41261. * If not set, the helper will take the color of the light.
  41262. *
  41263. * @type {number|Color|string}
  41264. */
  41265. this.color = color;
  41266. this.type = 'HemisphereLightHelper';
  41267. const geometry = new OctahedronGeometry( size );
  41268. geometry.rotateY( Math.PI * 0.5 );
  41269. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41270. if ( this.color === undefined ) this.material.vertexColors = true;
  41271. const position = geometry.getAttribute( 'position' );
  41272. const colors = new Float32Array( position.count * 3 );
  41273. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41274. this.add( new Mesh( geometry, this.material ) );
  41275. this.update();
  41276. }
  41277. /**
  41278. * Frees the GPU-related resources allocated by this instance. Call this
  41279. * method whenever this instance is no longer used in your app.
  41280. */
  41281. dispose() {
  41282. this.children[ 0 ].geometry.dispose();
  41283. this.children[ 0 ].material.dispose();
  41284. }
  41285. /**
  41286. * Updates the helper to match the position and direction of the
  41287. * light being visualized.
  41288. */
  41289. update() {
  41290. const mesh = this.children[ 0 ];
  41291. if ( this.color !== undefined ) {
  41292. this.material.color.set( this.color );
  41293. } else {
  41294. const colors = mesh.geometry.getAttribute( 'color' );
  41295. _color1.copy( this.light.color );
  41296. _color2.copy( this.light.groundColor );
  41297. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41298. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41299. colors.setXYZ( i, color.r, color.g, color.b );
  41300. }
  41301. colors.needsUpdate = true;
  41302. }
  41303. this.light.updateWorldMatrix( true, false );
  41304. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41305. }
  41306. }
  41307. /**
  41308. * The helper is an object to define grids. Grids are two-dimensional
  41309. * arrays of lines.
  41310. *
  41311. * ```js
  41312. * const size = 10;
  41313. * const divisions = 10;
  41314. *
  41315. * const gridHelper = new THREE.GridHelper( size, divisions );
  41316. * scene.add( gridHelper );
  41317. * ```
  41318. *
  41319. * @augments LineSegments
  41320. */
  41321. class GridHelper extends LineSegments {
  41322. /**
  41323. * Constructs a new grid helper.
  41324. *
  41325. * @param {number} [size=10] - The size of the grid.
  41326. * @param {number} [divisions=10] - The number of divisions across the grid.
  41327. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41328. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41329. */
  41330. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41331. color1 = new Color( color1 );
  41332. color2 = new Color( color2 );
  41333. const center = divisions / 2;
  41334. const step = size / divisions;
  41335. const halfSize = size / 2;
  41336. const vertices = [], colors = [];
  41337. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41338. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41339. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41340. const color = i === center ? color1 : color2;
  41341. color.toArray( colors, j ); j += 3;
  41342. color.toArray( colors, j ); j += 3;
  41343. color.toArray( colors, j ); j += 3;
  41344. color.toArray( colors, j ); j += 3;
  41345. }
  41346. const geometry = new BufferGeometry();
  41347. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41348. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41349. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41350. super( geometry, material );
  41351. this.type = 'GridHelper';
  41352. }
  41353. /**
  41354. * Frees the GPU-related resources allocated by this instance. Call this
  41355. * method whenever this instance is no longer used in your app.
  41356. */
  41357. dispose() {
  41358. this.geometry.dispose();
  41359. this.material.dispose();
  41360. }
  41361. }
  41362. /**
  41363. * This helper is an object to define polar grids. Grids are
  41364. * two-dimensional arrays of lines.
  41365. *
  41366. * ```js
  41367. * const radius = 10;
  41368. * const sectors = 16;
  41369. * const rings = 8;
  41370. * const divisions = 64;
  41371. *
  41372. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41373. * scene.add( helper );
  41374. * ```
  41375. *
  41376. * @augments LineSegments
  41377. */
  41378. class PolarGridHelper extends LineSegments {
  41379. /**
  41380. * Constructs a new polar grid helper.
  41381. *
  41382. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41383. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41384. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41385. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41386. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41387. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41388. */
  41389. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41390. color1 = new Color( color1 );
  41391. color2 = new Color( color2 );
  41392. const vertices = [];
  41393. const colors = [];
  41394. // create the sectors
  41395. if ( sectors > 1 ) {
  41396. for ( let i = 0; i < sectors; i ++ ) {
  41397. const v = ( i / sectors ) * ( Math.PI * 2 );
  41398. const x = Math.sin( v ) * radius;
  41399. const z = Math.cos( v ) * radius;
  41400. vertices.push( 0, 0, 0 );
  41401. vertices.push( x, 0, z );
  41402. const color = ( i & 1 ) ? color1 : color2;
  41403. colors.push( color.r, color.g, color.b );
  41404. colors.push( color.r, color.g, color.b );
  41405. }
  41406. }
  41407. // create the rings
  41408. for ( let i = 0; i < rings; i ++ ) {
  41409. const color = ( i & 1 ) ? color1 : color2;
  41410. const r = radius - ( radius / rings * i );
  41411. for ( let j = 0; j < divisions; j ++ ) {
  41412. // first vertex
  41413. let v = ( j / divisions ) * ( Math.PI * 2 );
  41414. let x = Math.sin( v ) * r;
  41415. let z = Math.cos( v ) * r;
  41416. vertices.push( x, 0, z );
  41417. colors.push( color.r, color.g, color.b );
  41418. // second vertex
  41419. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41420. x = Math.sin( v ) * r;
  41421. z = Math.cos( v ) * r;
  41422. vertices.push( x, 0, z );
  41423. colors.push( color.r, color.g, color.b );
  41424. }
  41425. }
  41426. const geometry = new BufferGeometry();
  41427. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41428. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41429. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41430. super( geometry, material );
  41431. this.type = 'PolarGridHelper';
  41432. }
  41433. /**
  41434. * Frees the GPU-related resources allocated by this instance. Call this
  41435. * method whenever this instance is no longer used in your app.
  41436. */
  41437. dispose() {
  41438. this.geometry.dispose();
  41439. this.material.dispose();
  41440. }
  41441. }
  41442. const _v1 = /*@__PURE__*/ new Vector3();
  41443. const _v2 = /*@__PURE__*/ new Vector3();
  41444. const _v3 = /*@__PURE__*/ new Vector3();
  41445. /**
  41446. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41447. * effect on the scene. This consists of plane and a line representing the
  41448. * light's position and direction.
  41449. *
  41450. * ```js
  41451. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41452. * scene.add( light );
  41453. *
  41454. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41455. * scene.add( helper );
  41456. * ```
  41457. *
  41458. * @augments Object3D
  41459. */
  41460. class DirectionalLightHelper extends Object3D {
  41461. /**
  41462. * Constructs a new directional light helper.
  41463. *
  41464. * @param {DirectionalLight} light - The light to be visualized.
  41465. * @param {number} [size=1] - The dimensions of the plane.
  41466. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41467. * the color of the light.
  41468. */
  41469. constructor( light, size, color ) {
  41470. super();
  41471. /**
  41472. * The light being visualized.
  41473. *
  41474. * @type {DirectionalLight}
  41475. */
  41476. this.light = light;
  41477. this.matrix = light.matrixWorld;
  41478. this.matrixAutoUpdate = false;
  41479. /**
  41480. * The color parameter passed in the constructor.
  41481. * If not set, the helper will take the color of the light.
  41482. *
  41483. * @type {number|Color|string}
  41484. */
  41485. this.color = color;
  41486. this.type = 'DirectionalLightHelper';
  41487. if ( size === undefined ) size = 1;
  41488. let geometry = new BufferGeometry();
  41489. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41490. - size, size, 0,
  41491. size, size, 0,
  41492. size, - size, 0,
  41493. - size, - size, 0,
  41494. - size, size, 0
  41495. ], 3 ) );
  41496. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41497. /**
  41498. * Contains the line showing the location of the directional light.
  41499. *
  41500. * @type {Line}
  41501. */
  41502. this.lightPlane = new Line( geometry, material );
  41503. this.add( this.lightPlane );
  41504. geometry = new BufferGeometry();
  41505. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41506. /**
  41507. * Represents the target line of the directional light.
  41508. *
  41509. * @type {Line}
  41510. */
  41511. this.targetLine = new Line( geometry, material );
  41512. this.add( this.targetLine );
  41513. this.update();
  41514. }
  41515. /**
  41516. * Frees the GPU-related resources allocated by this instance. Call this
  41517. * method whenever this instance is no longer used in your app.
  41518. */
  41519. dispose() {
  41520. this.lightPlane.geometry.dispose();
  41521. this.lightPlane.material.dispose();
  41522. this.targetLine.geometry.dispose();
  41523. this.targetLine.material.dispose();
  41524. }
  41525. /**
  41526. * Updates the helper to match the position and direction of the
  41527. * light being visualized.
  41528. */
  41529. update() {
  41530. this.light.updateWorldMatrix( true, false );
  41531. this.light.target.updateWorldMatrix( true, false );
  41532. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41533. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41534. _v3.subVectors( _v2, _v1 );
  41535. this.lightPlane.lookAt( _v2 );
  41536. if ( this.color !== undefined ) {
  41537. this.lightPlane.material.color.set( this.color );
  41538. this.targetLine.material.color.set( this.color );
  41539. } else {
  41540. this.lightPlane.material.color.copy( this.light.color );
  41541. this.targetLine.material.color.copy( this.light.color );
  41542. }
  41543. this.targetLine.lookAt( _v2 );
  41544. this.targetLine.scale.z = _v3.length();
  41545. }
  41546. }
  41547. const _vector = /*@__PURE__*/ new Vector3();
  41548. const _camera = /*@__PURE__*/ new Camera();
  41549. /**
  41550. * This helps with visualizing what a camera contains in its frustum. It
  41551. * visualizes the frustum of a camera using a line segments.
  41552. *
  41553. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41554. *
  41555. * `CameraHelper` must be a child of the scene.
  41556. *
  41557. * ```js
  41558. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41559. * const helper = new THREE.CameraHelper( camera );
  41560. * scene.add( helper );
  41561. * ```
  41562. *
  41563. * @augments LineSegments
  41564. */
  41565. class CameraHelper extends LineSegments {
  41566. /**
  41567. * Constructs a new arrow helper.
  41568. *
  41569. * @param {Camera} camera - The camera to visualize.
  41570. */
  41571. constructor( camera ) {
  41572. const geometry = new BufferGeometry();
  41573. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41574. const vertices = [];
  41575. const colors = [];
  41576. const pointMap = {};
  41577. // near
  41578. addLine( 'n1', 'n2' );
  41579. addLine( 'n2', 'n4' );
  41580. addLine( 'n4', 'n3' );
  41581. addLine( 'n3', 'n1' );
  41582. // far
  41583. addLine( 'f1', 'f2' );
  41584. addLine( 'f2', 'f4' );
  41585. addLine( 'f4', 'f3' );
  41586. addLine( 'f3', 'f1' );
  41587. // sides
  41588. addLine( 'n1', 'f1' );
  41589. addLine( 'n2', 'f2' );
  41590. addLine( 'n3', 'f3' );
  41591. addLine( 'n4', 'f4' );
  41592. // cone
  41593. addLine( 'p', 'n1' );
  41594. addLine( 'p', 'n2' );
  41595. addLine( 'p', 'n3' );
  41596. addLine( 'p', 'n4' );
  41597. // up
  41598. addLine( 'u1', 'u2' );
  41599. addLine( 'u2', 'u3' );
  41600. addLine( 'u3', 'u1' );
  41601. // target
  41602. addLine( 'c', 't' );
  41603. addLine( 'p', 'c' );
  41604. // cross
  41605. addLine( 'cn1', 'cn2' );
  41606. addLine( 'cn3', 'cn4' );
  41607. addLine( 'cf1', 'cf2' );
  41608. addLine( 'cf3', 'cf4' );
  41609. function addLine( a, b ) {
  41610. addPoint( a );
  41611. addPoint( b );
  41612. }
  41613. function addPoint( id ) {
  41614. vertices.push( 0, 0, 0 );
  41615. colors.push( 0, 0, 0 );
  41616. if ( pointMap[ id ] === undefined ) {
  41617. pointMap[ id ] = [];
  41618. }
  41619. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41620. }
  41621. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41622. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41623. super( geometry, material );
  41624. this.type = 'CameraHelper';
  41625. /**
  41626. * The camera being visualized.
  41627. *
  41628. * @type {Camera}
  41629. */
  41630. this.camera = camera;
  41631. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41632. this.matrix = camera.matrixWorld;
  41633. this.matrixAutoUpdate = false;
  41634. /**
  41635. * This contains the points used to visualize the camera.
  41636. *
  41637. * @type {Object<string,Array<number>>}
  41638. */
  41639. this.pointMap = pointMap;
  41640. this.update();
  41641. // colors
  41642. const colorFrustum = new Color( 0xffaa00 );
  41643. const colorCone = new Color( 0xff0000 );
  41644. const colorUp = new Color( 0x00aaff );
  41645. const colorTarget = new Color( 0xffffff );
  41646. const colorCross = new Color( 0x333333 );
  41647. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41648. }
  41649. /**
  41650. * Defines the colors of the helper.
  41651. *
  41652. * @param {Color} frustum - The frustum line color.
  41653. * @param {Color} cone - The cone line color.
  41654. * @param {Color} up - The up line color.
  41655. * @param {Color} target - The target line color.
  41656. * @param {Color} cross - The cross line color.
  41657. * @return {CameraHelper} A reference to this helper.
  41658. */
  41659. setColors( frustum, cone, up, target, cross ) {
  41660. const geometry = this.geometry;
  41661. const colorAttribute = geometry.getAttribute( 'color' );
  41662. // near
  41663. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41664. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41665. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41666. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41667. // far
  41668. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41669. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41670. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41671. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41672. // sides
  41673. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41674. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41675. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41676. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41677. // cone
  41678. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41679. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41680. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41681. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41682. // up
  41683. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41684. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41685. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41686. // target
  41687. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41688. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41689. // cross
  41690. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41691. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41692. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41693. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41694. colorAttribute.needsUpdate = true;
  41695. return this;
  41696. }
  41697. /**
  41698. * Updates the helper based on the projection matrix of the camera.
  41699. */
  41700. update() {
  41701. const geometry = this.geometry;
  41702. const pointMap = this.pointMap;
  41703. const w = 1, h = 1;
  41704. let nearZ, farZ;
  41705. // we need just camera projection matrix inverse
  41706. // world matrix must be identity
  41707. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41708. // Adjust z values based on coordinate system
  41709. if ( this.camera.reversedDepth === true ) {
  41710. nearZ = 1;
  41711. farZ = 0;
  41712. } else {
  41713. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41714. nearZ = -1;
  41715. farZ = 1;
  41716. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41717. nearZ = 0;
  41718. farZ = 1;
  41719. } else {
  41720. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41721. }
  41722. }
  41723. // center / target
  41724. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41725. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41726. // near
  41727. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41728. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41729. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41730. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41731. // far
  41732. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41733. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41734. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41735. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41736. // up
  41737. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41738. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41739. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41740. // cross
  41741. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41742. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41743. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41744. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41745. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41746. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41747. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41748. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41749. geometry.getAttribute( 'position' ).needsUpdate = true;
  41750. }
  41751. /**
  41752. * Frees the GPU-related resources allocated by this instance. Call this
  41753. * method whenever this instance is no longer used in your app.
  41754. */
  41755. dispose() {
  41756. this.geometry.dispose();
  41757. this.material.dispose();
  41758. }
  41759. }
  41760. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41761. _vector.set( x, y, z ).unproject( camera );
  41762. const points = pointMap[ point ];
  41763. if ( points !== undefined ) {
  41764. const position = geometry.getAttribute( 'position' );
  41765. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41766. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41767. }
  41768. }
  41769. }
  41770. const _box = /*@__PURE__*/ new Box3();
  41771. /**
  41772. * Helper object to graphically show the world-axis-aligned bounding box
  41773. * around an object. The actual bounding box is handled with {@link Box3},
  41774. * this is just a visual helper for debugging. It can be automatically
  41775. * resized with {@link BoxHelper#update} when the object it's created from
  41776. * is transformed. Note that the object must have a geometry for this to work,
  41777. * so it won't work with sprites.
  41778. *
  41779. * ```js
  41780. * const sphere = new THREE.SphereGeometry();
  41781. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41782. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41783. * scene.add( box );
  41784. * ```
  41785. *
  41786. * @augments LineSegments
  41787. */
  41788. class BoxHelper extends LineSegments {
  41789. /**
  41790. * Constructs a new box helper.
  41791. *
  41792. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41793. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41794. */
  41795. constructor( object, color = 0xffff00 ) {
  41796. 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 ] );
  41797. const positions = new Float32Array( 8 * 3 );
  41798. const geometry = new BufferGeometry();
  41799. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41800. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41801. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41802. /**
  41803. * The 3D object being visualized.
  41804. *
  41805. * @type {Object3D}
  41806. */
  41807. this.object = object;
  41808. this.type = 'BoxHelper';
  41809. this.matrixAutoUpdate = false;
  41810. this.update();
  41811. }
  41812. /**
  41813. * Updates the helper's geometry to match the dimensions of the object,
  41814. * including any children.
  41815. */
  41816. update() {
  41817. if ( this.object !== undefined ) {
  41818. _box.setFromObject( this.object );
  41819. }
  41820. if ( _box.isEmpty() ) return;
  41821. const min = _box.min;
  41822. const max = _box.max;
  41823. /*
  41824. 5____4
  41825. 1/___0/|
  41826. | 6__|_7
  41827. 2/___3/
  41828. 0: max.x, max.y, max.z
  41829. 1: min.x, max.y, max.z
  41830. 2: min.x, min.y, max.z
  41831. 3: max.x, min.y, max.z
  41832. 4: max.x, max.y, min.z
  41833. 5: min.x, max.y, min.z
  41834. 6: min.x, min.y, min.z
  41835. 7: max.x, min.y, min.z
  41836. */
  41837. const position = this.geometry.attributes.position;
  41838. const array = position.array;
  41839. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41840. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41841. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41842. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41843. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41844. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41845. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41846. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41847. position.needsUpdate = true;
  41848. this.geometry.computeBoundingSphere();
  41849. }
  41850. /**
  41851. * Updates the wireframe box for the passed object.
  41852. *
  41853. * @param {Object3D} object - The 3D object to create the helper for.
  41854. * @return {BoxHelper} A reference to this instance.
  41855. */
  41856. setFromObject( object ) {
  41857. this.object = object;
  41858. this.update();
  41859. return this;
  41860. }
  41861. copy( source, recursive ) {
  41862. super.copy( source, recursive );
  41863. this.object = source.object;
  41864. return this;
  41865. }
  41866. /**
  41867. * Frees the GPU-related resources allocated by this instance. Call this
  41868. * method whenever this instance is no longer used in your app.
  41869. */
  41870. dispose() {
  41871. this.geometry.dispose();
  41872. this.material.dispose();
  41873. }
  41874. }
  41875. /**
  41876. * A helper object to visualize an instance of {@link Box3}.
  41877. *
  41878. * ```js
  41879. * const box = new THREE.Box3();
  41880. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41881. *
  41882. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41883. * scene.add( helper )
  41884. * ```
  41885. *
  41886. * @augments LineSegments
  41887. */
  41888. class Box3Helper extends LineSegments {
  41889. /**
  41890. * Constructs a new box3 helper.
  41891. *
  41892. * @param {Box3} box - The box to visualize.
  41893. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41894. */
  41895. constructor( box, color = 0xffff00 ) {
  41896. 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 ] );
  41897. 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 ];
  41898. const geometry = new BufferGeometry();
  41899. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41900. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41901. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41902. /**
  41903. * The box being visualized.
  41904. *
  41905. * @type {Box3}
  41906. */
  41907. this.box = box;
  41908. this.type = 'Box3Helper';
  41909. this.geometry.computeBoundingSphere();
  41910. }
  41911. updateMatrixWorld( force ) {
  41912. const box = this.box;
  41913. if ( box.isEmpty() ) return;
  41914. box.getCenter( this.position );
  41915. box.getSize( this.scale );
  41916. this.scale.multiplyScalar( 0.5 );
  41917. super.updateMatrixWorld( force );
  41918. }
  41919. /**
  41920. * Frees the GPU-related resources allocated by this instance. Call this
  41921. * method whenever this instance is no longer used in your app.
  41922. */
  41923. dispose() {
  41924. this.geometry.dispose();
  41925. this.material.dispose();
  41926. }
  41927. }
  41928. /**
  41929. * A helper object to visualize an instance of {@link Plane}.
  41930. *
  41931. * ```js
  41932. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41933. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41934. * scene.add( helper );
  41935. * ```
  41936. *
  41937. * @augments Line
  41938. */
  41939. class PlaneHelper extends Line {
  41940. /**
  41941. * Constructs a new plane helper.
  41942. *
  41943. * @param {Plane} plane - The plane to be visualized.
  41944. * @param {number} [size=1] - The side length of plane helper.
  41945. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41946. */
  41947. constructor( plane, size = 1, hex = 0xffff00 ) {
  41948. const color = hex;
  41949. 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 ];
  41950. const geometry = new BufferGeometry();
  41951. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41952. geometry.computeBoundingSphere();
  41953. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41954. this.type = 'PlaneHelper';
  41955. /**
  41956. * The plane being visualized.
  41957. *
  41958. * @type {Plane}
  41959. */
  41960. this.plane = plane;
  41961. /**
  41962. * The side length of plane helper.
  41963. *
  41964. * @type {number}
  41965. * @default 1
  41966. */
  41967. this.size = size;
  41968. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41969. const geometry2 = new BufferGeometry();
  41970. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41971. geometry2.computeBoundingSphere();
  41972. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41973. }
  41974. updateMatrixWorld( force ) {
  41975. this.position.set( 0, 0, 0 );
  41976. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41977. this.lookAt( this.plane.normal );
  41978. this.translateZ( - this.plane.constant );
  41979. super.updateMatrixWorld( force );
  41980. }
  41981. /**
  41982. * Updates the helper to match the position and direction of the
  41983. * light being visualized.
  41984. */
  41985. dispose() {
  41986. this.geometry.dispose();
  41987. this.material.dispose();
  41988. this.children[ 0 ].geometry.dispose();
  41989. this.children[ 0 ].material.dispose();
  41990. }
  41991. }
  41992. const _axis = /*@__PURE__*/ new Vector3();
  41993. let _lineGeometry, _coneGeometry;
  41994. /**
  41995. * An 3D arrow object for visualizing directions.
  41996. *
  41997. * ```js
  41998. * const dir = new THREE.Vector3( 1, 2, 0 );
  41999. *
  42000. * //normalize the direction vector (convert to vector of length 1)
  42001. * dir.normalize();
  42002. *
  42003. * const origin = new THREE.Vector3( 0, 0, 0 );
  42004. * const length = 1;
  42005. * const hex = 0xffff00;
  42006. *
  42007. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42008. * scene.add( arrowHelper );
  42009. * ```
  42010. *
  42011. * @augments Object3D
  42012. */
  42013. class ArrowHelper extends Object3D {
  42014. /**
  42015. * Constructs a new arrow helper.
  42016. *
  42017. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42018. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42019. * @param {number} [length=1] - Length of the arrow in world units.
  42020. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42021. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42022. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42023. */
  42024. 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 ) {
  42025. super();
  42026. this.type = 'ArrowHelper';
  42027. if ( _lineGeometry === undefined ) {
  42028. _lineGeometry = new BufferGeometry();
  42029. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42030. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42031. _coneGeometry.translate( 0, -0.5, 0 );
  42032. }
  42033. this.position.copy( origin );
  42034. /**
  42035. * The line part of the arrow helper.
  42036. *
  42037. * @type {Line}
  42038. */
  42039. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42040. this.line.matrixAutoUpdate = false;
  42041. this.add( this.line );
  42042. /**
  42043. * The cone part of the arrow helper.
  42044. *
  42045. * @type {Mesh}
  42046. */
  42047. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42048. this.cone.matrixAutoUpdate = false;
  42049. this.add( this.cone );
  42050. this.setDirection( dir );
  42051. this.setLength( length, headLength, headWidth );
  42052. }
  42053. /**
  42054. * Sets the direction of the helper.
  42055. *
  42056. * @param {Vector3} dir - The normalized direction vector.
  42057. */
  42058. setDirection( dir ) {
  42059. // dir is assumed to be normalized
  42060. if ( dir.y > 0.99999 ) {
  42061. this.quaternion.set( 0, 0, 0, 1 );
  42062. } else if ( dir.y < -0.99999 ) {
  42063. this.quaternion.set( 1, 0, 0, 0 );
  42064. } else {
  42065. _axis.set( dir.z, 0, - dir.x ).normalize();
  42066. const radians = Math.acos( dir.y );
  42067. this.quaternion.setFromAxisAngle( _axis, radians );
  42068. }
  42069. }
  42070. /**
  42071. * Sets the length of the helper.
  42072. *
  42073. * @param {number} length - Length of the arrow in world units.
  42074. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42075. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42076. */
  42077. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42078. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42079. this.line.updateMatrix();
  42080. this.cone.scale.set( headWidth, headLength, headWidth );
  42081. this.cone.position.y = length;
  42082. this.cone.updateMatrix();
  42083. }
  42084. /**
  42085. * Sets the color of the helper.
  42086. *
  42087. * @param {number|Color|string} color - The color to set.
  42088. */
  42089. setColor( color ) {
  42090. this.line.material.color.set( color );
  42091. this.cone.material.color.set( color );
  42092. }
  42093. copy( source ) {
  42094. super.copy( source, false );
  42095. this.line.copy( source.line );
  42096. this.cone.copy( source.cone );
  42097. return this;
  42098. }
  42099. /**
  42100. * Frees the GPU-related resources allocated by this instance. Call this
  42101. * method whenever this instance is no longer used in your app.
  42102. */
  42103. dispose() {
  42104. this.line.geometry.dispose();
  42105. this.line.material.dispose();
  42106. this.cone.geometry.dispose();
  42107. this.cone.material.dispose();
  42108. }
  42109. }
  42110. /**
  42111. * An axis object to visualize the 3 axes in a simple way.
  42112. * The X axis is red. The Y axis is green. The Z axis is blue.
  42113. *
  42114. * ```js
  42115. * const axesHelper = new THREE.AxesHelper( 5 );
  42116. * scene.add( axesHelper );
  42117. * ```
  42118. *
  42119. * @augments LineSegments
  42120. */
  42121. class AxesHelper extends LineSegments {
  42122. /**
  42123. * Constructs a new axes helper.
  42124. *
  42125. * @param {number} [size=1] - Size of the lines representing the axes.
  42126. */
  42127. constructor( size = 1 ) {
  42128. const vertices = [
  42129. 0, 0, 0, size, 0, 0,
  42130. 0, 0, 0, 0, size, 0,
  42131. 0, 0, 0, 0, 0, size
  42132. ];
  42133. const colors = [
  42134. 1, 0, 0, 1, 0.6, 0,
  42135. 0, 1, 0, 0.6, 1, 0,
  42136. 0, 0, 1, 0, 0.6, 1
  42137. ];
  42138. const geometry = new BufferGeometry();
  42139. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42140. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42141. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42142. super( geometry, material );
  42143. this.type = 'AxesHelper';
  42144. }
  42145. /**
  42146. * Defines the colors of the axes helper.
  42147. *
  42148. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42149. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42150. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42151. * @return {AxesHelper} A reference to this axes helper.
  42152. */
  42153. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42154. const color = new Color();
  42155. const array = this.geometry.attributes.color.array;
  42156. color.set( xAxisColor );
  42157. color.toArray( array, 0 );
  42158. color.toArray( array, 3 );
  42159. color.set( yAxisColor );
  42160. color.toArray( array, 6 );
  42161. color.toArray( array, 9 );
  42162. color.set( zAxisColor );
  42163. color.toArray( array, 12 );
  42164. color.toArray( array, 15 );
  42165. this.geometry.attributes.color.needsUpdate = true;
  42166. return this;
  42167. }
  42168. /**
  42169. * Frees the GPU-related resources allocated by this instance. Call this
  42170. * method whenever this instance is no longer used in your app.
  42171. */
  42172. dispose() {
  42173. this.geometry.dispose();
  42174. this.material.dispose();
  42175. }
  42176. }
  42177. /**
  42178. * This class is used to convert a series of paths to an array of
  42179. * shapes. It is specifically used in context of fonts and SVG.
  42180. */
  42181. class ShapePath {
  42182. /**
  42183. * Constructs a new shape path.
  42184. */
  42185. constructor() {
  42186. this.type = 'ShapePath';
  42187. /**
  42188. * The color of the shape.
  42189. *
  42190. * @type {Color}
  42191. */
  42192. this.color = new Color();
  42193. /**
  42194. * The paths that have been generated for this shape.
  42195. *
  42196. * @type {Array<Path>}
  42197. * @default null
  42198. */
  42199. this.subPaths = [];
  42200. /**
  42201. * The current path that is being generated.
  42202. *
  42203. * @type {?Path}
  42204. * @default null
  42205. */
  42206. this.currentPath = null;
  42207. }
  42208. /**
  42209. * Creates a new path and moves it current point to the given one.
  42210. *
  42211. * @param {number} x - The x coordinate.
  42212. * @param {number} y - The y coordinate.
  42213. * @return {ShapePath} A reference to this shape path.
  42214. */
  42215. moveTo( x, y ) {
  42216. this.currentPath = new Path();
  42217. this.subPaths.push( this.currentPath );
  42218. this.currentPath.moveTo( x, y );
  42219. return this;
  42220. }
  42221. /**
  42222. * Adds an instance of {@link LineCurve} to the path by connecting
  42223. * the current point with the given one.
  42224. *
  42225. * @param {number} x - The x coordinate of the end point.
  42226. * @param {number} y - The y coordinate of the end point.
  42227. * @return {ShapePath} A reference to this shape path.
  42228. */
  42229. lineTo( x, y ) {
  42230. this.currentPath.lineTo( x, y );
  42231. return this;
  42232. }
  42233. /**
  42234. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42235. * the current point with the given one.
  42236. *
  42237. * @param {number} aCPx - The x coordinate of the control point.
  42238. * @param {number} aCPy - The y coordinate of the control point.
  42239. * @param {number} aX - The x coordinate of the end point.
  42240. * @param {number} aY - The y coordinate of the end point.
  42241. * @return {ShapePath} A reference to this shape path.
  42242. */
  42243. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42244. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42245. return this;
  42246. }
  42247. /**
  42248. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42249. * the current point with the given one.
  42250. *
  42251. * @param {number} aCP1x - The x coordinate of the first control point.
  42252. * @param {number} aCP1y - The y coordinate of the first control point.
  42253. * @param {number} aCP2x - The x coordinate of the second control point.
  42254. * @param {number} aCP2y - The y coordinate of the second control point.
  42255. * @param {number} aX - The x coordinate of the end point.
  42256. * @param {number} aY - The y coordinate of the end point.
  42257. * @return {ShapePath} A reference to this shape path.
  42258. */
  42259. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42260. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42261. return this;
  42262. }
  42263. /**
  42264. * Adds an instance of {@link SplineCurve} to the path by connecting
  42265. * the current point with the given list of points.
  42266. *
  42267. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42268. * @return {ShapePath} A reference to this shape path.
  42269. */
  42270. splineThru( pts ) {
  42271. this.currentPath.splineThru( pts );
  42272. return this;
  42273. }
  42274. /**
  42275. * Converts the paths into an array of shapes.
  42276. *
  42277. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42278. * If this flag is set to `true`, then those are flipped.
  42279. * @return {Array<Shape>} An array of shapes.
  42280. */
  42281. toShapes( isCCW ) {
  42282. function toShapesNoHoles( inSubpaths ) {
  42283. const shapes = [];
  42284. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42285. const tmpPath = inSubpaths[ i ];
  42286. const tmpShape = new Shape();
  42287. tmpShape.curves = tmpPath.curves;
  42288. shapes.push( tmpShape );
  42289. }
  42290. return shapes;
  42291. }
  42292. function isPointInsidePolygon( inPt, inPolygon ) {
  42293. const polyLen = inPolygon.length;
  42294. // inPt on polygon contour => immediate success or
  42295. // toggling of inside/outside at every single! intersection point of an edge
  42296. // with the horizontal line through inPt, left of inPt
  42297. // not counting lowerY endpoints of edges and whole edges on that line
  42298. let inside = false;
  42299. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42300. let edgeLowPt = inPolygon[ p ];
  42301. let edgeHighPt = inPolygon[ q ];
  42302. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42303. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42304. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42305. // not parallel
  42306. if ( edgeDy < 0 ) {
  42307. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42308. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42309. }
  42310. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42311. if ( inPt.y === edgeLowPt.y ) {
  42312. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42313. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42314. } else {
  42315. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42316. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42317. if ( perpEdge < 0 ) continue;
  42318. inside = ! inside; // true intersection left of inPt
  42319. }
  42320. } else {
  42321. // parallel or collinear
  42322. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42323. // edge lies on the same horizontal line as inPt
  42324. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42325. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42326. // continue;
  42327. }
  42328. }
  42329. return inside;
  42330. }
  42331. const isClockWise = ShapeUtils.isClockWise;
  42332. const subPaths = this.subPaths;
  42333. if ( subPaths.length === 0 ) return [];
  42334. let solid, tmpPath, tmpShape;
  42335. const shapes = [];
  42336. if ( subPaths.length === 1 ) {
  42337. tmpPath = subPaths[ 0 ];
  42338. tmpShape = new Shape();
  42339. tmpShape.curves = tmpPath.curves;
  42340. shapes.push( tmpShape );
  42341. return shapes;
  42342. }
  42343. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42344. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42345. // log("Holes first", holesFirst);
  42346. const betterShapeHoles = [];
  42347. const newShapes = [];
  42348. let newShapeHoles = [];
  42349. let mainIdx = 0;
  42350. let tmpPoints;
  42351. newShapes[ mainIdx ] = undefined;
  42352. newShapeHoles[ mainIdx ] = [];
  42353. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42354. tmpPath = subPaths[ i ];
  42355. tmpPoints = tmpPath.getPoints();
  42356. solid = isClockWise( tmpPoints );
  42357. solid = isCCW ? ! solid : solid;
  42358. if ( solid ) {
  42359. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42360. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42361. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42362. if ( holesFirst ) mainIdx ++;
  42363. newShapeHoles[ mainIdx ] = [];
  42364. //log('cw', i);
  42365. } else {
  42366. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42367. //log('ccw', i);
  42368. }
  42369. }
  42370. // only Holes? -> probably all Shapes with wrong orientation
  42371. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42372. if ( newShapes.length > 1 ) {
  42373. let ambiguous = false;
  42374. let toChange = 0;
  42375. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42376. betterShapeHoles[ sIdx ] = [];
  42377. }
  42378. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42379. const sho = newShapeHoles[ sIdx ];
  42380. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42381. const ho = sho[ hIdx ];
  42382. let hole_unassigned = true;
  42383. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42384. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42385. if ( sIdx !== s2Idx ) toChange ++;
  42386. if ( hole_unassigned ) {
  42387. hole_unassigned = false;
  42388. betterShapeHoles[ s2Idx ].push( ho );
  42389. } else {
  42390. ambiguous = true;
  42391. }
  42392. }
  42393. }
  42394. if ( hole_unassigned ) {
  42395. betterShapeHoles[ sIdx ].push( ho );
  42396. }
  42397. }
  42398. }
  42399. if ( toChange > 0 && ambiguous === false ) {
  42400. newShapeHoles = betterShapeHoles;
  42401. }
  42402. }
  42403. let tmpHoles;
  42404. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42405. tmpShape = newShapes[ i ].s;
  42406. shapes.push( tmpShape );
  42407. tmpHoles = newShapeHoles[ i ];
  42408. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42409. tmpShape.holes.push( tmpHoles[ j ].h );
  42410. }
  42411. }
  42412. //log("shape", shapes);
  42413. return shapes;
  42414. }
  42415. }
  42416. /**
  42417. * Abstract base class for controls.
  42418. *
  42419. * @abstract
  42420. * @augments EventDispatcher
  42421. */
  42422. class Controls extends EventDispatcher {
  42423. /**
  42424. * Constructs a new controls instance.
  42425. *
  42426. * @param {Object3D} object - The object that is managed by the controls.
  42427. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42428. */
  42429. constructor( object, domElement = null ) {
  42430. super();
  42431. /**
  42432. * The object that is managed by the controls.
  42433. *
  42434. * @type {Object3D}
  42435. */
  42436. this.object = object;
  42437. /**
  42438. * The HTML element used for event listeners.
  42439. *
  42440. * @type {?HTMLElement}
  42441. * @default null
  42442. */
  42443. this.domElement = domElement;
  42444. /**
  42445. * Whether the controls responds to user input or not.
  42446. *
  42447. * @type {boolean}
  42448. * @default true
  42449. */
  42450. this.enabled = true;
  42451. /**
  42452. * The internal state of the controls.
  42453. *
  42454. * @type {number}
  42455. * @default -1
  42456. */
  42457. this.state = -1;
  42458. /**
  42459. * This object defines the keyboard input of the controls.
  42460. *
  42461. * @type {Object}
  42462. */
  42463. this.keys = {};
  42464. /**
  42465. * This object defines what type of actions are assigned to the available mouse buttons.
  42466. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42467. *
  42468. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42469. */
  42470. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42471. /**
  42472. * This object defines what type of actions are assigned to what kind of touch interaction.
  42473. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42474. *
  42475. * @type {{ONE: ?number, TWO: ?number}}
  42476. */
  42477. this.touches = { ONE: null, TWO: null };
  42478. }
  42479. /**
  42480. * Connects the controls to the DOM. This method has so called "side effects" since
  42481. * it adds the module's event listeners to the DOM.
  42482. *
  42483. * @param {HTMLElement} element - The DOM element to connect to.
  42484. */
  42485. connect( element ) {
  42486. if ( element === undefined ) {
  42487. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42488. return;
  42489. }
  42490. if ( this.domElement !== null ) this.disconnect();
  42491. this.domElement = element;
  42492. }
  42493. /**
  42494. * Disconnects the controls from the DOM.
  42495. */
  42496. disconnect() {}
  42497. /**
  42498. * Call this method if you no longer want use to the controls. It frees all internal
  42499. * resources and removes all event listeners.
  42500. */
  42501. dispose() {}
  42502. /**
  42503. * Controls should implement this method if they have to update their internal state
  42504. * per simulation step.
  42505. *
  42506. * @param {number} [delta] - The time delta in seconds.
  42507. */
  42508. update( /* delta */ ) {}
  42509. }
  42510. /**
  42511. * Scales the texture as large as possible within its surface without cropping
  42512. * or stretching the texture. The method preserves the original aspect ratio of
  42513. * the texture. Akin to CSS `object-fit: contain`
  42514. *
  42515. * @param {Texture} texture - The texture.
  42516. * @param {number} aspect - The texture's aspect ratio.
  42517. * @return {Texture} The updated texture.
  42518. */
  42519. function contain( texture, aspect ) {
  42520. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42521. if ( imageAspect > aspect ) {
  42522. texture.repeat.x = 1;
  42523. texture.repeat.y = imageAspect / aspect;
  42524. texture.offset.x = 0;
  42525. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42526. } else {
  42527. texture.repeat.x = aspect / imageAspect;
  42528. texture.repeat.y = 1;
  42529. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42530. texture.offset.y = 0;
  42531. }
  42532. return texture;
  42533. }
  42534. /**
  42535. * Scales the texture to the smallest possible size to fill the surface, leaving
  42536. * no empty space. The method preserves the original aspect ratio of the texture.
  42537. * Akin to CSS `object-fit: cover`.
  42538. *
  42539. * @param {Texture} texture - The texture.
  42540. * @param {number} aspect - The texture's aspect ratio.
  42541. * @return {Texture} The updated texture.
  42542. */
  42543. function cover( texture, aspect ) {
  42544. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42545. if ( imageAspect > aspect ) {
  42546. texture.repeat.x = aspect / imageAspect;
  42547. texture.repeat.y = 1;
  42548. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42549. texture.offset.y = 0;
  42550. } else {
  42551. texture.repeat.x = 1;
  42552. texture.repeat.y = imageAspect / aspect;
  42553. texture.offset.x = 0;
  42554. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42555. }
  42556. return texture;
  42557. }
  42558. /**
  42559. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42560. *
  42561. * @param {Texture} texture - The texture.
  42562. * @return {Texture} The updated texture.
  42563. */
  42564. function fill( texture ) {
  42565. texture.repeat.x = 1;
  42566. texture.repeat.y = 1;
  42567. texture.offset.x = 0;
  42568. texture.offset.y = 0;
  42569. return texture;
  42570. }
  42571. /**
  42572. * Determines how many bytes must be used to represent the texture.
  42573. *
  42574. * @param {number} width - The width of the texture.
  42575. * @param {number} height - The height of the texture.
  42576. * @param {number} format - The texture's format.
  42577. * @param {number} type - The texture's type.
  42578. * @return {number} The byte length.
  42579. */
  42580. function getByteLength( width, height, format, type ) {
  42581. const typeByteLength = getTextureTypeByteLength( type );
  42582. switch ( format ) {
  42583. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42584. case AlphaFormat:
  42585. return width * height;
  42586. case RedFormat:
  42587. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42588. case RedIntegerFormat:
  42589. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42590. case RGFormat:
  42591. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42592. case RGIntegerFormat:
  42593. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42594. case RGBFormat:
  42595. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42596. case RGBAFormat:
  42597. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42598. case RGBAIntegerFormat:
  42599. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42600. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42601. case RGB_S3TC_DXT1_Format:
  42602. case RGBA_S3TC_DXT1_Format:
  42603. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42604. case RGBA_S3TC_DXT3_Format:
  42605. case RGBA_S3TC_DXT5_Format:
  42606. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42607. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42608. case RGB_PVRTC_2BPPV1_Format:
  42609. case RGBA_PVRTC_2BPPV1_Format:
  42610. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42611. case RGB_PVRTC_4BPPV1_Format:
  42612. case RGBA_PVRTC_4BPPV1_Format:
  42613. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42614. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42615. case RGB_ETC1_Format:
  42616. case RGB_ETC2_Format:
  42617. case R11_EAC_Format:
  42618. case SIGNED_R11_EAC_Format:
  42619. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42620. case RGBA_ETC2_EAC_Format:
  42621. case RG11_EAC_Format:
  42622. case SIGNED_RG11_EAC_Format:
  42623. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42624. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42625. case RGBA_ASTC_4x4_Format:
  42626. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42627. case RGBA_ASTC_5x4_Format:
  42628. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42629. case RGBA_ASTC_5x5_Format:
  42630. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42631. case RGBA_ASTC_6x5_Format:
  42632. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42633. case RGBA_ASTC_6x6_Format:
  42634. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42635. case RGBA_ASTC_8x5_Format:
  42636. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42637. case RGBA_ASTC_8x6_Format:
  42638. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42639. case RGBA_ASTC_8x8_Format:
  42640. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42641. case RGBA_ASTC_10x5_Format:
  42642. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42643. case RGBA_ASTC_10x6_Format:
  42644. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42645. case RGBA_ASTC_10x8_Format:
  42646. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42647. case RGBA_ASTC_10x10_Format:
  42648. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42649. case RGBA_ASTC_12x10_Format:
  42650. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42651. case RGBA_ASTC_12x12_Format:
  42652. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42653. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42654. case RGBA_BPTC_Format:
  42655. case RGB_BPTC_SIGNED_Format:
  42656. case RGB_BPTC_UNSIGNED_Format:
  42657. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42658. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42659. case RED_RGTC1_Format:
  42660. case SIGNED_RED_RGTC1_Format:
  42661. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42662. case RED_GREEN_RGTC2_Format:
  42663. case SIGNED_RED_GREEN_RGTC2_Format:
  42664. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42665. }
  42666. throw new Error(
  42667. `Unable to determine texture byte length for ${format} format.`,
  42668. );
  42669. }
  42670. function getTextureTypeByteLength( type ) {
  42671. switch ( type ) {
  42672. case UnsignedByteType:
  42673. case ByteType:
  42674. return { byteLength: 1, components: 1 };
  42675. case UnsignedShortType:
  42676. case ShortType:
  42677. case HalfFloatType:
  42678. return { byteLength: 2, components: 1 };
  42679. case UnsignedShort4444Type:
  42680. case UnsignedShort5551Type:
  42681. return { byteLength: 2, components: 4 };
  42682. case UnsignedIntType:
  42683. case IntType:
  42684. case FloatType:
  42685. return { byteLength: 4, components: 1 };
  42686. case UnsignedInt5999Type:
  42687. case UnsignedInt101111Type:
  42688. return { byteLength: 4, components: 3 };
  42689. }
  42690. throw new Error( `Unknown texture type ${type}.` );
  42691. }
  42692. /**
  42693. * A class containing utility functions for textures.
  42694. *
  42695. * @hideconstructor
  42696. */
  42697. class TextureUtils {
  42698. /**
  42699. * Scales the texture as large as possible within its surface without cropping
  42700. * or stretching the texture. The method preserves the original aspect ratio of
  42701. * the texture. Akin to CSS `object-fit: contain`
  42702. *
  42703. * @param {Texture} texture - The texture.
  42704. * @param {number} aspect - The texture's aspect ratio.
  42705. * @return {Texture} The updated texture.
  42706. */
  42707. static contain( texture, aspect ) {
  42708. return contain( texture, aspect );
  42709. }
  42710. /**
  42711. * Scales the texture to the smallest possible size to fill the surface, leaving
  42712. * no empty space. The method preserves the original aspect ratio of the texture.
  42713. * Akin to CSS `object-fit: cover`.
  42714. *
  42715. * @param {Texture} texture - The texture.
  42716. * @param {number} aspect - The texture's aspect ratio.
  42717. * @return {Texture} The updated texture.
  42718. */
  42719. static cover( texture, aspect ) {
  42720. return cover( texture, aspect );
  42721. }
  42722. /**
  42723. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42724. *
  42725. * @param {Texture} texture - The texture.
  42726. * @return {Texture} The updated texture.
  42727. */
  42728. static fill( texture ) {
  42729. return fill( texture );
  42730. }
  42731. /**
  42732. * Determines how many bytes must be used to represent the texture.
  42733. *
  42734. * @param {number} width - The width of the texture.
  42735. * @param {number} height - The height of the texture.
  42736. * @param {number} format - The texture's format.
  42737. * @param {number} type - The texture's type.
  42738. * @return {number} The byte length.
  42739. */
  42740. static getByteLength( width, height, format, type ) {
  42741. return getByteLength( width, height, format, type );
  42742. }
  42743. }
  42744. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42745. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42746. revision: REVISION,
  42747. } } ) );
  42748. }
  42749. if ( typeof window !== 'undefined' ) {
  42750. if ( window.__THREE__ ) {
  42751. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42752. } else {
  42753. window.__THREE__ = REVISION;
  42754. }
  42755. }
  42756. function WebGLAnimation() {
  42757. let context = null;
  42758. let isAnimating = false;
  42759. let animationLoop = null;
  42760. let requestId = null;
  42761. function onAnimationFrame( time, frame ) {
  42762. animationLoop( time, frame );
  42763. requestId = context.requestAnimationFrame( onAnimationFrame );
  42764. }
  42765. return {
  42766. start: function () {
  42767. if ( isAnimating === true ) return;
  42768. if ( animationLoop === null ) return;
  42769. requestId = context.requestAnimationFrame( onAnimationFrame );
  42770. isAnimating = true;
  42771. },
  42772. stop: function () {
  42773. context.cancelAnimationFrame( requestId );
  42774. isAnimating = false;
  42775. },
  42776. setAnimationLoop: function ( callback ) {
  42777. animationLoop = callback;
  42778. },
  42779. setContext: function ( value ) {
  42780. context = value;
  42781. }
  42782. };
  42783. }
  42784. function WebGLAttributes( gl ) {
  42785. const buffers = new WeakMap();
  42786. function createBuffer( attribute, bufferType ) {
  42787. const array = attribute.array;
  42788. const usage = attribute.usage;
  42789. const size = array.byteLength;
  42790. const buffer = gl.createBuffer();
  42791. gl.bindBuffer( bufferType, buffer );
  42792. gl.bufferData( bufferType, array, usage );
  42793. attribute.onUploadCallback();
  42794. let type;
  42795. if ( array instanceof Float32Array ) {
  42796. type = gl.FLOAT;
  42797. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42798. type = gl.HALF_FLOAT;
  42799. } else if ( array instanceof Uint16Array ) {
  42800. if ( attribute.isFloat16BufferAttribute ) {
  42801. type = gl.HALF_FLOAT;
  42802. } else {
  42803. type = gl.UNSIGNED_SHORT;
  42804. }
  42805. } else if ( array instanceof Int16Array ) {
  42806. type = gl.SHORT;
  42807. } else if ( array instanceof Uint32Array ) {
  42808. type = gl.UNSIGNED_INT;
  42809. } else if ( array instanceof Int32Array ) {
  42810. type = gl.INT;
  42811. } else if ( array instanceof Int8Array ) {
  42812. type = gl.BYTE;
  42813. } else if ( array instanceof Uint8Array ) {
  42814. type = gl.UNSIGNED_BYTE;
  42815. } else if ( array instanceof Uint8ClampedArray ) {
  42816. type = gl.UNSIGNED_BYTE;
  42817. } else {
  42818. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42819. }
  42820. return {
  42821. buffer: buffer,
  42822. type: type,
  42823. bytesPerElement: array.BYTES_PER_ELEMENT,
  42824. version: attribute.version,
  42825. size: size
  42826. };
  42827. }
  42828. function updateBuffer( buffer, attribute, bufferType ) {
  42829. const array = attribute.array;
  42830. const updateRanges = attribute.updateRanges;
  42831. gl.bindBuffer( bufferType, buffer );
  42832. if ( updateRanges.length === 0 ) {
  42833. // Not using update ranges
  42834. gl.bufferSubData( bufferType, 0, array );
  42835. } else {
  42836. // Before applying update ranges, we merge any adjacent / overlapping
  42837. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42838. // to performance improvements for applications which make heavy use of
  42839. // update ranges. Likely due to GPU command overhead.
  42840. //
  42841. // Note that to reduce garbage collection between frames, we merge the
  42842. // update ranges in-place. This is safe because this method will clear the
  42843. // update ranges once updated.
  42844. updateRanges.sort( ( a, b ) => a.start - b.start );
  42845. // To merge the update ranges in-place, we work from left to right in the
  42846. // existing updateRanges array, merging ranges. This may result in a final
  42847. // array which is smaller than the original. This index tracks the last
  42848. // index representing a merged range, any data after this index can be
  42849. // trimmed once the merge algorithm is completed.
  42850. let mergeIndex = 0;
  42851. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42852. const previousRange = updateRanges[ mergeIndex ];
  42853. const range = updateRanges[ i ];
  42854. // We add one here to merge adjacent ranges. This is safe because ranges
  42855. // operate over positive integers.
  42856. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42857. previousRange.count = Math.max(
  42858. previousRange.count,
  42859. range.start + range.count - previousRange.start
  42860. );
  42861. } else {
  42862. ++ mergeIndex;
  42863. updateRanges[ mergeIndex ] = range;
  42864. }
  42865. }
  42866. // Trim the array to only contain the merged ranges.
  42867. updateRanges.length = mergeIndex + 1;
  42868. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42869. const range = updateRanges[ i ];
  42870. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42871. array, range.start, range.count );
  42872. }
  42873. attribute.clearUpdateRanges();
  42874. }
  42875. attribute.onUploadCallback();
  42876. }
  42877. //
  42878. function get( attribute ) {
  42879. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42880. return buffers.get( attribute );
  42881. }
  42882. function remove( attribute ) {
  42883. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42884. const data = buffers.get( attribute );
  42885. if ( data ) {
  42886. gl.deleteBuffer( data.buffer );
  42887. buffers.delete( attribute );
  42888. }
  42889. }
  42890. function update( attribute, bufferType ) {
  42891. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42892. if ( attribute.isGLBufferAttribute ) {
  42893. const cached = buffers.get( attribute );
  42894. if ( ! cached || cached.version < attribute.version ) {
  42895. buffers.set( attribute, {
  42896. buffer: attribute.buffer,
  42897. type: attribute.type,
  42898. bytesPerElement: attribute.elementSize,
  42899. version: attribute.version
  42900. } );
  42901. }
  42902. return;
  42903. }
  42904. const data = buffers.get( attribute );
  42905. if ( data === undefined ) {
  42906. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42907. } else if ( data.version < attribute.version ) {
  42908. if ( data.size !== attribute.array.byteLength ) {
  42909. throw new Error( 'THREE.WebGLAttributes: The size of the buffer attribute\'s array buffer does not match the original size. Resizing buffer attributes is not supported.' );
  42910. }
  42911. updateBuffer( data.buffer, attribute, bufferType );
  42912. data.version = attribute.version;
  42913. }
  42914. }
  42915. return {
  42916. get: get,
  42917. remove: remove,
  42918. update: update
  42919. };
  42920. }
  42921. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42922. var alphahash_pars_fragment = "#ifdef USE_ALPHAHASH\n\tconst float ALPHA_HASH_SCALE = 0.05;\n\tfloat hash2D( vec2 value ) {\n\t\treturn fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) );\n\t}\n\tfloat hash3D( vec3 value ) {\n\t\treturn hash2D( vec2( hash2D( value.xy ), value.z ) );\n\t}\n\tfloat getAlphaHashThreshold( vec3 position ) {\n\t\tfloat maxDeriv = max(\n\t\t\tlength( dFdx( position.xyz ) ),\n\t\t\tlength( dFdy( position.xyz ) )\n\t\t);\n\t\tfloat pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv );\n\t\tvec2 pixScales = vec2(\n\t\t\texp2( floor( log2( pixScale ) ) ),\n\t\t\texp2( ceil( log2( pixScale ) ) )\n\t\t);\n\t\tvec2 alpha = vec2(\n\t\t\thash3D( floor( pixScales.x * position.xyz ) ),\n\t\t\thash3D( floor( pixScales.y * position.xyz ) )\n\t\t);\n\t\tfloat lerpFactor = fract( log2( pixScale ) );\n\t\tfloat x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y;\n\t\tfloat a = min( lerpFactor, 1.0 - lerpFactor );\n\t\tvec3 cases = vec3(\n\t\t\tx * x / ( 2.0 * a * ( 1.0 - a ) ),\n\t\t\t( x - 0.5 * a ) / ( 1.0 - a ),\n\t\t\t1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) )\n\t\t);\n\t\tfloat threshold = ( x < ( 1.0 - a ) )\n\t\t\t? ( ( x < a ) ? cases.x : cases.y )\n\t\t\t: cases.z;\n\t\treturn clamp( threshold , 1.0e-6, 1.0 );\n\t}\n#endif";
  42923. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42924. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42925. var alphatest_fragment = "#ifdef USE_ALPHATEST\n\t#ifdef ALPHA_TO_COVERAGE\n\tdiffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a );\n\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\tif ( diffuseColor.a < alphaTest ) discard;\n\t#endif\n#endif";
  42926. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42927. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_CLEARCOAT ) \n\t\tclearcoatSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_SHEEN ) \n\t\tsheenSpecularIndirect *= ambientOcclusion;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD )\n\t\tfloat dotNV = saturate( dot( geometryNormal, geometryViewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness );\n\t#endif\n#endif";
  42928. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42929. var batching_pars_vertex = "#ifdef USE_BATCHING\n\t#if ! defined( GL_ANGLE_multi_draw )\n\t#define gl_DrawID _gl_DrawID\n\tuniform int _gl_DrawID;\n\t#endif\n\tuniform highp sampler2D batchingTexture;\n\tuniform highp usampler2D batchingIdTexture;\n\tmat4 getBatchingMatrix( const in float i ) {\n\t\tint size = textureSize( batchingTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n\tfloat getIndirectIndex( const in int i ) {\n\t\tint size = textureSize( batchingIdTexture, 0 ).x;\n\t\tint x = i % size;\n\t\tint y = i / size;\n\t\treturn float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r );\n\t}\n#endif\n#ifdef USE_BATCHING_COLOR\n\tuniform sampler2D batchingColorTexture;\n\tvec3 getBatchingColor( const in float i ) {\n\t\tint size = textureSize( batchingColorTexture, 0 ).x;\n\t\tint j = int( i );\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\treturn texelFetch( batchingColorTexture, ivec2( x, y ), 0 ).rgb;\n\t}\n#endif";
  42930. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42931. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42932. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42933. var bsdfs = "float G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, 1.0, dotVH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n} // validated";
  42934. var iridescence_fragment = "#ifdef USE_IRIDESCENCE\n\tconst mat3 XYZ_TO_REC709 = mat3(\n\t\t 3.2404542, -0.9692660, 0.0556434,\n\t\t-1.5371385, 1.8760108, -0.2040259,\n\t\t-0.4985314, 0.0415560, 1.0572252\n\t);\n\tvec3 Fresnel0ToIor( vec3 fresnel0 ) {\n\t\tvec3 sqrtF0 = sqrt( fresnel0 );\n\t\treturn ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 );\n\t}\n\tvec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) );\n\t}\n\tfloat IorToFresnel0( float transmittedIor, float incidentIor ) {\n\t\treturn pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor ));\n\t}\n\tvec3 evalSensitivity( float OPD, vec3 shift ) {\n\t\tfloat phase = 2.0 * PI * OPD * 1.0e-9;\n\t\tvec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );\n\t\tvec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );\n\t\tvec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );\n\t\tvec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var );\n\t\txyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) );\n\t\txyz /= 1.0685e-7;\n\t\tvec3 rgb = XYZ_TO_REC709 * xyz;\n\t\treturn rgb;\n\t}\n\tvec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) {\n\t\tvec3 I;\n\t\tfloat iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );\n\t\tfloat sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) );\n\t\tfloat cosTheta2Sq = 1.0 - sinTheta2Sq;\n\t\tif ( cosTheta2Sq < 0.0 ) {\n\t\t\treturn vec3( 1.0 );\n\t\t}\n\t\tfloat cosTheta2 = sqrt( cosTheta2Sq );\n\t\tfloat R0 = IorToFresnel0( iridescenceIOR, outsideIOR );\n\t\tfloat R12 = F_Schlick( R0, 1.0, cosTheta1 );\n\t\tfloat T121 = 1.0 - R12;\n\t\tfloat phi12 = 0.0;\n\t\tif ( iridescenceIOR < outsideIOR ) phi12 = PI;\n\t\tfloat phi21 = PI - phi12;\n\t\tvec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) );\t\tvec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR );\n\t\tvec3 R23 = F_Schlick( R1, 1.0, cosTheta2 );\n\t\tvec3 phi23 = vec3( 0.0 );\n\t\tif ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI;\n\t\tif ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI;\n\t\tif ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI;\n\t\tfloat OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2;\n\t\tvec3 phi = vec3( phi21 ) + phi23;\n\t\tvec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 );\n\t\tvec3 r123 = sqrt( R123 );\n\t\tvec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 );\n\t\tvec3 C0 = R12 + Rs;\n\t\tI = C0;\n\t\tvec3 Cm = Rs - T121;\n\t\tfor ( int m = 1; m <= 2; ++ m ) {\n\t\t\tCm *= r123;\n\t\t\tvec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi );\n\t\t\tI += Cm * Sm;\n\t\t}\n\t\treturn max( I, vec3( 0.0 ) );\n\t}\n#endif";
  42935. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vBumpMapUv );\n\t\tvec2 dSTdy = dFdy( vBumpMapUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) {\n\t\tvec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) );\n\t\tvec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 ) * faceDirection;\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif";
  42936. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvec4 plane;\n\t#ifdef ALPHA_TO_COVERAGE\n\t\tfloat distanceToPlane, distanceGradient;\n\t\tfloat clipOpacity = 1.0;\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\tclipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\tif ( clipOpacity == 0.0 ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tfloat unionClipOpacity = 1.0;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tdistanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w;\n\t\t\t\tdistanceGradient = fwidth( distanceToPlane ) / 2.0;\n\t\t\t\tunionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane );\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tclipOpacity *= 1.0 - unionClipOpacity;\n\t\t#endif\n\t\tdiffuseColor.a *= clipOpacity;\n\t\tif ( diffuseColor.a == 0.0 ) discard;\n\t#else\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) {\n\t\t\tplane = clippingPlanes[ i ];\n\t\t\tif ( dot( vClipPosition, plane.xyz ) > plane.w ) discard;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\t\tbool clipped = true;\n\t\t\t#pragma unroll_loop_start\n\t\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) {\n\t\t\t\tplane = clippingPlanes[ i ];\n\t\t\t\tclipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t\t}\n\t\t\t#pragma unroll_loop_end\n\t\t\tif ( clipped ) discard;\n\t\t#endif\n\t#endif\n#endif";
  42937. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42938. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42939. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42940. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42941. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42942. var color_pars_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42943. var color_vertex = "#if defined( USE_COLOR_ALPHA )\n\tvColor = vec4( 1.0 );\n#elif defined( USE_COLOR ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR )\n\tvColor = vec3( 1.0 );\n#endif\n#ifdef USE_COLOR\n\tvColor *= color;\n#endif\n#ifdef USE_INSTANCING_COLOR\n\tvColor.xyz *= instanceColor.xyz;\n#endif\n#ifdef USE_BATCHING_COLOR\n\tvec3 batchingColor = getBatchingColor( getIndirectIndex( gl_DrawID ) );\n\tvColor.xyz *= batchingColor.xyz;\n#endif";
  42944. var common = "#define PI 3.141592653589793\n#define PI2 6.283185307179586\n#define PI_HALF 1.5707963267948966\n#define RECIPROCAL_PI 0.3183098861837907\n#define RECIPROCAL_PI2 0.15915494309189535\n#define EPSILON 1e-6\n#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\n#define whiteComplement( a ) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nvec3 pow2( const in vec3 x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); }\nfloat average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract( sin( sn ) * c );\n}\n#ifdef HIGH_PRECISION\n\tfloat precisionSafeLength( vec3 v ) { return length( v ); }\n#else\n\tfloat precisionSafeLength( vec3 v ) {\n\t\tfloat maxComponent = max3( abs( v ) );\n\t\treturn length( v / maxComponent ) * maxComponent;\n\t}\n#endif\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\n#ifdef USE_ALPHAHASH\n\tvarying vec3 vPosition;\n#endif\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nbool isPerspectiveMatrix( mat4 m ) {\n\treturn m[ 2 ][ 3 ] == - 1.0;\n}\nvec2 equirectUv( in vec3 dir ) {\n\tfloat u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5;\n\tfloat v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\n\treturn vec2( u, v );\n}\nvec3 BRDF_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n}\nfloat F_Schlick( const in float f0, const in float f90, const in float dotVH ) {\n\tfloat fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH );\n\treturn f0 * ( 1.0 - fresnel ) + ( f90 * fresnel );\n} // validated";
  42945. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n\t#define cubeUV_minMipLevel 4.0\n\t#define cubeUV_minTileSize 16.0\n\tfloat getFace( vec3 direction ) {\n\t\tvec3 absDirection = abs( direction );\n\t\tfloat face = - 1.0;\n\t\tif ( absDirection.x > absDirection.z ) {\n\t\t\tif ( absDirection.x > absDirection.y )\n\t\t\t\tface = direction.x > 0.0 ? 0.0 : 3.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t} else {\n\t\t\tif ( absDirection.z > absDirection.y )\n\t\t\t\tface = direction.z > 0.0 ? 2.0 : 5.0;\n\t\t\telse\n\t\t\t\tface = direction.y > 0.0 ? 1.0 : 4.0;\n\t\t}\n\t\treturn face;\n\t}\n\tvec2 getUV( vec3 direction, float face ) {\n\t\tvec2 uv;\n\t\tif ( face == 0.0 ) {\n\t\t\tuv = vec2( direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 1.0 ) {\n\t\t\tuv = vec2( - direction.x, - direction.z ) / abs( direction.y );\n\t\t} else if ( face == 2.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.y ) / abs( direction.z );\n\t\t} else if ( face == 3.0 ) {\n\t\t\tuv = vec2( - direction.z, direction.y ) / abs( direction.x );\n\t\t} else if ( face == 4.0 ) {\n\t\t\tuv = vec2( - direction.x, direction.z ) / abs( direction.y );\n\t\t} else {\n\t\t\tuv = vec2( direction.x, direction.y ) / abs( direction.z );\n\t\t}\n\t\treturn 0.5 * ( uv + 1.0 );\n\t}\n\tvec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) {\n\t\tfloat face = getFace( direction );\n\t\tfloat filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 );\n\t\tmipInt = max( mipInt, cubeUV_minMipLevel );\n\t\tfloat faceSize = exp2( mipInt );\n\t\thighp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0;\n\t\tif ( face > 2.0 ) {\n\t\t\tuv.y += faceSize;\n\t\t\tface -= 3.0;\n\t\t}\n\t\tuv.x += face * faceSize;\n\t\tuv.x += filterInt * 3.0 * cubeUV_minTileSize;\n\t\tuv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize );\n\t\tuv.x *= CUBEUV_TEXEL_WIDTH;\n\t\tuv.y *= CUBEUV_TEXEL_HEIGHT;\n\t\t#ifdef texture2DGradEXT\n\t\t\treturn texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb;\n\t\t#else\n\t\t\treturn texture2D( envMap, uv ).rgb;\n\t\t#endif\n\t}\n\t#define cubeUV_r0 1.0\n\t#define cubeUV_m0 - 2.0\n\t#define cubeUV_r1 0.8\n\t#define cubeUV_m1 - 1.0\n\t#define cubeUV_r4 0.4\n\t#define cubeUV_m4 2.0\n\t#define cubeUV_r5 0.305\n\t#define cubeUV_m5 3.0\n\t#define cubeUV_r6 0.21\n\t#define cubeUV_m6 4.0\n\tfloat roughnessToMip( float roughness ) {\n\t\tfloat mip = 0.0;\n\t\tif ( roughness >= cubeUV_r1 ) {\n\t\t\tmip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0;\n\t\t} else if ( roughness >= cubeUV_r4 ) {\n\t\t\tmip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1;\n\t\t} else if ( roughness >= cubeUV_r5 ) {\n\t\t\tmip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4;\n\t\t} else if ( roughness >= cubeUV_r6 ) {\n\t\t\tmip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5;\n\t\t} else {\n\t\t\tmip = - 2.0 * log2( 1.16 * roughness );\t\t}\n\t\treturn mip;\n\t}\n\tvec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) {\n\t\tfloat mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );\n\t\tfloat mipF = fract( mip );\n\t\tfloat mipInt = floor( mip );\n\t\tvec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt );\n\t\tif ( mipF == 0.0 ) {\n\t\t\treturn vec4( color0, 1.0 );\n\t\t} else {\n\t\t\tvec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 );\n\t\t\treturn vec4( mix( color0, color1, mipF ), 1.0 );\n\t\t}\n\t}\n#endif";
  42946. var defaultnormal_vertex = "vec3 transformedNormal = objectNormal;\n#ifdef USE_TANGENT\n\tvec3 transformedTangent = objectTangent;\n#endif\n#ifdef USE_BATCHING\n\tmat3 bm = mat3( batchingMatrix );\n\ttransformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) );\n\ttransformedNormal = bm * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = bm * transformedTangent;\n\t#endif\n#endif\n#ifdef USE_INSTANCING\n\tmat3 im = mat3( instanceMatrix );\n\ttransformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) );\n\ttransformedNormal = im * transformedNormal;\n\t#ifdef USE_TANGENT\n\t\ttransformedTangent = im * transformedTangent;\n\t#endif\n#endif\ntransformedNormal = normalMatrix * transformedNormal;\n#ifdef FLIP_SIDED\n\ttransformedNormal = - transformedNormal;\n#endif\n#ifdef USE_TANGENT\n\ttransformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz;\n\t#ifdef FLIP_SIDED\n\t\ttransformedTangent = - transformedTangent;\n\t#endif\n#endif";
  42947. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42948. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42949. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE_EMISSIVE\n\t\temissiveColor = sRGBTransferEOTF( emissiveColor );\n\t#endif\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif";
  42950. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42951. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42952. var colorspace_pars_fragment = "vec4 LinearTransferOETF( in vec4 value ) {\n\treturn value;\n}\nvec4 sRGBTransferEOTF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a );\n}\nvec4 sRGBTransferOETF( in vec4 value ) {\n\treturn vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a );\n}";
  42953. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#ifdef ENV_WORLDPOS\n\t\tvec3 cameraToFrag;\n\t\tif ( isOrthographic ) {\n\t\t\tcameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) );\n\t\t} else {\n\t\t\tcameraToFrag = normalize( vWorldPosition - cameraPosition );\n\t\t}\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToFrag, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif";
  42954. var envmap_common_pars_fragment = "#ifdef USE_ENVMAP\n\tuniform float envMapIntensity;\n\tuniform float flipEnvMap;\n\tuniform mat3 envMapRotation;\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n#endif";
  42955. 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";
  42956. 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";
  42957. 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";
  42958. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42959. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42960. 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";
  42961. 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";
  42962. 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}";
  42963. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42964. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42965. var lights_lambert_pars_fragment = "varying vec3 vViewPosition;\nstruct LambertMaterial {\n\tvec3 diffuseColor;\n\tfloat specularStrength;\n};\nvoid RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Lambert\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Lambert";
  42966. var lights_pars_begin = "uniform bool receiveShadow;\nuniform vec3 ambientLightColor;\n#if defined( USE_LIGHT_PROBES )\n\tuniform vec3 lightProbe[ 9 ];\n#endif\nvec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) {\n\tfloat x = normal.x, y = normal.y, z = normal.z;\n\tvec3 result = shCoefficients[ 0 ] * 0.886227;\n\tresult += shCoefficients[ 1 ] * 2.0 * 0.511664 * y;\n\tresult += shCoefficients[ 2 ] * 2.0 * 0.511664 * z;\n\tresult += shCoefficients[ 3 ] * 2.0 * 0.511664 * x;\n\tresult += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y;\n\tresult += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z;\n\tresult += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 );\n\tresult += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z;\n\tresult += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y );\n\treturn result;\n}\nvec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) {\n\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\tvec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe );\n\treturn irradiance;\n}\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\treturn irradiance;\n}\nfloat getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\tif ( cutoffDistance > 0.0 ) {\n\t\tdistanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t}\n\treturn distanceFalloff;\n}\nfloat getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) {\n\treturn smoothstep( coneCosine, penumbraCosine, angleCosine );\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) {\n\t\tlight.color = directionalLight.color;\n\t\tlight.direction = directionalLight.direction;\n\t\tlight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = pointLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tlight.color = pointLight.color;\n\t\tlight.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay );\n\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) {\n\t\tvec3 lVector = spotLight.position - geometryPosition;\n\t\tlight.direction = normalize( lVector );\n\t\tfloat angleCos = dot( light.direction, spotLight.direction );\n\t\tfloat spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\tif ( spotAttenuation > 0.0 ) {\n\t\t\tfloat lightDistance = length( lVector );\n\t\t\tlight.color = spotLight.color * spotAttenuation;\n\t\t\tlight.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tlight.visible = ( light.color != vec3( 0.0 ) );\n\t\t} else {\n\t\t\tlight.color = vec3( 0.0 );\n\t\t\tlight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltc_1;\tuniform sampler2D ltc_2;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) {\n\t\tfloat dotNL = dot( normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\treturn irradiance;\n\t}\n#endif";
  42967. var envmap_physical_pars_fragment = "#ifdef USE_ENVMAP\n\tvec3 getIBLIrradiance( const in vec3 normal ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 );\n\t\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\tvec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) {\n\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\tvec3 reflectVec = reflect( - viewDir, normal );\n\t\t\treflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) );\n\t\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\t\tvec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness );\n\t\t\treturn envMapColor.rgb * envMapIntensity;\n\t\t#else\n\t\t\treturn vec3( 0.0 );\n\t\t#endif\n\t}\n\t#ifdef USE_ANISOTROPY\n\t\tvec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) {\n\t\t\t#ifdef ENVMAP_TYPE_CUBE_UV\n\t\t\t\tvec3 bentNormal = cross( bitangent, viewDir );\n\t\t\t\tbentNormal = normalize( cross( bentNormal, bitangent ) );\n\t\t\t\tbentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) );\n\t\t\t\treturn getIBLRadiance( viewDir, bentNormal, roughness );\n\t\t\t#else\n\t\t\t\treturn vec3( 0.0 );\n\t\t\t#endif\n\t\t}\n\t#endif\n#endif";
  42968. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42969. var lights_toon_pars_fragment = "varying vec3 vViewPosition;\nstruct ToonMaterial {\n\tvec3 diffuseColor;\n};\nvoid RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_Toon\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Toon";
  42970. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  42971. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\nstruct BlinnPhongMaterial {\n\tvec3 diffuseColor;\n\tvec3 specularColor;\n\tfloat specularShininess;\n\tfloat specularStrength;\n};\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong";
  42972. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.metalness = metalnessFactor;\nvec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) );\nfloat geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z );\nmaterial.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness;\nmaterial.roughness = min( material.roughness, 1.0 );\n#ifdef IOR\n\tmaterial.ior = ior;\n\t#ifdef USE_SPECULAR\n\t\tfloat specularIntensityFactor = specularIntensity;\n\t\tvec3 specularColorFactor = specularColor;\n\t\t#ifdef USE_SPECULAR_COLORMAP\n\t\t\tspecularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb;\n\t\t#endif\n\t\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\t\tspecularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a;\n\t\t#endif\n\t\tmaterial.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor );\n\t#else\n\t\tfloat specularIntensityFactor = 1.0;\n\t\tvec3 specularColorFactor = vec3( 1.0 );\n\t\tmaterial.specularF90 = 1.0;\n\t#endif\n\tmaterial.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor;\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = vec3( 0.04 );\n\tmaterial.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor );\n\tmaterial.specularF90 = 1.0;\n#endif\n#ifdef USE_CLEARCOAT\n\tmaterial.clearcoat = clearcoat;\n\tmaterial.clearcoatRoughness = clearcoatRoughness;\n\tmaterial.clearcoatF0 = vec3( 0.04 );\n\tmaterial.clearcoatF90 = 1.0;\n\t#ifdef USE_CLEARCOATMAP\n\t\tmaterial.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x;\n\t#endif\n\t#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\t\tmaterial.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y;\n\t#endif\n\tmaterial.clearcoat = saturate( material.clearcoat );\tmaterial.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 );\n\tmaterial.clearcoatRoughness += geometryRoughness;\n\tmaterial.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 );\n#endif\n#ifdef USE_DISPERSION\n\tmaterial.dispersion = dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tmaterial.iridescence = iridescence;\n\tmaterial.iridescenceIOR = iridescenceIOR;\n\t#ifdef USE_IRIDESCENCEMAP\n\t\tmaterial.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r;\n\t#endif\n\t#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\t\tmaterial.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum;\n\t#else\n\t\tmaterial.iridescenceThickness = iridescenceThicknessMaximum;\n\t#endif\n#endif\n#ifdef USE_SHEEN\n\tmaterial.sheenColor = sheenColor;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tmaterial.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb;\n\t#endif\n\tmaterial.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  42973. var lights_physical_pars_fragment = "uniform sampler2D dfgLUT;\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tvec3 diffuseContribution;\n\tvec3 specularColor;\n\tvec3 specularColorBlended;\n\tfloat roughness;\n\tfloat metalness;\n\tfloat specularF90;\n\tfloat dispersion;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat clearcoat;\n\t\tfloat clearcoatRoughness;\n\t\tvec3 clearcoatF0;\n\t\tfloat clearcoatF90;\n\t#endif\n\t#ifdef USE_IRIDESCENCE\n\t\tfloat iridescence;\n\t\tfloat iridescenceIOR;\n\t\tfloat iridescenceThickness;\n\t\tvec3 iridescenceFresnel;\n\t\tvec3 iridescenceF0;\n\t\tvec3 iridescenceFresnelDielectric;\n\t\tvec3 iridescenceFresnelMetallic;\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tvec3 sheenColor;\n\t\tfloat sheenRoughness;\n\t#endif\n\t#ifdef IOR\n\t\tfloat ior;\n\t#endif\n\t#ifdef USE_TRANSMISSION\n\t\tfloat transmission;\n\t\tfloat transmissionAlpha;\n\t\tfloat thickness;\n\t\tfloat attenuationDistance;\n\t\tvec3 attenuationColor;\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat anisotropy;\n\t\tfloat alphaT;\n\t\tvec3 anisotropyT;\n\t\tvec3 anisotropyB;\n\t#endif\n};\nvec3 clearcoatSpecularDirect = vec3( 0.0 );\nvec3 clearcoatSpecularIndirect = vec3( 0.0 );\nvec3 sheenSpecularDirect = vec3( 0.0 );\nvec3 sheenSpecularIndirect = vec3(0.0 );\nvec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) {\n float x = clamp( 1.0 - dotVH, 0.0, 1.0 );\n float x2 = x * x;\n float x5 = clamp( x * x2 * x2, 0.0, 0.9999 );\n return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 );\n}\nfloat V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\n#ifdef USE_ANISOTROPY\n\tfloat V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) {\n\t\tfloat gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) );\n\t\tfloat gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) );\n\t\tfloat v = 0.5 / ( gv + gl );\n\t\treturn v;\n\t}\n\tfloat D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) {\n\t\tfloat a2 = alphaT * alphaB;\n\t\thighp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH );\n\t\thighp float v2 = dot( v, v );\n\t\tfloat w2 = a2 / v2;\n\t\treturn RECIPROCAL_PI * a2 * pow2 ( w2 );\n\t}\n#endif\n#ifdef USE_CLEARCOAT\n\tvec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) {\n\t\tvec3 f0 = material.clearcoatF0;\n\t\tfloat f90 = material.clearcoatF90;\n\t\tfloat roughness = material.clearcoatRoughness;\n\t\tfloat alpha = pow2( roughness );\n\t\tvec3 halfDir = normalize( lightDir + viewDir );\n\t\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\t\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\t\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\t\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\t\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t\treturn F * ( V * D );\n\t}\n#endif\nvec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 f0 = material.specularColorBlended;\n\tfloat f90 = material.specularF90;\n\tfloat roughness = material.roughness;\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat dotVH = saturate( dot( viewDir, halfDir ) );\n\tvec3 F = F_Schlick( f0, f90, dotVH );\n\t#ifdef USE_IRIDESCENCE\n\t\tF = mix( F, material.iridescenceFresnel, material.iridescence );\n\t#endif\n\t#ifdef USE_ANISOTROPY\n\t\tfloat dotTL = dot( material.anisotropyT, lightDir );\n\t\tfloat dotTV = dot( material.anisotropyT, viewDir );\n\t\tfloat dotTH = dot( material.anisotropyT, halfDir );\n\t\tfloat dotBL = dot( material.anisotropyB, lightDir );\n\t\tfloat dotBV = dot( material.anisotropyB, viewDir );\n\t\tfloat dotBH = dot( material.anisotropyB, halfDir );\n\t\tfloat V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL );\n\t\tfloat D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH );\n\t#else\n\t\tfloat V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\t\tfloat D = D_GGX( alpha, dotNH );\n\t#endif\n\treturn F * ( V * D );\n}\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\n\tfloat dotNV = saturate( dot( N, V ) );\n\tvec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\n\tfloat l = length( f );\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\n}\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\n\tfloat x = dot( v1, v2 );\n\tfloat y = abs( x );\n\tfloat a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y;\n\tfloat b = 3.4175940 + ( 4.1616724 + y ) * y;\n\tfloat v = a / b;\n\tfloat theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v;\n\treturn cross( v1, v2 ) * theta_sintheta;\n}\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\n\tvec3 lightNormal = cross( v1, v2 );\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\n\tvec3 T1, T2;\n\tT1 = normalize( V - N * dot( V, N ) );\n\tT2 = - cross( N, T1 );\n\tmat3 mat = mInv * transpose( mat3( T1, T2, N ) );\n\tvec3 coords[ 4 ];\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\n\tvec3 vectorFormFactor = vec3( 0.0 );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\n\tfloat result = LTC_ClippedSphereFormFactor( vectorFormFactor );\n\treturn vec3( result );\n}\n#if defined( USE_SHEEN )\nfloat D_Charlie( float roughness, float dotNH ) {\n\tfloat alpha = pow2( roughness );\n\tfloat invAlpha = 1.0 / alpha;\n\tfloat cos2h = dotNH * dotNH;\n\tfloat sin2h = max( 1.0 - cos2h, 0.0078125 );\n\treturn ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI );\n}\nfloat V_Neubelt( float dotNV, float dotNL ) {\n\treturn saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) );\n}\nvec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) {\n\tvec3 halfDir = normalize( lightDir + viewDir );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat dotNH = saturate( dot( normal, halfDir ) );\n\tfloat D = D_Charlie( sheenRoughness, dotNH );\n\tfloat V = V_Neubelt( dotNV, dotNL );\n\treturn sheenColor * ( D * V );\n}\n#endif\nfloat IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tfloat r2 = roughness * roughness;\n\tfloat rInv = 1.0 / ( roughness + 0.1 );\n\tfloat a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv;\n\tfloat b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv;\n\tfloat DG = exp( a * dotNV + b );\n\treturn saturate( DG );\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg;\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}\nvec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) {\n\tvec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );\n\tfloat dotNL = saturate( dot( normal, lightDir ) );\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg;\n\tvec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg;\n\tvec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y;\n\tvec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y;\n\tfloat Ess_V = dfgV.x + dfgV.y;\n\tfloat Ess_L = dfgL.x + dfgL.y;\n\tfloat Ems_V = 1.0 - Ess_V;\n\tfloat Ems_L = 1.0 - Ess_L;\n\tvec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619;\n\tvec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON );\n\tfloat compensationFactor = Ems_V * Ems_L;\n\tvec3 multiScatter = Fms * compensationFactor;\n\treturn singleScatter + multiScatter;\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t\tvec3 normal = geometryNormal;\n\t\tvec3 viewDir = geometryViewDir;\n\t\tvec3 position = geometryPosition;\n\t\tvec3 lightPos = rectAreaLight.position;\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\n\t\tvec3 lightColor = rectAreaLight.color;\n\t\tfloat roughness = material.roughness;\n\t\tvec3 rectCoords[ 4 ];\n\t\trectCoords[ 0 ] = lightPos + halfWidth - halfHeight;\t\trectCoords[ 1 ] = lightPos - halfWidth - halfHeight;\n\t\trectCoords[ 2 ] = lightPos - halfWidth + halfHeight;\n\t\trectCoords[ 3 ] = lightPos + halfWidth + halfHeight;\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\n\t\tvec4 t1 = texture2D( ltc_1, uv );\n\t\tvec4 t2 = texture2D( ltc_2, uv );\n\t\tmat3 mInv = mat3(\n\t\t\tvec3( t1.x, 0, t1.y ),\n\t\t\tvec3( 0, 1, 0 ),\n\t\t\tvec3( t1.z, 0, t1.w )\n\t\t);\n\t\tvec3 fresnel = ( material.specularColorBlended * t2.x + ( vec3( 1.0 ) - material.specularColorBlended ) * t2.y );\n\t\treflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords );\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords );\n\t}\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometryNormal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) );\n\t\tvec3 ccIrradiance = dotNLcc * directLight.color;\n\t\tclearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material );\n\t#endif\n\t#ifdef USE_SHEEN\n \n \t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\n \n \t\tfloat sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n \t\tfloat sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness );\n \n \t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL );\n \n \t\tirradiance *= sheenEnergyComp;\n \n \t#endif\n\treflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material );\n\treflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tvec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution );\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tdiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectDiffuse += diffuse;\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI;\n \t#endif\n\tvec3 singleScatteringDielectric = vec3( 0.0 );\n\tvec3 multiScatteringDielectric = vec3( 0.0 );\n\tvec3 singleScatteringMetallic = vec3( 0.0 );\n\tvec3 multiScatteringMetallic = vec3( 0.0 );\n\t#ifdef USE_IRIDESCENCE\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#else\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric );\n\t\tcomputeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic );\n\t#endif\n\tvec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness );\n\tvec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness );\n\tvec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric;\n\tvec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric );\n\tvec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI;\n\tvec3 indirectSpecular = radiance * singleScattering;\n\tindirectSpecular += multiScattering * cosineWeightedIrradiance;\n\tvec3 indirectDiffuse = diffuse * cosineWeightedIrradiance;\n\t#ifdef USE_SHEEN\n\t\tfloat sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t\tfloat sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo;\n\t\tindirectSpecular *= sheenEnergyComp;\n\t\tindirectDiffuse *= sheenEnergyComp;\n\t#endif\n\treflectedLight.indirectSpecular += indirectSpecular;\n\treflectedLight.indirectDiffuse += indirectDiffuse;\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}";
  42974. var lights_fragment_begin = "\nvec3 geometryPosition = - vViewPosition;\nvec3 geometryNormal = normal;\nvec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition );\nvec3 geometryClearcoatNormal = vec3( 0.0 );\n#ifdef USE_CLEARCOAT\n\tgeometryClearcoatNormal = clearcoatNormal;\n#endif\n#ifdef USE_IRIDESCENCE\n\tfloat dotNVi = saturate( dot( normal, geometryViewDir ) );\n\tif ( material.iridescenceThickness == 0.0 ) {\n\t\tmaterial.iridescence = 0.0;\n\t} else {\n\t\tmaterial.iridescence = saturate( material.iridescence );\n\t}\n\tif ( material.iridescence > 0.0 ) {\n\t\tmaterial.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor );\n\t\tmaterial.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor );\n\t\tmaterial.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness );\n\t\tmaterial.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi );\n\t}\n#endif\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0\n\tPointLightShadow pointLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointLightInfo( pointLight, geometryPosition, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\t\tpointLightShadow = pointLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tvec4 spotColor;\n\tvec3 spotLightCoord;\n\tbool inSpotLightMap;\n\t#if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotLightInfo( spotLight, geometryPosition, directLight );\n\t\t#if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX\n\t\t#elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t#define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS\n\t\t#else\n\t\t#define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS )\n\t\t#endif\n\t\t#if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS )\n\t\t\tspotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w;\n\t\t\tinSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) );\n\t\t\tspotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy );\n\t\t\tdirectLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color;\n\t\t#endif\n\t\t#undef SPOT_LIGHT_MAP_INDEX\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\tspotLightShadow = spotLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\t#if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLightShadow;\n\t#endif\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalLightInfo( directionalLight, directLight );\n\t\t#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )\n\t\tdirectionalLightShadow = directionalLightShadows[ i ];\n\t\tdirectLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n\t}\n\t#pragma unroll_loop_end\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 iblIrradiance = vec3( 0.0 );\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#if defined( USE_LIGHT_PROBES )\n\t\tirradiance += getLightProbeIrradiance( lightProbe, geometryNormal );\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal );\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if defined( RE_IndirectSpecular )\n\tvec3 radiance = vec3( 0.0 );\n\tvec3 clearcoatRadiance = vec3( 0.0 );\n#endif";
  42975. var lights_fragment_maps = "#if defined( RE_IndirectDiffuse )\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\tvec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity;\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( STANDARD ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t\tiblIrradiance += getIBLIrradiance( geometryNormal );\n\t#endif\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\t#ifdef USE_ANISOTROPY\n\t\tradiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy );\n\t#else\n\t\tradiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness );\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness );\n\t#endif\n#endif";
  42976. var lights_fragment_end = "#if defined( RE_IndirectDiffuse )\n\tRE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif\n#if defined( RE_IndirectSpecular )\n\tRE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight );\n#endif";
  42977. var logdepthbuf_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tgl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5;\n#endif";
  42978. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42979. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42980. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  42981. var map_fragment = "#ifdef USE_MAP\n\tvec4 sampledDiffuseColor = texture2D( map, vMapUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\tsampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor );\n\t#endif\n\tdiffuseColor *= sampledDiffuseColor;\n#endif";
  42982. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  42983. var map_particle_fragment = "#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t#if defined( USE_POINTS_UV )\n\t\tvec2 uv = vUv;\n\t#else\n\t\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tdiffuseColor *= texture2D( map, uv );\n#endif\n#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, uv ).g;\n#endif";
  42984. var map_particle_pars_fragment = "#if defined( USE_POINTS_UV )\n\tvarying vec2 vUv;\n#else\n\t#if defined( USE_MAP ) || defined( USE_ALPHAMAP )\n\t\tuniform mat3 uvTransform;\n\t#endif\n#endif\n#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42985. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  42986. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  42987. var morphinstance_vertex = "#ifdef USE_INSTANCING_MORPH\n\tfloat morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\tfloat morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tmorphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r;\n\t}\n#endif";
  42988. var morphcolor_vertex = "#if defined( USE_MORPHCOLORS )\n\tvColor *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\t#if defined( USE_COLOR_ALPHA )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ];\n\t\t#elif defined( USE_COLOR )\n\t\t\tif ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ];\n\t\t#endif\n\t}\n#endif";
  42989. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  42990. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_INSTANCING_MORPH\n\t\tuniform float morphTargetBaseInfluence;\n\t\tuniform float morphTargetInfluences[ MORPHTARGETS_COUNT ];\n\t#endif\n\tuniform sampler2DArray morphTargetsTexture;\n\tuniform ivec2 morphTargetsTextureSize;\n\tvec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) {\n\t\tint texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset;\n\t\tint y = texelIndex / morphTargetsTextureSize.x;\n\t\tint x = texelIndex - y * morphTargetsTextureSize.x;\n\t\tivec3 morphUV = ivec3( x, y, morphTargetIndex );\n\t\treturn texelFetch( morphTargetsTexture, morphUV, 0 );\n\t}\n#endif";
  42991. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed *= morphTargetBaseInfluence;\n\tfor ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) {\n\t\tif ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ];\n\t}\n#endif";
  42992. var normal_fragment_begin = "float faceDirection = gl_FrontFacing ? 1.0 : - 1.0;\n#ifdef FLAT_SHADED\n\tvec3 fdx = dFdx( vViewPosition );\n\tvec3 fdy = dFdy( vViewPosition );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal );\n\t#ifdef DOUBLE_SIDED\n\t\tnormal *= faceDirection;\n\t#endif\n#endif\n#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY )\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn = getTangentFrame( - vViewPosition, normal,\n\t\t#if defined( USE_NORMALMAP )\n\t\t\tvNormalMapUv\n\t\t#elif defined( USE_CLEARCOAT_NORMALMAP )\n\t\t\tvClearcoatNormalMapUv\n\t\t#else\n\t\t\tvUv\n\t\t#endif\n\t\t);\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn[0] *= faceDirection;\n\t\ttbn[1] *= faceDirection;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\t#ifdef USE_TANGENT\n\t\tmat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal );\n\t#else\n\t\tmat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv );\n\t#endif\n\t#if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED )\n\t\ttbn2[0] *= faceDirection;\n\t\ttbn2[1] *= faceDirection;\n\t#endif\n#endif\nvec3 nonPerturbedNormal = normal;";
  42993. var normal_fragment_maps = "#ifdef USE_NORMALMAP_OBJECTSPACE\n\tnormal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\t#ifdef FLIP_SIDED\n\t\tnormal = - normal;\n\t#endif\n\t#ifdef DOUBLE_SIDED\n\t\tnormal = normal * faceDirection;\n\t#endif\n\tnormal = normalize( normalMatrix * normal );\n#elif defined( USE_NORMALMAP_TANGENTSPACE )\n\tvec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0;\n\tmapN.xy *= normalScale;\n\tnormal = normalize( tbn * mapN );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection );\n#endif";
  42994. 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";
  42995. 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";
  42996. 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";
  42997. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n#endif\n#ifdef USE_NORMALMAP_OBJECTSPACE\n\tuniform mat3 normalMatrix;\n#endif\n#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) )\n\tmat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( uv.st );\n\t\tvec2 st1 = dFdy( uv.st );\n\t\tvec3 N = surf_norm;\n\t\tvec3 q1perp = cross( q1, N );\n\t\tvec3 q0perp = cross( N, q0 );\n\t\tvec3 T = q1perp * st0.x + q0perp * st1.x;\n\t\tvec3 B = q1perp * st0.y + q0perp * st1.y;\n\t\tfloat det = max( dot( T, T ), dot( B, B ) );\n\t\tfloat scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det );\n\t\treturn mat3( T * scale, B * scale, N );\n\t}\n#endif";
  42998. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  42999. var clearcoat_normal_fragment_maps = "#ifdef USE_CLEARCOAT_NORMALMAP\n\tvec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0;\n\tclearcoatMapN.xy *= clearcoatNormalScale;\n\tclearcoatNormal = normalize( tbn2 * clearcoatMapN );\n#endif";
  43000. var clearcoat_pars_fragment = "#ifdef USE_CLEARCOATMAP\n\tuniform sampler2D clearcoatMap;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform sampler2D clearcoatNormalMap;\n\tuniform vec2 clearcoatNormalScale;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform sampler2D clearcoatRoughnessMap;\n#endif";
  43001. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  43002. var opaque_fragment = "#ifdef OPAQUE\ndiffuseColor.a = 1.0;\n#endif\n#ifdef USE_TRANSMISSION\ndiffuseColor.a *= material.transmissionAlpha;\n#endif\ngl_FragColor = vec4( outgoingLight, diffuseColor.a );";
  43003. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n\treturn normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n\treturn 2.0 * rgb.xyz - 1.0;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.;\nconst float Inv255 = 1. / 255.;\nconst vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 );\nconst vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g );\nconst vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b );\nconst vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a );\nvec4 packDepthToRGBA( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec4( 0., 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec4( 1., 1., 1., 1. );\n\tfloat vuf;\n\tfloat af = modf( v * PackFactors.a, vuf );\n\tfloat bf = modf( vuf * ShiftRight8, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af );\n}\nvec3 packDepthToRGB( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec3( 0., 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec3( 1., 1., 1. );\n\tfloat vuf;\n\tfloat bf = modf( v * PackFactors.b, vuf );\n\tfloat gf = modf( vuf * ShiftRight8, vuf );\n\treturn vec3( vuf * Inv255, gf * PackUpscale, bf );\n}\nvec2 packDepthToRG( const in float v ) {\n\tif( v <= 0.0 )\n\t\treturn vec2( 0., 0. );\n\tif( v >= 1.0 )\n\t\treturn vec2( 1., 1. );\n\tfloat vuf;\n\tfloat gf = modf( v * 256., vuf );\n\treturn vec2( vuf * Inv255, gf );\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors4 );\n}\nfloat unpackRGBToDepth( const in vec3 v ) {\n\treturn dot( v, UnpackFactors3 );\n}\nfloat unpackRGToDepth( const in vec2 v ) {\n\treturn v.r * UnpackFactors2.r + v.g * UnpackFactors2.g;\n}\nvec4 pack2HalfToRGBA( const in vec2 v ) {\n\tvec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) );\n\treturn vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w );\n}\nvec2 unpackRGBATo2Half( const in vec4 v ) {\n\treturn vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn depth * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n\treturn ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) {\n\treturn ( near * far ) / ( ( far - near ) * depth - far );\n}";
  43004. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  43005. var project_vertex = "vec4 mvPosition = vec4( transformed, 1.0 );\n#ifdef USE_BATCHING\n\tmvPosition = batchingMatrix * mvPosition;\n#endif\n#ifdef USE_INSTANCING\n\tmvPosition = instanceMatrix * mvPosition;\n#endif\nmvPosition = modelViewMatrix * mvPosition;\ngl_Position = projectionMatrix * mvPosition;";
  43006. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  43007. 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";
  43008. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  43009. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  43010. var shadowmap_pars_fragment = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#if NUM_SPOT_LIGHT_MAPS > 0\n\tuniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#else\n\t\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tuniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\t\t\tuniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ];\n\t\t#endif\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat interleavedGradientNoise( vec2 position ) {\n\t\t\treturn fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) );\n\t\t}\n\t\tvec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) {\n\t\t\tconst float goldenAngle = 2.399963229728653;\n\t\t\tfloat r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) );\n\t\t\tfloat theta = float( sampleIndex ) * goldenAngle + phi;\n\t\t\treturn vec2( cos( theta ), sin( theta ) ) * r;\n\t\t}\n\t#endif\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\tfloat getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\t\tfloat radius = shadowRadius * texelSize.x;\n\t\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\t\tshadow = (\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) +\n\t\t\t\t\ttexture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) )\n\t\t\t\t) * 0.2;\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#elif defined( SHADOWMAP_TYPE_VSM )\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tvec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg;\n\t\t\t\tfloat mean = distribution.x;\n\t\t\t\tfloat variance = distribution.y * distribution.y;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tfloat hard_shadow = step( mean, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tfloat hard_shadow = step( shadowCoord.z, mean );\n\t\t\t\t#endif\n\t\t\t\tif ( hard_shadow == 1.0 ) {\n\t\t\t\t\tshadow = 1.0;\n\t\t\t\t} else {\n\t\t\t\t\tvariance = max( variance, 0.0000001 );\n\t\t\t\t\tfloat d = shadowCoord.z - mean;\n\t\t\t\t\tfloat p_max = variance / ( variance + d * d );\n\t\t\t\t\tp_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 );\n\t\t\t\t\tshadow = max( hard_shadow, p_max );\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#else\n\t\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\t\tfloat shadow = 1.0;\n\t\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\t\tshadowCoord.z += shadowBias;\n\t\t\tbool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0;\n\t\t\tbool frustumTest = inFrustum && shadowCoord.z <= 1.0;\n\t\t\tif ( frustumTest ) {\n\t\t\t\tfloat depth = texture2D( shadowMap, shadowCoord.xy ).r;\n\t\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\t\tshadow = step( depth, shadowCoord.z );\n\t\t\t\t#else\n\t\t\t\t\tshadow = step( shadowCoord.z, depth );\n\t\t\t\t#endif\n\t\t\t}\n\t\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t\t}\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t#if defined( SHADOWMAP_TYPE_PCF )\n\tfloat getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat texelSize = shadowRadius / shadowMapSize.x;\n\t\t\tvec3 absDir = abs( bd3D );\n\t\t\tvec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 );\n\t\t\ttangent = normalize( cross( bd3D, tangent ) );\n\t\t\tvec3 bitangent = cross( bd3D, tangent );\n\t\t\tfloat phi = interleavedGradientNoise( gl_FragCoord.xy ) * 6.28318530718;\n\t\t\tshadow = (\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 0, 5, phi ).x + bitangent * vogelDiskSample( 0, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 1, 5, phi ).x + bitangent * vogelDiskSample( 1, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 2, 5, phi ).x + bitangent * vogelDiskSample( 2, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 3, 5, phi ).x + bitangent * vogelDiskSample( 3, 5, phi ).y ) * texelSize, dp ) ) +\n\t\t\t\ttexture( shadowMap, vec4( bd3D + ( tangent * vogelDiskSample( 4, 5, phi ).x + bitangent * vogelDiskSample( 4, 5, phi ).y ) * texelSize, dp ) )\n\t\t\t) * 0.2;\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#elif defined( SHADOWMAP_TYPE_BASIC )\n\tfloat getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\n\t\tfloat shadow = 1.0;\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tvec3 absVec = abs( lightToPosition );\n\t\tfloat viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z );\n\t\tif ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) {\n\t\t\tfloat dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );\n\t\t\tdp += shadowBias;\n\t\t\tfloat depth = textureCube( shadowMap, bd3D ).r;\n\t\t\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\t\t\tshadow = step( depth, dp );\n\t\t\t#else\n\t\t\t\tshadow = step( dp, depth );\n\t\t\t#endif\n\t\t}\n\t\treturn mix( 1.0, shadow, shadowIntensity );\n\t}\n\t#endif\n\t#endif\n#endif";
  43011. var shadowmap_pars_vertex = "#if NUM_SPOT_LIGHT_COORDS > 0\n\tuniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ];\n\tvarying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ];\n#endif\n#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];\n\t\tstruct DirectionalLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\t\tstruct SpotLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t};\n\t\tuniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ];\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ];\n\t\tstruct PointLightShadow {\n\t\t\tfloat shadowIntensity;\n\t\t\tfloat shadowBias;\n\t\t\tfloat shadowNormalBias;\n\t\t\tfloat shadowRadius;\n\t\t\tvec2 shadowMapSize;\n\t\t\tfloat shadowCameraNear;\n\t\t\tfloat shadowCameraFar;\n\t\t};\n\t\tuniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ];\n\t#endif\n#endif";
  43012. var shadowmap_vertex = "#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 )\n\tvec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\tvec4 shadowWorldPosition;\n#endif\n#if defined( USE_SHADOWMAP )\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0\n\t\t#pragma unroll_loop_start\n\t\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\t\tshadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 );\n\t\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition;\n\t\t}\n\t\t#pragma unroll_loop_end\n\t#endif\n#endif\n#if NUM_SPOT_LIGHT_COORDS > 0\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) {\n\t\tshadowWorldPosition = worldPosition;\n\t\t#if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS )\n\t\t\tshadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias;\n\t\t#endif\n\t\tvSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition;\n\t}\n\t#pragma unroll_loop_end\n#endif";
  43013. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHT_SHADOWS > 0\n\tDirectionalLightShadow directionalLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {\n\t\tdirectionalLight = directionalLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_SPOT_LIGHT_SHADOWS > 0\n\tSpotLightShadow spotLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) {\n\t\tspotLight = spotLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) )\n\tPointLightShadow pointLight;\n\t#pragma unroll_loop_start\n\tfor ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) {\n\t\tpointLight = pointLightShadows[ i ];\n\t\tshadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\n\t}\n\t#pragma unroll_loop_end\n\t#endif\n\t#endif\n\treturn shadow;\n}";
  43014. 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";
  43015. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\tuniform highp sampler2D boneTexture;\n\tmat4 getBoneMatrix( const in float i ) {\n\t\tint size = textureSize( boneTexture, 0 ).x;\n\t\tint j = int( i ) * 4;\n\t\tint x = j % size;\n\t\tint y = j / size;\n\t\tvec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 );\n\t\tvec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 );\n\t\tvec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 );\n\t\tvec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 );\n\t\treturn mat4( v1, v2, v3, v4 );\n\t}\n#endif";
  43016. 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";
  43017. 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";
  43018. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vSpecularMapUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  43019. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  43020. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  43021. var tonemapping_pars_fragment = "#ifndef saturate\n#define saturate( a ) clamp( a, 0.0, 1.0 )\n#endif\nuniform float toneMappingExposure;\nvec3 LinearToneMapping( vec3 color ) {\n\treturn saturate( toneMappingExposure * color );\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\n}\nvec3 CineonToneMapping( vec3 color ) {\n\tcolor *= toneMappingExposure;\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\nvec3 RRTAndODTFit( vec3 v ) {\n\tvec3 a = v * ( v + 0.0245786 ) - 0.000090537;\n\tvec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081;\n\treturn a / b;\n}\nvec3 ACESFilmicToneMapping( vec3 color ) {\n\tconst mat3 ACESInputMat = mat3(\n\t\tvec3( 0.59719, 0.07600, 0.02840 ),\t\tvec3( 0.35458, 0.90834, 0.13383 ),\n\t\tvec3( 0.04823, 0.01566, 0.83777 )\n\t);\n\tconst mat3 ACESOutputMat = mat3(\n\t\tvec3( 1.60475, -0.10208, -0.00327 ),\t\tvec3( -0.53108, 1.10813, -0.07276 ),\n\t\tvec3( -0.07367, -0.00605, 1.07602 )\n\t);\n\tcolor *= toneMappingExposure / 0.6;\n\tcolor = ACESInputMat * color;\n\tcolor = RRTAndODTFit( color );\n\tcolor = ACESOutputMat * color;\n\treturn saturate( color );\n}\nconst mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3(\n\tvec3( 1.6605, - 0.1246, - 0.0182 ),\n\tvec3( - 0.5876, 1.1329, - 0.1006 ),\n\tvec3( - 0.0728, - 0.0083, 1.1187 )\n);\nconst mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3(\n\tvec3( 0.6274, 0.0691, 0.0164 ),\n\tvec3( 0.3293, 0.9195, 0.0880 ),\n\tvec3( 0.0433, 0.0113, 0.8956 )\n);\nvec3 agxDefaultContrastApprox( vec3 x ) {\n\tvec3 x2 = x * x;\n\tvec3 x4 = x2 * x2;\n\treturn + 15.5 * x4 * x2\n\t\t- 40.14 * x4 * x\n\t\t+ 31.96 * x4\n\t\t- 6.868 * x2 * x\n\t\t+ 0.4298 * x2\n\t\t+ 0.1191 * x\n\t\t- 0.00232;\n}\nvec3 AgXToneMapping( vec3 color ) {\n\tconst mat3 AgXInsetMatrix = mat3(\n\t\tvec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ),\n\t\tvec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ),\n\t\tvec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 )\n\t);\n\tconst mat3 AgXOutsetMatrix = mat3(\n\t\tvec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ),\n\t\tvec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ),\n\t\tvec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 )\n\t);\n\tconst float AgxMinEv = - 12.47393;\tconst float AgxMaxEv = 4.026069;\n\tcolor *= toneMappingExposure;\n\tcolor = LINEAR_SRGB_TO_LINEAR_REC2020 * color;\n\tcolor = AgXInsetMatrix * color;\n\tcolor = max( color, 1e-10 );\tcolor = log2( color );\n\tcolor = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv );\n\tcolor = clamp( color, 0.0, 1.0 );\n\tcolor = agxDefaultContrastApprox( color );\n\tcolor = AgXOutsetMatrix * color;\n\tcolor = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) );\n\tcolor = LINEAR_REC2020_TO_LINEAR_SRGB * color;\n\tcolor = clamp( color, 0.0, 1.0 );\n\treturn color;\n}\nvec3 NeutralToneMapping( vec3 color ) {\n\tconst float StartCompression = 0.8 - 0.04;\n\tconst float Desaturation = 0.15;\n\tcolor *= toneMappingExposure;\n\tfloat x = min( color.r, min( color.g, color.b ) );\n\tfloat offset = x < 0.08 ? x - 6.25 * x * x : 0.04;\n\tcolor -= offset;\n\tfloat peak = max( color.r, max( color.g, color.b ) );\n\tif ( peak < StartCompression ) return color;\n\tfloat d = 1. - StartCompression;\n\tfloat newPeak = 1. - d * d / ( peak + d - StartCompression );\n\tcolor *= newPeak / peak;\n\tfloat g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. );\n\treturn mix( color, vec3( newPeak ), g );\n}\nvec3 CustomToneMapping( vec3 color ) { return color; }";
  43022. var transmission_fragment = "#ifdef USE_TRANSMISSION\n\tmaterial.transmission = transmission;\n\tmaterial.transmissionAlpha = 1.0;\n\tmaterial.thickness = thickness;\n\tmaterial.attenuationDistance = attenuationDistance;\n\tmaterial.attenuationColor = attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tmaterial.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tmaterial.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g;\n\t#endif\n\tvec3 pos = vWorldPosition;\n\tvec3 v = normalize( cameraPosition - pos );\n\tvec3 n = inverseTransformDirection( normal, viewMatrix );\n\tvec4 transmitted = getIBLVolumeRefraction(\n\t\tn, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90,\n\t\tpos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness,\n\t\tmaterial.attenuationColor, material.attenuationDistance );\n\tmaterial.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission );\n\ttotalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );\n#endif";
  43023. var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) );\n\t\tvec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) );\n\t\treturn mix( fSample, cSample, fract( lod ) );\n\t}\n\tvec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) {\n\t\tvec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior );\n\t\tvec3 modelScale;\n\t\tmodelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) );\n\t\tmodelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) );\n\t\tmodelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) );\n\t\treturn normalize( refractionVector ) * thickness * modelScale;\n\t}\n\tfloat applyIorToRoughness( const in float roughness, const in float ior ) {\n\t\treturn roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 );\n\t}\n\tvec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) {\n\t\tfloat lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior );\n\t\treturn textureBicubic( transmissionSamplerMap, fragCoord.xy, lod );\n\t}\n\tvec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tif ( isinf( attenuationDistance ) ) {\n\t\t\treturn vec3( 1.0 );\n\t\t} else {\n\t\t\tvec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance;\n\t\t\tvec3 transmittance = exp( - attenuationCoefficient * transmissionDistance );\t\t\treturn transmittance;\n\t\t}\n\t}\n\tvec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor,\n\t\tconst in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix,\n\t\tconst in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness,\n\t\tconst in vec3 attenuationColor, const in float attenuationDistance ) {\n\t\tvec4 transmittedLight;\n\t\tvec3 transmittance;\n\t\t#ifdef USE_DISPERSION\n\t\t\tfloat halfSpread = ( ior - 1.0 ) * 0.025 * dispersion;\n\t\t\tvec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread );\n\t\t\tfor ( int i = 0; i < 3; i ++ ) {\n\t\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix );\n\t\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\t\trefractionCoords += 1.0;\n\t\t\t\trefractionCoords /= 2.0;\n\t\t\t\tvec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] );\n\t\t\t\ttransmittedLight[ i ] = transmissionSample[ i ];\n\t\t\t\ttransmittedLight.a += transmissionSample.a;\n\t\t\t\ttransmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ];\n\t\t\t}\n\t\t\ttransmittedLight.a /= 3.0;\n\t\t#else\n\t\t\tvec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );\n\t\t\tvec3 refractedRayExit = position + transmissionRay;\n\t\t\tvec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 );\n\t\t\tvec2 refractionCoords = ndcPos.xy / ndcPos.w;\n\t\t\trefractionCoords += 1.0;\n\t\t\trefractionCoords /= 2.0;\n\t\t\ttransmittedLight = getTransmissionSample( refractionCoords, roughness, ior );\n\t\t\ttransmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance );\n\t\t#endif\n\t\tvec3 attenuatedColor = transmittance * transmittedLight.rgb;\n\t\tvec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness );\n\t\tfloat transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0;\n\t\treturn vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor );\n\t}\n#endif";
  43024. var uv_pars_fragment = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  43025. var uv_pars_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvarying vec2 vUv;\n#endif\n#ifdef USE_MAP\n\tuniform mat3 mapTransform;\n\tvarying vec2 vMapUv;\n#endif\n#ifdef USE_ALPHAMAP\n\tuniform mat3 alphaMapTransform;\n\tvarying vec2 vAlphaMapUv;\n#endif\n#ifdef USE_LIGHTMAP\n\tuniform mat3 lightMapTransform;\n\tvarying vec2 vLightMapUv;\n#endif\n#ifdef USE_AOMAP\n\tuniform mat3 aoMapTransform;\n\tvarying vec2 vAoMapUv;\n#endif\n#ifdef USE_BUMPMAP\n\tuniform mat3 bumpMapTransform;\n\tvarying vec2 vBumpMapUv;\n#endif\n#ifdef USE_NORMALMAP\n\tuniform mat3 normalMapTransform;\n\tvarying vec2 vNormalMapUv;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tuniform mat3 displacementMapTransform;\n\tvarying vec2 vDisplacementMapUv;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tuniform mat3 emissiveMapTransform;\n\tvarying vec2 vEmissiveMapUv;\n#endif\n#ifdef USE_METALNESSMAP\n\tuniform mat3 metalnessMapTransform;\n\tvarying vec2 vMetalnessMapUv;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tuniform mat3 roughnessMapTransform;\n\tvarying vec2 vRoughnessMapUv;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tuniform mat3 anisotropyMapTransform;\n\tvarying vec2 vAnisotropyMapUv;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tuniform mat3 clearcoatMapTransform;\n\tvarying vec2 vClearcoatMapUv;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tuniform mat3 clearcoatNormalMapTransform;\n\tvarying vec2 vClearcoatNormalMapUv;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tuniform mat3 clearcoatRoughnessMapTransform;\n\tvarying vec2 vClearcoatRoughnessMapUv;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tuniform mat3 sheenColorMapTransform;\n\tvarying vec2 vSheenColorMapUv;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tuniform mat3 sheenRoughnessMapTransform;\n\tvarying vec2 vSheenRoughnessMapUv;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tuniform mat3 iridescenceMapTransform;\n\tvarying vec2 vIridescenceMapUv;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform mat3 iridescenceThicknessMapTransform;\n\tvarying vec2 vIridescenceThicknessMapUv;\n#endif\n#ifdef USE_SPECULARMAP\n\tuniform mat3 specularMapTransform;\n\tvarying vec2 vSpecularMapUv;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tuniform mat3 specularColorMapTransform;\n\tvarying vec2 vSpecularColorMapUv;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tuniform mat3 specularIntensityMapTransform;\n\tvarying vec2 vSpecularIntensityMapUv;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tuniform mat3 transmissionMapTransform;\n\tvarying vec2 vTransmissionMapUv;\n#endif\n#ifdef USE_THICKNESSMAP\n\tuniform mat3 thicknessMapTransform;\n\tvarying vec2 vThicknessMapUv;\n#endif";
  43026. var uv_vertex = "#if defined( USE_UV ) || defined( USE_ANISOTROPY )\n\tvUv = vec3( uv, 1 ).xy;\n#endif\n#ifdef USE_MAP\n\tvMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ALPHAMAP\n\tvAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_LIGHTMAP\n\tvLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_AOMAP\n\tvAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_BUMPMAP\n\tvBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_NORMALMAP\n\tvNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_DISPLACEMENTMAP\n\tvDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_EMISSIVEMAP\n\tvEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_METALNESSMAP\n\tvMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ROUGHNESSMAP\n\tvRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_ANISOTROPYMAP\n\tvAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOATMAP\n\tvClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_NORMALMAP\n\tvClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_CLEARCOAT_ROUGHNESSMAP\n\tvClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCEMAP\n\tvIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tvIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_COLORMAP\n\tvSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SHEEN_ROUGHNESSMAP\n\tvSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULARMAP\n\tvSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_COLORMAP\n\tvSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_SPECULAR_INTENSITYMAP\n\tvSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_TRANSMISSIONMAP\n\tvTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy;\n#endif\n#ifdef USE_THICKNESSMAP\n\tvThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy;\n#endif";
  43027. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0\n\tvec4 worldPosition = vec4( transformed, 1.0 );\n\t#ifdef USE_BATCHING\n\t\tworldPosition = batchingMatrix * worldPosition;\n\t#endif\n\t#ifdef USE_INSTANCING\n\t\tworldPosition = instanceMatrix * worldPosition;\n\t#endif\n\tworldPosition = modelMatrix * worldPosition;\n#endif";
  43028. const vertex$h = "varying vec2 vUv;\nuniform mat3 uvTransform;\nvoid main() {\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\tgl_Position = vec4( position.xy, 1.0, 1.0 );\n}";
  43029. const fragment$h = "uniform sampler2D t2D;\nuniform float backgroundIntensity;\nvarying vec2 vUv;\nvoid main() {\n\tvec4 texColor = texture2D( t2D, vUv );\n\t#ifdef DECODE_VIDEO_TEXTURE\n\t\ttexColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43030. const vertex$g = "varying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvWorldDirection = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\tgl_Position.z = gl_Position.w;\n}";
  43031. const fragment$g = "#ifdef ENVMAP_TYPE_CUBE\n\tuniform samplerCube envMap;\n#elif defined( ENVMAP_TYPE_CUBE_UV )\n\tuniform sampler2D envMap;\n#endif\nuniform float flipEnvMap;\nuniform float backgroundBlurriness;\nuniform float backgroundIntensity;\nuniform mat3 backgroundRotation;\nvarying vec3 vWorldDirection;\n#include <cube_uv_reflection_fragment>\nvoid main() {\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) );\n\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\tvec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness );\n\t#else\n\t\tvec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 );\n\t#endif\n\ttexColor.rgb *= backgroundIntensity;\n\tgl_FragColor = texColor;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43032. 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}";
  43033. const fragment$f = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldDirection;\nvoid main() {\n\tvec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) );\n\tgl_FragColor = texColor;\n\tgl_FragColor.a *= opacity;\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43034. const vertex$e = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvHighPrecisionZW = gl_Position.zw;\n}";
  43035. const fragment$e = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvarying vec2 vHighPrecisionZW;\nvoid main() {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <logdepthbuf_fragment>\n\t#ifdef USE_REVERSED_DEPTH_BUFFER\n\t\tfloat fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ];\n\t#else\n\t\tfloat fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5;\n\t#endif\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( fragCoordZ );\n\t#elif DEPTH_PACKING == 3202\n\t\tgl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 );\n\t#elif DEPTH_PACKING == 3203\n\t\tgl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 );\n\t#endif\n}";
  43036. const vertex$d = "#define DISTANCE\nvarying vec3 vWorldPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <skinbase_vertex>\n\t#include <morphinstance_vertex>\n\t#ifdef USE_DISPLACEMENTMAP\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition.xyz;\n}";
  43037. const fragment$d = "#define DISTANCE\nuniform vec3 referencePosition;\nuniform float nearDistance;\nuniform float farDistance;\nvarying vec3 vWorldPosition;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#include <clipping_planes_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\tfloat dist = length( vWorldPosition - referencePosition );\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\n\tdist = saturate( dist );\n\tgl_FragColor = vec4( dist, 0.0, 0.0, 1.0 );\n}";
  43038. 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}";
  43039. const fragment$c = "uniform sampler2D tEquirect;\nvarying vec3 vWorldDirection;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldDirection );\n\tvec2 sampleUV = equirectUv( direction );\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n}";
  43040. const vertex$b = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\tvLineDistance = scale * lineDistance;\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n}";
  43041. const fragment$b = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43042. const vertex$a = "#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#if defined ( USE_ENVMAP ) || defined ( USE_SKINNING )\n\t\t#include <beginnormal_vertex>\n\t\t#include <morphnormal_vertex>\n\t\t#include <skinbase_vertex>\n\t\t#include <skinnormal_vertex>\n\t\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <fog_vertex>\n}";
  43043. const fragment$a = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\tvec4 lightMapTexel = texture2D( lightMap, vLightMapUv );\n\t\treflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43044. const vertex$9 = "#define LAMBERT\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43045. const fragment$9 = "#define LAMBERT\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_lambert_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_lambert_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43046. const vertex$8 = "#define MATCAP\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <color_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <fog_vertex>\n\tvViewPosition = - mvPosition.xyz;\n}";
  43047. const fragment$8 = "#define MATCAP\nuniform vec3 diffuse;\nuniform float opacity;\nuniform sampler2D matcap;\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tvec3 viewDir = normalize( vViewPosition );\n\tvec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) );\n\tvec3 y = cross( viewDir, x );\n\tvec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5;\n\t#ifdef USE_MATCAP\n\t\tvec4 matcapColor = texture2D( matcap, uv );\n\t#else\n\t\tvec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 );\n\t#endif\n\tvec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43048. const vertex$7 = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}";
  43049. const fragment$7 = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE )\n\tvarying vec3 vViewPosition;\n#endif\n#include <uv_pars_fragment>\n#include <normal_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity );\n\t#include <clipping_planes_fragment>\n\t#include <logdepthbuf_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\tgl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a );\n\t#ifdef OPAQUE\n\t\tgl_FragColor.a = 1.0;\n\t#endif\n}";
  43050. const vertex$6 = "#define PHONG\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43051. 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 <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43052. const vertex$5 = "#define STANDARD\nvarying vec3 vViewPosition;\n#ifdef USE_TRANSMISSION\n\tvarying vec3 vWorldPosition;\n#endif\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n#ifdef USE_TRANSMISSION\n\tvWorldPosition = worldPosition.xyz;\n#endif\n}";
  43053. const fragment$5 = "#define STANDARD\n#ifdef PHYSICAL\n\t#define IOR\n\t#define USE_SPECULAR\n#endif\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifdef IOR\n\tuniform float ior;\n#endif\n#ifdef USE_SPECULAR\n\tuniform float specularIntensity;\n\tuniform vec3 specularColor;\n\t#ifdef USE_SPECULAR_COLORMAP\n\t\tuniform sampler2D specularColorMap;\n\t#endif\n\t#ifdef USE_SPECULAR_INTENSITYMAP\n\t\tuniform sampler2D specularIntensityMap;\n\t#endif\n#endif\n#ifdef USE_CLEARCOAT\n\tuniform float clearcoat;\n\tuniform float clearcoatRoughness;\n#endif\n#ifdef USE_DISPERSION\n\tuniform float dispersion;\n#endif\n#ifdef USE_IRIDESCENCE\n\tuniform float iridescence;\n\tuniform float iridescenceIOR;\n\tuniform float iridescenceThicknessMinimum;\n\tuniform float iridescenceThicknessMaximum;\n#endif\n#ifdef USE_SHEEN\n\tuniform vec3 sheenColor;\n\tuniform float sheenRoughness;\n\t#ifdef USE_SHEEN_COLORMAP\n\t\tuniform sampler2D sheenColorMap;\n\t#endif\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tuniform sampler2D sheenRoughnessMap;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\tuniform vec2 anisotropyVector;\n\t#ifdef USE_ANISOTROPYMAP\n\t\tuniform sampler2D anisotropyMap;\n\t#endif\n#endif\nvarying vec3 vViewPosition;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <iridescence_fragment>\n#include <cube_uv_reflection_fragment>\n#include <envmap_common_pars_fragment>\n#include <envmap_physical_pars_fragment>\n#include <fog_pars_fragment>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_physical_pars_fragment>\n#include <transmission_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <clearcoat_pars_fragment>\n#include <iridescence_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <clearcoat_normal_fragment_begin>\n\t#include <clearcoat_normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;\n\tvec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;\n\t#include <transmission_fragment>\n\tvec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;\n\t#ifdef USE_SHEEN\n \n\t\toutgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect;\n \n \t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43054. const vertex$4 = "#define TOON\nvarying vec3 vViewPosition;\n#include <common>\n#include <batching_pars_vertex>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <normal_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <normal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <displacementmap_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43055. const fragment$4 = "#define TOON\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\n#include <common>\n#include <dithering_pars_fragment>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <normal_pars_fragment>\n#include <lights_toon_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\t#include <normal_fragment_begin>\n\t#include <normal_fragment_maps>\n\t#include <emissivemap_fragment>\n\t#include <lights_toon_fragment>\n\t#include <lights_fragment_begin>\n\t#include <lights_fragment_maps>\n\t#include <lights_fragment_end>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43056. const vertex$3 = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\n#ifdef USE_POINTS_UV\n\tvarying vec2 vUv;\n\tuniform mat3 uvTransform;\n#endif\nvoid main() {\n\t#ifdef USE_POINTS_UV\n\t\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\n\t#endif\n\t#include <color_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphcolor_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <project_vertex>\n\tgl_PointSize = size;\n\t#ifdef USE_SIZEATTENUATION\n\t\tbool isPerspective = isPerspectiveMatrix( projectionMatrix );\n\t\tif ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z );\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <fog_vertex>\n}";
  43057. const fragment$3 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n}";
  43058. const vertex$2 = "#include <common>\n#include <batching_pars_vertex>\n#include <fog_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <batching_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphinstance_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n\t#include <fog_vertex>\n}";
  43059. const fragment$2 = "uniform vec3 color;\nuniform float opacity;\n#include <common>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars_begin>\n#include <logdepthbuf_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  43060. 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[ 3 ];\n\tvec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) );\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}";
  43061. const fragment$1 = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <alphatest_pars_fragment>\n#include <alphahash_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <alphahash_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n}";
  43062. const ShaderChunk = {
  43063. alphahash_fragment: alphahash_fragment,
  43064. alphahash_pars_fragment: alphahash_pars_fragment,
  43065. alphamap_fragment: alphamap_fragment,
  43066. alphamap_pars_fragment: alphamap_pars_fragment,
  43067. alphatest_fragment: alphatest_fragment,
  43068. alphatest_pars_fragment: alphatest_pars_fragment,
  43069. aomap_fragment: aomap_fragment,
  43070. aomap_pars_fragment: aomap_pars_fragment,
  43071. batching_pars_vertex: batching_pars_vertex,
  43072. batching_vertex: batching_vertex,
  43073. begin_vertex: begin_vertex,
  43074. beginnormal_vertex: beginnormal_vertex,
  43075. bsdfs: bsdfs,
  43076. iridescence_fragment: iridescence_fragment,
  43077. bumpmap_pars_fragment: bumpmap_pars_fragment,
  43078. clipping_planes_fragment: clipping_planes_fragment,
  43079. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  43080. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  43081. clipping_planes_vertex: clipping_planes_vertex,
  43082. color_fragment: color_fragment,
  43083. color_pars_fragment: color_pars_fragment,
  43084. color_pars_vertex: color_pars_vertex,
  43085. color_vertex: color_vertex,
  43086. common: common,
  43087. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  43088. defaultnormal_vertex: defaultnormal_vertex,
  43089. displacementmap_pars_vertex: displacementmap_pars_vertex,
  43090. displacementmap_vertex: displacementmap_vertex,
  43091. emissivemap_fragment: emissivemap_fragment,
  43092. emissivemap_pars_fragment: emissivemap_pars_fragment,
  43093. colorspace_fragment: colorspace_fragment,
  43094. colorspace_pars_fragment: colorspace_pars_fragment,
  43095. envmap_fragment: envmap_fragment,
  43096. envmap_common_pars_fragment: envmap_common_pars_fragment,
  43097. envmap_pars_fragment: envmap_pars_fragment,
  43098. envmap_pars_vertex: envmap_pars_vertex,
  43099. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  43100. envmap_vertex: envmap_vertex,
  43101. fog_vertex: fog_vertex,
  43102. fog_pars_vertex: fog_pars_vertex,
  43103. fog_fragment: fog_fragment,
  43104. fog_pars_fragment: fog_pars_fragment,
  43105. gradientmap_pars_fragment: gradientmap_pars_fragment,
  43106. lightmap_pars_fragment: lightmap_pars_fragment,
  43107. lights_lambert_fragment: lights_lambert_fragment,
  43108. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  43109. lights_pars_begin: lights_pars_begin,
  43110. lights_toon_fragment: lights_toon_fragment,
  43111. lights_toon_pars_fragment: lights_toon_pars_fragment,
  43112. lights_phong_fragment: lights_phong_fragment,
  43113. lights_phong_pars_fragment: lights_phong_pars_fragment,
  43114. lights_physical_fragment: lights_physical_fragment,
  43115. lights_physical_pars_fragment: lights_physical_pars_fragment,
  43116. lights_fragment_begin: lights_fragment_begin,
  43117. lights_fragment_maps: lights_fragment_maps,
  43118. lights_fragment_end: lights_fragment_end,
  43119. logdepthbuf_fragment: logdepthbuf_fragment,
  43120. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  43121. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  43122. logdepthbuf_vertex: logdepthbuf_vertex,
  43123. map_fragment: map_fragment,
  43124. map_pars_fragment: map_pars_fragment,
  43125. map_particle_fragment: map_particle_fragment,
  43126. map_particle_pars_fragment: map_particle_pars_fragment,
  43127. metalnessmap_fragment: metalnessmap_fragment,
  43128. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  43129. morphinstance_vertex: morphinstance_vertex,
  43130. morphcolor_vertex: morphcolor_vertex,
  43131. morphnormal_vertex: morphnormal_vertex,
  43132. morphtarget_pars_vertex: morphtarget_pars_vertex,
  43133. morphtarget_vertex: morphtarget_vertex,
  43134. normal_fragment_begin: normal_fragment_begin,
  43135. normal_fragment_maps: normal_fragment_maps,
  43136. normal_pars_fragment: normal_pars_fragment,
  43137. normal_pars_vertex: normal_pars_vertex,
  43138. normal_vertex: normal_vertex,
  43139. normalmap_pars_fragment: normalmap_pars_fragment,
  43140. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  43141. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  43142. clearcoat_pars_fragment: clearcoat_pars_fragment,
  43143. iridescence_pars_fragment: iridescence_pars_fragment,
  43144. opaque_fragment: opaque_fragment,
  43145. packing: packing,
  43146. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  43147. project_vertex: project_vertex,
  43148. dithering_fragment: dithering_fragment,
  43149. dithering_pars_fragment: dithering_pars_fragment,
  43150. roughnessmap_fragment: roughnessmap_fragment,
  43151. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  43152. shadowmap_pars_fragment: shadowmap_pars_fragment,
  43153. shadowmap_pars_vertex: shadowmap_pars_vertex,
  43154. shadowmap_vertex: shadowmap_vertex,
  43155. shadowmask_pars_fragment: shadowmask_pars_fragment,
  43156. skinbase_vertex: skinbase_vertex,
  43157. skinning_pars_vertex: skinning_pars_vertex,
  43158. skinning_vertex: skinning_vertex,
  43159. skinnormal_vertex: skinnormal_vertex,
  43160. specularmap_fragment: specularmap_fragment,
  43161. specularmap_pars_fragment: specularmap_pars_fragment,
  43162. tonemapping_fragment: tonemapping_fragment,
  43163. tonemapping_pars_fragment: tonemapping_pars_fragment,
  43164. transmission_fragment: transmission_fragment,
  43165. transmission_pars_fragment: transmission_pars_fragment,
  43166. uv_pars_fragment: uv_pars_fragment,
  43167. uv_pars_vertex: uv_pars_vertex,
  43168. uv_vertex: uv_vertex,
  43169. worldpos_vertex: worldpos_vertex,
  43170. background_vert: vertex$h,
  43171. background_frag: fragment$h,
  43172. backgroundCube_vert: vertex$g,
  43173. backgroundCube_frag: fragment$g,
  43174. cube_vert: vertex$f,
  43175. cube_frag: fragment$f,
  43176. depth_vert: vertex$e,
  43177. depth_frag: fragment$e,
  43178. distance_vert: vertex$d,
  43179. distance_frag: fragment$d,
  43180. equirect_vert: vertex$c,
  43181. equirect_frag: fragment$c,
  43182. linedashed_vert: vertex$b,
  43183. linedashed_frag: fragment$b,
  43184. meshbasic_vert: vertex$a,
  43185. meshbasic_frag: fragment$a,
  43186. meshlambert_vert: vertex$9,
  43187. meshlambert_frag: fragment$9,
  43188. meshmatcap_vert: vertex$8,
  43189. meshmatcap_frag: fragment$8,
  43190. meshnormal_vert: vertex$7,
  43191. meshnormal_frag: fragment$7,
  43192. meshphong_vert: vertex$6,
  43193. meshphong_frag: fragment$6,
  43194. meshphysical_vert: vertex$5,
  43195. meshphysical_frag: fragment$5,
  43196. meshtoon_vert: vertex$4,
  43197. meshtoon_frag: fragment$4,
  43198. points_vert: vertex$3,
  43199. points_frag: fragment$3,
  43200. shadow_vert: vertex$2,
  43201. shadow_frag: fragment$2,
  43202. sprite_vert: vertex$1,
  43203. sprite_frag: fragment$1
  43204. };
  43205. // Uniforms library for shared webgl shaders
  43206. const UniformsLib = {
  43207. common: {
  43208. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43209. opacity: { value: 1.0 },
  43210. map: { value: null },
  43211. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43212. alphaMap: { value: null },
  43213. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43214. alphaTest: { value: 0 }
  43215. },
  43216. specularmap: {
  43217. specularMap: { value: null },
  43218. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43219. },
  43220. envmap: {
  43221. envMap: { value: null },
  43222. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43223. flipEnvMap: { value: -1 },
  43224. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43225. ior: { value: 1.5 }, // physical
  43226. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43227. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  43228. },
  43229. aomap: {
  43230. aoMap: { value: null },
  43231. aoMapIntensity: { value: 1 },
  43232. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43233. },
  43234. lightmap: {
  43235. lightMap: { value: null },
  43236. lightMapIntensity: { value: 1 },
  43237. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43238. },
  43239. bumpmap: {
  43240. bumpMap: { value: null },
  43241. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43242. bumpScale: { value: 1 }
  43243. },
  43244. normalmap: {
  43245. normalMap: { value: null },
  43246. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43247. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43248. },
  43249. displacementmap: {
  43250. displacementMap: { value: null },
  43251. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43252. displacementScale: { value: 1 },
  43253. displacementBias: { value: 0 }
  43254. },
  43255. emissivemap: {
  43256. emissiveMap: { value: null },
  43257. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43258. },
  43259. metalnessmap: {
  43260. metalnessMap: { value: null },
  43261. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43262. },
  43263. roughnessmap: {
  43264. roughnessMap: { value: null },
  43265. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43266. },
  43267. gradientmap: {
  43268. gradientMap: { value: null }
  43269. },
  43270. fog: {
  43271. fogDensity: { value: 0.00025 },
  43272. fogNear: { value: 1 },
  43273. fogFar: { value: 2000 },
  43274. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43275. },
  43276. lights: {
  43277. ambientLightColor: { value: [] },
  43278. lightProbe: { value: [] },
  43279. directionalLights: { value: [], properties: {
  43280. direction: {},
  43281. color: {}
  43282. } },
  43283. directionalLightShadows: { value: [], properties: {
  43284. shadowIntensity: 1,
  43285. shadowBias: {},
  43286. shadowNormalBias: {},
  43287. shadowRadius: {},
  43288. shadowMapSize: {}
  43289. } },
  43290. directionalShadowMap: { value: [] },
  43291. directionalShadowMatrix: { value: [] },
  43292. spotLights: { value: [], properties: {
  43293. color: {},
  43294. position: {},
  43295. direction: {},
  43296. distance: {},
  43297. coneCos: {},
  43298. penumbraCos: {},
  43299. decay: {}
  43300. } },
  43301. spotLightShadows: { value: [], properties: {
  43302. shadowIntensity: 1,
  43303. shadowBias: {},
  43304. shadowNormalBias: {},
  43305. shadowRadius: {},
  43306. shadowMapSize: {}
  43307. } },
  43308. spotLightMap: { value: [] },
  43309. spotShadowMap: { value: [] },
  43310. spotLightMatrix: { value: [] },
  43311. pointLights: { value: [], properties: {
  43312. color: {},
  43313. position: {},
  43314. decay: {},
  43315. distance: {}
  43316. } },
  43317. pointLightShadows: { value: [], properties: {
  43318. shadowIntensity: 1,
  43319. shadowBias: {},
  43320. shadowNormalBias: {},
  43321. shadowRadius: {},
  43322. shadowMapSize: {},
  43323. shadowCameraNear: {},
  43324. shadowCameraFar: {}
  43325. } },
  43326. pointShadowMap: { value: [] },
  43327. pointShadowMatrix: { value: [] },
  43328. hemisphereLights: { value: [], properties: {
  43329. direction: {},
  43330. skyColor: {},
  43331. groundColor: {}
  43332. } },
  43333. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43334. rectAreaLights: { value: [], properties: {
  43335. color: {},
  43336. position: {},
  43337. width: {},
  43338. height: {}
  43339. } },
  43340. ltc_1: { value: null },
  43341. ltc_2: { value: null }
  43342. },
  43343. points: {
  43344. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43345. opacity: { value: 1.0 },
  43346. size: { value: 1.0 },
  43347. scale: { value: 1.0 },
  43348. map: { value: null },
  43349. alphaMap: { value: null },
  43350. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43351. alphaTest: { value: 0 },
  43352. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43353. },
  43354. sprite: {
  43355. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43356. opacity: { value: 1.0 },
  43357. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43358. rotation: { value: 0.0 },
  43359. map: { value: null },
  43360. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43361. alphaMap: { value: null },
  43362. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43363. alphaTest: { value: 0 }
  43364. }
  43365. };
  43366. const ShaderLib = {
  43367. basic: {
  43368. uniforms: /*@__PURE__*/ mergeUniforms( [
  43369. UniformsLib.common,
  43370. UniformsLib.specularmap,
  43371. UniformsLib.envmap,
  43372. UniformsLib.aomap,
  43373. UniformsLib.lightmap,
  43374. UniformsLib.fog
  43375. ] ),
  43376. vertexShader: ShaderChunk.meshbasic_vert,
  43377. fragmentShader: ShaderChunk.meshbasic_frag
  43378. },
  43379. lambert: {
  43380. uniforms: /*@__PURE__*/ mergeUniforms( [
  43381. UniformsLib.common,
  43382. UniformsLib.specularmap,
  43383. UniformsLib.envmap,
  43384. UniformsLib.aomap,
  43385. UniformsLib.lightmap,
  43386. UniformsLib.emissivemap,
  43387. UniformsLib.bumpmap,
  43388. UniformsLib.normalmap,
  43389. UniformsLib.displacementmap,
  43390. UniformsLib.fog,
  43391. UniformsLib.lights,
  43392. {
  43393. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43394. }
  43395. ] ),
  43396. vertexShader: ShaderChunk.meshlambert_vert,
  43397. fragmentShader: ShaderChunk.meshlambert_frag
  43398. },
  43399. phong: {
  43400. uniforms: /*@__PURE__*/ mergeUniforms( [
  43401. UniformsLib.common,
  43402. UniformsLib.specularmap,
  43403. UniformsLib.envmap,
  43404. UniformsLib.aomap,
  43405. UniformsLib.lightmap,
  43406. UniformsLib.emissivemap,
  43407. UniformsLib.bumpmap,
  43408. UniformsLib.normalmap,
  43409. UniformsLib.displacementmap,
  43410. UniformsLib.fog,
  43411. UniformsLib.lights,
  43412. {
  43413. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43414. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43415. shininess: { value: 30 }
  43416. }
  43417. ] ),
  43418. vertexShader: ShaderChunk.meshphong_vert,
  43419. fragmentShader: ShaderChunk.meshphong_frag
  43420. },
  43421. standard: {
  43422. uniforms: /*@__PURE__*/ mergeUniforms( [
  43423. UniformsLib.common,
  43424. UniformsLib.envmap,
  43425. UniformsLib.aomap,
  43426. UniformsLib.lightmap,
  43427. UniformsLib.emissivemap,
  43428. UniformsLib.bumpmap,
  43429. UniformsLib.normalmap,
  43430. UniformsLib.displacementmap,
  43431. UniformsLib.roughnessmap,
  43432. UniformsLib.metalnessmap,
  43433. UniformsLib.fog,
  43434. UniformsLib.lights,
  43435. {
  43436. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43437. roughness: { value: 1.0 },
  43438. metalness: { value: 0.0 },
  43439. envMapIntensity: { value: 1 }
  43440. }
  43441. ] ),
  43442. vertexShader: ShaderChunk.meshphysical_vert,
  43443. fragmentShader: ShaderChunk.meshphysical_frag
  43444. },
  43445. toon: {
  43446. uniforms: /*@__PURE__*/ mergeUniforms( [
  43447. UniformsLib.common,
  43448. UniformsLib.aomap,
  43449. UniformsLib.lightmap,
  43450. UniformsLib.emissivemap,
  43451. UniformsLib.bumpmap,
  43452. UniformsLib.normalmap,
  43453. UniformsLib.displacementmap,
  43454. UniformsLib.gradientmap,
  43455. UniformsLib.fog,
  43456. UniformsLib.lights,
  43457. {
  43458. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43459. }
  43460. ] ),
  43461. vertexShader: ShaderChunk.meshtoon_vert,
  43462. fragmentShader: ShaderChunk.meshtoon_frag
  43463. },
  43464. matcap: {
  43465. uniforms: /*@__PURE__*/ mergeUniforms( [
  43466. UniformsLib.common,
  43467. UniformsLib.bumpmap,
  43468. UniformsLib.normalmap,
  43469. UniformsLib.displacementmap,
  43470. UniformsLib.fog,
  43471. {
  43472. matcap: { value: null }
  43473. }
  43474. ] ),
  43475. vertexShader: ShaderChunk.meshmatcap_vert,
  43476. fragmentShader: ShaderChunk.meshmatcap_frag
  43477. },
  43478. points: {
  43479. uniforms: /*@__PURE__*/ mergeUniforms( [
  43480. UniformsLib.points,
  43481. UniformsLib.fog
  43482. ] ),
  43483. vertexShader: ShaderChunk.points_vert,
  43484. fragmentShader: ShaderChunk.points_frag
  43485. },
  43486. dashed: {
  43487. uniforms: /*@__PURE__*/ mergeUniforms( [
  43488. UniformsLib.common,
  43489. UniformsLib.fog,
  43490. {
  43491. scale: { value: 1 },
  43492. dashSize: { value: 1 },
  43493. totalSize: { value: 2 }
  43494. }
  43495. ] ),
  43496. vertexShader: ShaderChunk.linedashed_vert,
  43497. fragmentShader: ShaderChunk.linedashed_frag
  43498. },
  43499. depth: {
  43500. uniforms: /*@__PURE__*/ mergeUniforms( [
  43501. UniformsLib.common,
  43502. UniformsLib.displacementmap
  43503. ] ),
  43504. vertexShader: ShaderChunk.depth_vert,
  43505. fragmentShader: ShaderChunk.depth_frag
  43506. },
  43507. normal: {
  43508. uniforms: /*@__PURE__*/ mergeUniforms( [
  43509. UniformsLib.common,
  43510. UniformsLib.bumpmap,
  43511. UniformsLib.normalmap,
  43512. UniformsLib.displacementmap,
  43513. {
  43514. opacity: { value: 1.0 }
  43515. }
  43516. ] ),
  43517. vertexShader: ShaderChunk.meshnormal_vert,
  43518. fragmentShader: ShaderChunk.meshnormal_frag
  43519. },
  43520. sprite: {
  43521. uniforms: /*@__PURE__*/ mergeUniforms( [
  43522. UniformsLib.sprite,
  43523. UniformsLib.fog
  43524. ] ),
  43525. vertexShader: ShaderChunk.sprite_vert,
  43526. fragmentShader: ShaderChunk.sprite_frag
  43527. },
  43528. background: {
  43529. uniforms: {
  43530. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43531. t2D: { value: null },
  43532. backgroundIntensity: { value: 1 }
  43533. },
  43534. vertexShader: ShaderChunk.background_vert,
  43535. fragmentShader: ShaderChunk.background_frag
  43536. },
  43537. backgroundCube: {
  43538. uniforms: {
  43539. envMap: { value: null },
  43540. flipEnvMap: { value: -1 },
  43541. backgroundBlurriness: { value: 0 },
  43542. backgroundIntensity: { value: 1 },
  43543. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43544. },
  43545. vertexShader: ShaderChunk.backgroundCube_vert,
  43546. fragmentShader: ShaderChunk.backgroundCube_frag
  43547. },
  43548. cube: {
  43549. uniforms: {
  43550. tCube: { value: null },
  43551. tFlip: { value: -1 },
  43552. opacity: { value: 1.0 }
  43553. },
  43554. vertexShader: ShaderChunk.cube_vert,
  43555. fragmentShader: ShaderChunk.cube_frag
  43556. },
  43557. equirect: {
  43558. uniforms: {
  43559. tEquirect: { value: null },
  43560. },
  43561. vertexShader: ShaderChunk.equirect_vert,
  43562. fragmentShader: ShaderChunk.equirect_frag
  43563. },
  43564. distance: {
  43565. uniforms: /*@__PURE__*/ mergeUniforms( [
  43566. UniformsLib.common,
  43567. UniformsLib.displacementmap,
  43568. {
  43569. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43570. nearDistance: { value: 1 },
  43571. farDistance: { value: 1000 }
  43572. }
  43573. ] ),
  43574. vertexShader: ShaderChunk.distance_vert,
  43575. fragmentShader: ShaderChunk.distance_frag
  43576. },
  43577. shadow: {
  43578. uniforms: /*@__PURE__*/ mergeUniforms( [
  43579. UniformsLib.lights,
  43580. UniformsLib.fog,
  43581. {
  43582. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43583. opacity: { value: 1.0 }
  43584. },
  43585. ] ),
  43586. vertexShader: ShaderChunk.shadow_vert,
  43587. fragmentShader: ShaderChunk.shadow_frag
  43588. }
  43589. };
  43590. ShaderLib.physical = {
  43591. uniforms: /*@__PURE__*/ mergeUniforms( [
  43592. ShaderLib.standard.uniforms,
  43593. {
  43594. clearcoat: { value: 0 },
  43595. clearcoatMap: { value: null },
  43596. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43597. clearcoatNormalMap: { value: null },
  43598. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43599. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43600. clearcoatRoughness: { value: 0 },
  43601. clearcoatRoughnessMap: { value: null },
  43602. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43603. dispersion: { value: 0 },
  43604. iridescence: { value: 0 },
  43605. iridescenceMap: { value: null },
  43606. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43607. iridescenceIOR: { value: 1.3 },
  43608. iridescenceThicknessMinimum: { value: 100 },
  43609. iridescenceThicknessMaximum: { value: 400 },
  43610. iridescenceThicknessMap: { value: null },
  43611. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43612. sheen: { value: 0 },
  43613. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43614. sheenColorMap: { value: null },
  43615. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43616. sheenRoughness: { value: 1 },
  43617. sheenRoughnessMap: { value: null },
  43618. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43619. transmission: { value: 0 },
  43620. transmissionMap: { value: null },
  43621. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43622. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43623. transmissionSamplerMap: { value: null },
  43624. thickness: { value: 0 },
  43625. thicknessMap: { value: null },
  43626. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43627. attenuationDistance: { value: 0 },
  43628. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43629. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43630. specularColorMap: { value: null },
  43631. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43632. specularIntensity: { value: 1 },
  43633. specularIntensityMap: { value: null },
  43634. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43635. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43636. anisotropyMap: { value: null },
  43637. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43638. }
  43639. ] ),
  43640. vertexShader: ShaderChunk.meshphysical_vert,
  43641. fragmentShader: ShaderChunk.meshphysical_frag
  43642. };
  43643. const _rgb = { r: 0, b: 0, g: 0 };
  43644. const _e1$1 = /*@__PURE__*/ new Euler();
  43645. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43646. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43647. const clearColor = new Color( 0x000000 );
  43648. let clearAlpha = alpha === true ? 0 : 1;
  43649. let planeMesh;
  43650. let boxMesh;
  43651. let currentBackground = null;
  43652. let currentBackgroundVersion = 0;
  43653. let currentTonemapping = null;
  43654. function getBackground( scene ) {
  43655. let background = scene.isScene === true ? scene.background : null;
  43656. if ( background && background.isTexture ) {
  43657. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43658. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43659. }
  43660. return background;
  43661. }
  43662. function render( scene ) {
  43663. let forceClear = false;
  43664. const background = getBackground( scene );
  43665. if ( background === null ) {
  43666. setClear( clearColor, clearAlpha );
  43667. } else if ( background && background.isColor ) {
  43668. setClear( background, 1 );
  43669. forceClear = true;
  43670. }
  43671. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43672. if ( environmentBlendMode === 'additive' ) {
  43673. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43674. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43675. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43676. }
  43677. if ( renderer.autoClear || forceClear ) {
  43678. // buffers might not be writable which is required to ensure a correct clear
  43679. state.buffers.depth.setTest( true );
  43680. state.buffers.depth.setMask( true );
  43681. state.buffers.color.setMask( true );
  43682. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43683. }
  43684. }
  43685. function addToRenderList( renderList, scene ) {
  43686. const background = getBackground( scene );
  43687. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43688. if ( boxMesh === undefined ) {
  43689. boxMesh = new Mesh(
  43690. new BoxGeometry( 1, 1, 1 ),
  43691. new ShaderMaterial( {
  43692. name: 'BackgroundCubeMaterial',
  43693. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43694. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43695. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43696. side: BackSide,
  43697. depthTest: false,
  43698. depthWrite: false,
  43699. fog: false,
  43700. allowOverride: false
  43701. } )
  43702. );
  43703. boxMesh.geometry.deleteAttribute( 'normal' );
  43704. boxMesh.geometry.deleteAttribute( 'uv' );
  43705. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43706. this.matrixWorld.copyPosition( camera.matrixWorld );
  43707. };
  43708. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43709. Object.defineProperty( boxMesh.material, 'envMap', {
  43710. get: function () {
  43711. return this.uniforms.envMap.value;
  43712. }
  43713. } );
  43714. objects.update( boxMesh );
  43715. }
  43716. _e1$1.copy( scene.backgroundRotation );
  43717. // accommodate left-handed frame
  43718. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43719. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43720. // environment maps which are not cube render targets or PMREMs follow a different convention
  43721. _e1$1.y *= -1;
  43722. _e1$1.z *= -1;
  43723. }
  43724. boxMesh.material.uniforms.envMap.value = background;
  43725. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43726. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43727. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43728. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43729. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43730. if ( currentBackground !== background ||
  43731. currentBackgroundVersion !== background.version ||
  43732. currentTonemapping !== renderer.toneMapping ) {
  43733. boxMesh.material.needsUpdate = true;
  43734. currentBackground = background;
  43735. currentBackgroundVersion = background.version;
  43736. currentTonemapping = renderer.toneMapping;
  43737. }
  43738. boxMesh.layers.enableAll();
  43739. // push to the pre-sorted opaque render list
  43740. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43741. } else if ( background && background.isTexture ) {
  43742. if ( planeMesh === undefined ) {
  43743. planeMesh = new Mesh(
  43744. new PlaneGeometry( 2, 2 ),
  43745. new ShaderMaterial( {
  43746. name: 'BackgroundMaterial',
  43747. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43748. vertexShader: ShaderLib.background.vertexShader,
  43749. fragmentShader: ShaderLib.background.fragmentShader,
  43750. side: FrontSide,
  43751. depthTest: false,
  43752. depthWrite: false,
  43753. fog: false,
  43754. allowOverride: false
  43755. } )
  43756. );
  43757. planeMesh.geometry.deleteAttribute( 'normal' );
  43758. // add "map" material property so the renderer can evaluate it like for built-in materials
  43759. Object.defineProperty( planeMesh.material, 'map', {
  43760. get: function () {
  43761. return this.uniforms.t2D.value;
  43762. }
  43763. } );
  43764. objects.update( planeMesh );
  43765. }
  43766. planeMesh.material.uniforms.t2D.value = background;
  43767. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43768. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43769. if ( background.matrixAutoUpdate === true ) {
  43770. background.updateMatrix();
  43771. }
  43772. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43773. if ( currentBackground !== background ||
  43774. currentBackgroundVersion !== background.version ||
  43775. currentTonemapping !== renderer.toneMapping ) {
  43776. planeMesh.material.needsUpdate = true;
  43777. currentBackground = background;
  43778. currentBackgroundVersion = background.version;
  43779. currentTonemapping = renderer.toneMapping;
  43780. }
  43781. planeMesh.layers.enableAll();
  43782. // push to the pre-sorted opaque render list
  43783. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43784. }
  43785. }
  43786. function setClear( color, alpha ) {
  43787. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43788. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43789. }
  43790. function dispose() {
  43791. if ( boxMesh !== undefined ) {
  43792. boxMesh.geometry.dispose();
  43793. boxMesh.material.dispose();
  43794. boxMesh = undefined;
  43795. }
  43796. if ( planeMesh !== undefined ) {
  43797. planeMesh.geometry.dispose();
  43798. planeMesh.material.dispose();
  43799. planeMesh = undefined;
  43800. }
  43801. }
  43802. return {
  43803. getClearColor: function () {
  43804. return clearColor;
  43805. },
  43806. setClearColor: function ( color, alpha = 1 ) {
  43807. clearColor.set( color );
  43808. clearAlpha = alpha;
  43809. setClear( clearColor, clearAlpha );
  43810. },
  43811. getClearAlpha: function () {
  43812. return clearAlpha;
  43813. },
  43814. setClearAlpha: function ( alpha ) {
  43815. clearAlpha = alpha;
  43816. setClear( clearColor, clearAlpha );
  43817. },
  43818. render: render,
  43819. addToRenderList: addToRenderList,
  43820. dispose: dispose
  43821. };
  43822. }
  43823. function WebGLBindingStates( gl, attributes ) {
  43824. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43825. const bindingStates = {};
  43826. const defaultState = createBindingState( null );
  43827. let currentState = defaultState;
  43828. let forceUpdate = false;
  43829. function setup( object, material, program, geometry, index ) {
  43830. let updateBuffers = false;
  43831. const state = getBindingState( geometry, program, material );
  43832. if ( currentState !== state ) {
  43833. currentState = state;
  43834. bindVertexArrayObject( currentState.object );
  43835. }
  43836. updateBuffers = needsUpdate( object, geometry, program, index );
  43837. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43838. if ( index !== null ) {
  43839. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43840. }
  43841. if ( updateBuffers || forceUpdate ) {
  43842. forceUpdate = false;
  43843. setupVertexAttributes( object, material, program, geometry );
  43844. if ( index !== null ) {
  43845. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43846. }
  43847. }
  43848. }
  43849. function createVertexArrayObject() {
  43850. return gl.createVertexArray();
  43851. }
  43852. function bindVertexArrayObject( vao ) {
  43853. return gl.bindVertexArray( vao );
  43854. }
  43855. function deleteVertexArrayObject( vao ) {
  43856. return gl.deleteVertexArray( vao );
  43857. }
  43858. function getBindingState( geometry, program, material ) {
  43859. const wireframe = ( material.wireframe === true );
  43860. let programMap = bindingStates[ geometry.id ];
  43861. if ( programMap === undefined ) {
  43862. programMap = {};
  43863. bindingStates[ geometry.id ] = programMap;
  43864. }
  43865. let stateMap = programMap[ program.id ];
  43866. if ( stateMap === undefined ) {
  43867. stateMap = {};
  43868. programMap[ program.id ] = stateMap;
  43869. }
  43870. let state = stateMap[ wireframe ];
  43871. if ( state === undefined ) {
  43872. state = createBindingState( createVertexArrayObject() );
  43873. stateMap[ wireframe ] = state;
  43874. }
  43875. return state;
  43876. }
  43877. function createBindingState( vao ) {
  43878. const newAttributes = [];
  43879. const enabledAttributes = [];
  43880. const attributeDivisors = [];
  43881. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43882. newAttributes[ i ] = 0;
  43883. enabledAttributes[ i ] = 0;
  43884. attributeDivisors[ i ] = 0;
  43885. }
  43886. return {
  43887. // for backward compatibility on non-VAO support browser
  43888. geometry: null,
  43889. program: null,
  43890. wireframe: false,
  43891. newAttributes: newAttributes,
  43892. enabledAttributes: enabledAttributes,
  43893. attributeDivisors: attributeDivisors,
  43894. object: vao,
  43895. attributes: {},
  43896. index: null
  43897. };
  43898. }
  43899. function needsUpdate( object, geometry, program, index ) {
  43900. const cachedAttributes = currentState.attributes;
  43901. const geometryAttributes = geometry.attributes;
  43902. let attributesNum = 0;
  43903. const programAttributes = program.getAttributes();
  43904. for ( const name in programAttributes ) {
  43905. const programAttribute = programAttributes[ name ];
  43906. if ( programAttribute.location >= 0 ) {
  43907. const cachedAttribute = cachedAttributes[ name ];
  43908. let geometryAttribute = geometryAttributes[ name ];
  43909. if ( geometryAttribute === undefined ) {
  43910. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43911. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43912. }
  43913. if ( cachedAttribute === undefined ) return true;
  43914. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43915. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43916. attributesNum ++;
  43917. }
  43918. }
  43919. if ( currentState.attributesNum !== attributesNum ) return true;
  43920. if ( currentState.index !== index ) return true;
  43921. return false;
  43922. }
  43923. function saveCache( object, geometry, program, index ) {
  43924. const cache = {};
  43925. const attributes = geometry.attributes;
  43926. let attributesNum = 0;
  43927. const programAttributes = program.getAttributes();
  43928. for ( const name in programAttributes ) {
  43929. const programAttribute = programAttributes[ name ];
  43930. if ( programAttribute.location >= 0 ) {
  43931. let attribute = attributes[ name ];
  43932. if ( attribute === undefined ) {
  43933. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43934. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43935. }
  43936. const data = {};
  43937. data.attribute = attribute;
  43938. if ( attribute && attribute.data ) {
  43939. data.data = attribute.data;
  43940. }
  43941. cache[ name ] = data;
  43942. attributesNum ++;
  43943. }
  43944. }
  43945. currentState.attributes = cache;
  43946. currentState.attributesNum = attributesNum;
  43947. currentState.index = index;
  43948. }
  43949. function initAttributes() {
  43950. const newAttributes = currentState.newAttributes;
  43951. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43952. newAttributes[ i ] = 0;
  43953. }
  43954. }
  43955. function enableAttribute( attribute ) {
  43956. enableAttributeAndDivisor( attribute, 0 );
  43957. }
  43958. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43959. const newAttributes = currentState.newAttributes;
  43960. const enabledAttributes = currentState.enabledAttributes;
  43961. const attributeDivisors = currentState.attributeDivisors;
  43962. newAttributes[ attribute ] = 1;
  43963. if ( enabledAttributes[ attribute ] === 0 ) {
  43964. gl.enableVertexAttribArray( attribute );
  43965. enabledAttributes[ attribute ] = 1;
  43966. }
  43967. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  43968. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  43969. attributeDivisors[ attribute ] = meshPerAttribute;
  43970. }
  43971. }
  43972. function disableUnusedAttributes() {
  43973. const newAttributes = currentState.newAttributes;
  43974. const enabledAttributes = currentState.enabledAttributes;
  43975. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  43976. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  43977. gl.disableVertexAttribArray( i );
  43978. enabledAttributes[ i ] = 0;
  43979. }
  43980. }
  43981. }
  43982. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  43983. if ( integer === true ) {
  43984. gl.vertexAttribIPointer( index, size, type, stride, offset );
  43985. } else {
  43986. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  43987. }
  43988. }
  43989. function setupVertexAttributes( object, material, program, geometry ) {
  43990. initAttributes();
  43991. const geometryAttributes = geometry.attributes;
  43992. const programAttributes = program.getAttributes();
  43993. const materialDefaultAttributeValues = material.defaultAttributeValues;
  43994. for ( const name in programAttributes ) {
  43995. const programAttribute = programAttributes[ name ];
  43996. if ( programAttribute.location >= 0 ) {
  43997. let geometryAttribute = geometryAttributes[ name ];
  43998. if ( geometryAttribute === undefined ) {
  43999. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44000. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44001. }
  44002. if ( geometryAttribute !== undefined ) {
  44003. const normalized = geometryAttribute.normalized;
  44004. const size = geometryAttribute.itemSize;
  44005. const attribute = attributes.get( geometryAttribute );
  44006. // TODO Attribute may not be available on context restore
  44007. if ( attribute === undefined ) continue;
  44008. const buffer = attribute.buffer;
  44009. const type = attribute.type;
  44010. const bytesPerElement = attribute.bytesPerElement;
  44011. // check for integer attributes
  44012. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  44013. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  44014. const data = geometryAttribute.data;
  44015. const stride = data.stride;
  44016. const offset = geometryAttribute.offset;
  44017. if ( data.isInstancedInterleavedBuffer ) {
  44018. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44019. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  44020. }
  44021. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44022. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  44023. }
  44024. } else {
  44025. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44026. enableAttribute( programAttribute.location + i );
  44027. }
  44028. }
  44029. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44030. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44031. vertexAttribPointer(
  44032. programAttribute.location + i,
  44033. size / programAttribute.locationSize,
  44034. type,
  44035. normalized,
  44036. stride * bytesPerElement,
  44037. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  44038. integer
  44039. );
  44040. }
  44041. } else {
  44042. if ( geometryAttribute.isInstancedBufferAttribute ) {
  44043. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44044. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  44045. }
  44046. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44047. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  44048. }
  44049. } else {
  44050. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44051. enableAttribute( programAttribute.location + i );
  44052. }
  44053. }
  44054. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44055. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44056. vertexAttribPointer(
  44057. programAttribute.location + i,
  44058. size / programAttribute.locationSize,
  44059. type,
  44060. normalized,
  44061. size * bytesPerElement,
  44062. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  44063. integer
  44064. );
  44065. }
  44066. }
  44067. } else if ( materialDefaultAttributeValues !== undefined ) {
  44068. const value = materialDefaultAttributeValues[ name ];
  44069. if ( value !== undefined ) {
  44070. switch ( value.length ) {
  44071. case 2:
  44072. gl.vertexAttrib2fv( programAttribute.location, value );
  44073. break;
  44074. case 3:
  44075. gl.vertexAttrib3fv( programAttribute.location, value );
  44076. break;
  44077. case 4:
  44078. gl.vertexAttrib4fv( programAttribute.location, value );
  44079. break;
  44080. default:
  44081. gl.vertexAttrib1fv( programAttribute.location, value );
  44082. }
  44083. }
  44084. }
  44085. }
  44086. }
  44087. disableUnusedAttributes();
  44088. }
  44089. function dispose() {
  44090. reset();
  44091. for ( const geometryId in bindingStates ) {
  44092. const programMap = bindingStates[ geometryId ];
  44093. for ( const programId in programMap ) {
  44094. const stateMap = programMap[ programId ];
  44095. for ( const wireframe in stateMap ) {
  44096. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44097. delete stateMap[ wireframe ];
  44098. }
  44099. delete programMap[ programId ];
  44100. }
  44101. delete bindingStates[ geometryId ];
  44102. }
  44103. }
  44104. function releaseStatesOfGeometry( geometry ) {
  44105. if ( bindingStates[ geometry.id ] === undefined ) return;
  44106. const programMap = bindingStates[ geometry.id ];
  44107. for ( const programId in programMap ) {
  44108. const stateMap = programMap[ programId ];
  44109. for ( const wireframe in stateMap ) {
  44110. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44111. delete stateMap[ wireframe ];
  44112. }
  44113. delete programMap[ programId ];
  44114. }
  44115. delete bindingStates[ geometry.id ];
  44116. }
  44117. function releaseStatesOfProgram( program ) {
  44118. for ( const geometryId in bindingStates ) {
  44119. const programMap = bindingStates[ geometryId ];
  44120. if ( programMap[ program.id ] === undefined ) continue;
  44121. const stateMap = programMap[ program.id ];
  44122. for ( const wireframe in stateMap ) {
  44123. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44124. delete stateMap[ wireframe ];
  44125. }
  44126. delete programMap[ program.id ];
  44127. }
  44128. }
  44129. function reset() {
  44130. resetDefaultState();
  44131. forceUpdate = true;
  44132. if ( currentState === defaultState ) return;
  44133. currentState = defaultState;
  44134. bindVertexArrayObject( currentState.object );
  44135. }
  44136. // for backward-compatibility
  44137. function resetDefaultState() {
  44138. defaultState.geometry = null;
  44139. defaultState.program = null;
  44140. defaultState.wireframe = false;
  44141. }
  44142. return {
  44143. setup: setup,
  44144. reset: reset,
  44145. resetDefaultState: resetDefaultState,
  44146. dispose: dispose,
  44147. releaseStatesOfGeometry: releaseStatesOfGeometry,
  44148. releaseStatesOfProgram: releaseStatesOfProgram,
  44149. initAttributes: initAttributes,
  44150. enableAttribute: enableAttribute,
  44151. disableUnusedAttributes: disableUnusedAttributes
  44152. };
  44153. }
  44154. function WebGLBufferRenderer( gl, extensions, info ) {
  44155. let mode;
  44156. function setMode( value ) {
  44157. mode = value;
  44158. }
  44159. function render( start, count ) {
  44160. gl.drawArrays( mode, start, count );
  44161. info.update( count, mode, 1 );
  44162. }
  44163. function renderInstances( start, count, primcount ) {
  44164. if ( primcount === 0 ) return;
  44165. gl.drawArraysInstanced( mode, start, count, primcount );
  44166. info.update( count, mode, primcount );
  44167. }
  44168. function renderMultiDraw( starts, counts, drawCount ) {
  44169. if ( drawCount === 0 ) return;
  44170. const extension = extensions.get( 'WEBGL_multi_draw' );
  44171. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44172. let elementCount = 0;
  44173. for ( let i = 0; i < drawCount; i ++ ) {
  44174. elementCount += counts[ i ];
  44175. }
  44176. info.update( elementCount, mode, 1 );
  44177. }
  44178. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44179. if ( drawCount === 0 ) return;
  44180. const extension = extensions.get( 'WEBGL_multi_draw' );
  44181. if ( extension === null ) {
  44182. for ( let i = 0; i < starts.length; i ++ ) {
  44183. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44184. }
  44185. } else {
  44186. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44187. let elementCount = 0;
  44188. for ( let i = 0; i < drawCount; i ++ ) {
  44189. elementCount += counts[ i ] * primcount[ i ];
  44190. }
  44191. info.update( elementCount, mode, 1 );
  44192. }
  44193. }
  44194. //
  44195. this.setMode = setMode;
  44196. this.render = render;
  44197. this.renderInstances = renderInstances;
  44198. this.renderMultiDraw = renderMultiDraw;
  44199. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44200. }
  44201. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44202. let maxAnisotropy;
  44203. function getMaxAnisotropy() {
  44204. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44205. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44206. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44207. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44208. } else {
  44209. maxAnisotropy = 0;
  44210. }
  44211. return maxAnisotropy;
  44212. }
  44213. function textureFormatReadable( textureFormat ) {
  44214. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44215. return false;
  44216. }
  44217. return true;
  44218. }
  44219. function textureTypeReadable( textureType ) {
  44220. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44221. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44222. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44223. return false;
  44224. }
  44225. return true;
  44226. }
  44227. function getMaxPrecision( precision ) {
  44228. if ( precision === 'highp' ) {
  44229. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44230. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44231. return 'highp';
  44232. }
  44233. precision = 'mediump';
  44234. }
  44235. if ( precision === 'mediump' ) {
  44236. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44237. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44238. return 'mediump';
  44239. }
  44240. }
  44241. return 'lowp';
  44242. }
  44243. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44244. const maxPrecision = getMaxPrecision( precision );
  44245. if ( maxPrecision !== precision ) {
  44246. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44247. precision = maxPrecision;
  44248. }
  44249. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44250. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44251. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44252. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44253. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44254. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44255. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44256. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44257. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44258. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44259. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44260. const samples = gl.getParameter( gl.SAMPLES );
  44261. return {
  44262. isWebGL2: true, // keeping this for backwards compatibility
  44263. getMaxAnisotropy: getMaxAnisotropy,
  44264. getMaxPrecision: getMaxPrecision,
  44265. textureFormatReadable: textureFormatReadable,
  44266. textureTypeReadable: textureTypeReadable,
  44267. precision: precision,
  44268. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44269. reversedDepthBuffer: reversedDepthBuffer,
  44270. maxTextures: maxTextures,
  44271. maxVertexTextures: maxVertexTextures,
  44272. maxTextureSize: maxTextureSize,
  44273. maxCubemapSize: maxCubemapSize,
  44274. maxAttributes: maxAttributes,
  44275. maxVertexUniforms: maxVertexUniforms,
  44276. maxVaryings: maxVaryings,
  44277. maxFragmentUniforms: maxFragmentUniforms,
  44278. maxSamples: maxSamples,
  44279. samples: samples
  44280. };
  44281. }
  44282. function WebGLClipping( properties ) {
  44283. const scope = this;
  44284. let globalState = null,
  44285. numGlobalPlanes = 0,
  44286. localClippingEnabled = false,
  44287. renderingShadows = false;
  44288. const plane = new Plane(),
  44289. viewNormalMatrix = new Matrix3(),
  44290. uniform = { value: null, needsUpdate: false };
  44291. this.uniform = uniform;
  44292. this.numPlanes = 0;
  44293. this.numIntersection = 0;
  44294. this.init = function ( planes, enableLocalClipping ) {
  44295. const enabled =
  44296. planes.length !== 0 ||
  44297. enableLocalClipping ||
  44298. // enable state of previous frame - the clipping code has to
  44299. // run another frame in order to reset the state:
  44300. numGlobalPlanes !== 0 ||
  44301. localClippingEnabled;
  44302. localClippingEnabled = enableLocalClipping;
  44303. numGlobalPlanes = planes.length;
  44304. return enabled;
  44305. };
  44306. this.beginShadows = function () {
  44307. renderingShadows = true;
  44308. projectPlanes( null );
  44309. };
  44310. this.endShadows = function () {
  44311. renderingShadows = false;
  44312. };
  44313. this.setGlobalState = function ( planes, camera ) {
  44314. globalState = projectPlanes( planes, camera, 0 );
  44315. };
  44316. this.setState = function ( material, camera, useCache ) {
  44317. const planes = material.clippingPlanes,
  44318. clipIntersection = material.clipIntersection,
  44319. clipShadows = material.clipShadows;
  44320. const materialProperties = properties.get( material );
  44321. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44322. // there's no local clipping
  44323. if ( renderingShadows ) {
  44324. // there's no global clipping
  44325. projectPlanes( null );
  44326. } else {
  44327. resetGlobalState();
  44328. }
  44329. } else {
  44330. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44331. lGlobal = nGlobal * 4;
  44332. let dstArray = materialProperties.clippingState || null;
  44333. uniform.value = dstArray; // ensure unique state
  44334. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44335. for ( let i = 0; i !== lGlobal; ++ i ) {
  44336. dstArray[ i ] = globalState[ i ];
  44337. }
  44338. materialProperties.clippingState = dstArray;
  44339. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44340. this.numPlanes += nGlobal;
  44341. }
  44342. };
  44343. function resetGlobalState() {
  44344. if ( uniform.value !== globalState ) {
  44345. uniform.value = globalState;
  44346. uniform.needsUpdate = numGlobalPlanes > 0;
  44347. }
  44348. scope.numPlanes = numGlobalPlanes;
  44349. scope.numIntersection = 0;
  44350. }
  44351. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44352. const nPlanes = planes !== null ? planes.length : 0;
  44353. let dstArray = null;
  44354. if ( nPlanes !== 0 ) {
  44355. dstArray = uniform.value;
  44356. if ( skipTransform !== true || dstArray === null ) {
  44357. const flatSize = dstOffset + nPlanes * 4,
  44358. viewMatrix = camera.matrixWorldInverse;
  44359. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44360. if ( dstArray === null || dstArray.length < flatSize ) {
  44361. dstArray = new Float32Array( flatSize );
  44362. }
  44363. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44364. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44365. plane.normal.toArray( dstArray, i4 );
  44366. dstArray[ i4 + 3 ] = plane.constant;
  44367. }
  44368. }
  44369. uniform.value = dstArray;
  44370. uniform.needsUpdate = true;
  44371. }
  44372. scope.numPlanes = nPlanes;
  44373. scope.numIntersection = 0;
  44374. return dstArray;
  44375. }
  44376. }
  44377. function WebGLCubeMaps( renderer ) {
  44378. let cubemaps = new WeakMap();
  44379. function mapTextureMapping( texture, mapping ) {
  44380. if ( mapping === EquirectangularReflectionMapping ) {
  44381. texture.mapping = CubeReflectionMapping;
  44382. } else if ( mapping === EquirectangularRefractionMapping ) {
  44383. texture.mapping = CubeRefractionMapping;
  44384. }
  44385. return texture;
  44386. }
  44387. function get( texture ) {
  44388. if ( texture && texture.isTexture ) {
  44389. const mapping = texture.mapping;
  44390. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44391. if ( cubemaps.has( texture ) ) {
  44392. const cubemap = cubemaps.get( texture ).texture;
  44393. return mapTextureMapping( cubemap, texture.mapping );
  44394. } else {
  44395. const image = texture.image;
  44396. if ( image && image.height > 0 ) {
  44397. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44398. renderTarget.fromEquirectangularTexture( renderer, texture );
  44399. cubemaps.set( texture, renderTarget );
  44400. texture.addEventListener( 'dispose', onTextureDispose );
  44401. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44402. } else {
  44403. // image not yet ready. try the conversion next frame
  44404. return null;
  44405. }
  44406. }
  44407. }
  44408. }
  44409. return texture;
  44410. }
  44411. function onTextureDispose( event ) {
  44412. const texture = event.target;
  44413. texture.removeEventListener( 'dispose', onTextureDispose );
  44414. const cubemap = cubemaps.get( texture );
  44415. if ( cubemap !== undefined ) {
  44416. cubemaps.delete( texture );
  44417. cubemap.dispose();
  44418. }
  44419. }
  44420. function dispose() {
  44421. cubemaps = new WeakMap();
  44422. }
  44423. return {
  44424. get: get,
  44425. dispose: dispose
  44426. };
  44427. }
  44428. const LOD_MIN = 4;
  44429. // The standard deviations (radians) associated with the extra mips.
  44430. // Used for scene blur in fromScene() method.
  44431. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44432. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44433. // samples and exit early, but not recompile the shader.
  44434. // Used for scene blur in fromScene() method.
  44435. const MAX_SAMPLES = 20;
  44436. // GGX VNDF importance sampling configuration
  44437. const GGX_SAMPLES = 256;
  44438. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44439. const _clearColor = /*@__PURE__*/ new Color();
  44440. let _oldTarget = null;
  44441. let _oldActiveCubeFace = 0;
  44442. let _oldActiveMipmapLevel = 0;
  44443. let _oldXrEnabled = false;
  44444. const _origin = /*@__PURE__*/ new Vector3();
  44445. /**
  44446. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44447. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44448. * blur to be quickly accessed based on material roughness. It is packed into a
  44449. * special CubeUV format that allows us to perform custom interpolation so that
  44450. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44451. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44452. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44453. * higher roughness levels. In this way we maintain resolution to smoothly
  44454. * interpolate diffuse lighting while limiting sampling computation.
  44455. *
  44456. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  44457. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  44458. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  44459. * used in material rendering for physically-based image-based lighting.
  44460. */
  44461. class PMREMGenerator {
  44462. /**
  44463. * Constructs a new PMREM generator.
  44464. *
  44465. * @param {WebGLRenderer} renderer - The renderer.
  44466. */
  44467. constructor( renderer ) {
  44468. this._renderer = renderer;
  44469. this._pingPongRenderTarget = null;
  44470. this._lodMax = 0;
  44471. this._cubeSize = 0;
  44472. this._sizeLods = [];
  44473. this._sigmas = [];
  44474. this._lodMeshes = [];
  44475. this._backgroundBox = null;
  44476. this._cubemapMaterial = null;
  44477. this._equirectMaterial = null;
  44478. this._blurMaterial = null;
  44479. this._ggxMaterial = null;
  44480. }
  44481. /**
  44482. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44483. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44484. * in radians to be applied to the scene before PMREM generation. Optional near
  44485. * and far planes ensure the scene is rendered in its entirety.
  44486. *
  44487. * @param {Scene} scene - The scene to be captured.
  44488. * @param {number} [sigma=0] - The blur radius in radians.
  44489. * @param {number} [near=0.1] - The near plane distance.
  44490. * @param {number} [far=100] - The far plane distance.
  44491. * @param {Object} [options={}] - The configuration options.
  44492. * @param {number} [options.size=256] - The texture size of the PMREM.
  44493. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  44494. * @return {WebGLRenderTarget} The resulting PMREM.
  44495. */
  44496. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44497. const {
  44498. size = 256,
  44499. position = _origin,
  44500. } = options;
  44501. _oldTarget = this._renderer.getRenderTarget();
  44502. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44503. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44504. _oldXrEnabled = this._renderer.xr.enabled;
  44505. this._renderer.xr.enabled = false;
  44506. this._setSize( size );
  44507. const cubeUVRenderTarget = this._allocateTargets();
  44508. cubeUVRenderTarget.depthBuffer = true;
  44509. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44510. if ( sigma > 0 ) {
  44511. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44512. }
  44513. this._applyPMREM( cubeUVRenderTarget );
  44514. this._cleanup( cubeUVRenderTarget );
  44515. return cubeUVRenderTarget;
  44516. }
  44517. /**
  44518. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44519. * or HDR. The ideal input image size is 1k (1024 x 512),
  44520. * as this matches best with the 256 x 256 cubemap output.
  44521. *
  44522. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44523. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44524. * @return {WebGLRenderTarget} The resulting PMREM.
  44525. */
  44526. fromEquirectangular( equirectangular, renderTarget = null ) {
  44527. return this._fromTexture( equirectangular, renderTarget );
  44528. }
  44529. /**
  44530. * Generates a PMREM from an cubemap texture, which can be either LDR
  44531. * or HDR. The ideal input cube size is 256 x 256,
  44532. * as this matches best with the 256 x 256 cubemap output.
  44533. *
  44534. * @param {Texture} cubemap - The cubemap texture to be converted.
  44535. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44536. * @return {WebGLRenderTarget} The resulting PMREM.
  44537. */
  44538. fromCubemap( cubemap, renderTarget = null ) {
  44539. return this._fromTexture( cubemap, renderTarget );
  44540. }
  44541. /**
  44542. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44543. * your texture's network fetch for increased concurrency.
  44544. */
  44545. compileCubemapShader() {
  44546. if ( this._cubemapMaterial === null ) {
  44547. this._cubemapMaterial = _getCubemapMaterial();
  44548. this._compileMaterial( this._cubemapMaterial );
  44549. }
  44550. }
  44551. /**
  44552. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44553. * your texture's network fetch for increased concurrency.
  44554. */
  44555. compileEquirectangularShader() {
  44556. if ( this._equirectMaterial === null ) {
  44557. this._equirectMaterial = _getEquirectMaterial();
  44558. this._compileMaterial( this._equirectMaterial );
  44559. }
  44560. }
  44561. /**
  44562. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44563. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44564. * one of them will cause any others to also become unusable.
  44565. */
  44566. dispose() {
  44567. this._dispose();
  44568. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44569. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44570. if ( this._backgroundBox !== null ) {
  44571. this._backgroundBox.geometry.dispose();
  44572. this._backgroundBox.material.dispose();
  44573. }
  44574. }
  44575. // private interface
  44576. _setSize( cubeSize ) {
  44577. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44578. this._cubeSize = Math.pow( 2, this._lodMax );
  44579. }
  44580. _dispose() {
  44581. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44582. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  44583. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44584. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  44585. this._lodMeshes[ i ].geometry.dispose();
  44586. }
  44587. }
  44588. _cleanup( outputTarget ) {
  44589. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44590. this._renderer.xr.enabled = _oldXrEnabled;
  44591. outputTarget.scissorTest = false;
  44592. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44593. }
  44594. _fromTexture( texture, renderTarget ) {
  44595. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44596. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44597. } else { // Equirectangular
  44598. this._setSize( texture.image.width / 4 );
  44599. }
  44600. _oldTarget = this._renderer.getRenderTarget();
  44601. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44602. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44603. _oldXrEnabled = this._renderer.xr.enabled;
  44604. this._renderer.xr.enabled = false;
  44605. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44606. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44607. this._applyPMREM( cubeUVRenderTarget );
  44608. this._cleanup( cubeUVRenderTarget );
  44609. return cubeUVRenderTarget;
  44610. }
  44611. _allocateTargets() {
  44612. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44613. const height = 4 * this._cubeSize;
  44614. const params = {
  44615. magFilter: LinearFilter,
  44616. minFilter: LinearFilter,
  44617. generateMipmaps: false,
  44618. type: HalfFloatType,
  44619. format: RGBAFormat,
  44620. colorSpace: LinearSRGBColorSpace,
  44621. depthBuffer: false
  44622. };
  44623. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44624. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44625. if ( this._pingPongRenderTarget !== null ) {
  44626. this._dispose();
  44627. }
  44628. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44629. const { _lodMax } = this;
  44630. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44631. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44632. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  44633. }
  44634. return cubeUVRenderTarget;
  44635. }
  44636. _compileMaterial( material ) {
  44637. const mesh = new Mesh( new BufferGeometry(), material );
  44638. this._renderer.compile( mesh, _flatCamera );
  44639. }
  44640. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44641. const fov = 90;
  44642. const aspect = 1;
  44643. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44644. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44645. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44646. const renderer = this._renderer;
  44647. const originalAutoClear = renderer.autoClear;
  44648. const toneMapping = renderer.toneMapping;
  44649. renderer.getClearColor( _clearColor );
  44650. renderer.toneMapping = NoToneMapping;
  44651. renderer.autoClear = false;
  44652. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44653. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44654. if ( reversedDepthBuffer ) {
  44655. renderer.setRenderTarget( cubeUVRenderTarget );
  44656. renderer.clearDepth();
  44657. renderer.setRenderTarget( null );
  44658. }
  44659. if ( this._backgroundBox === null ) {
  44660. this._backgroundBox = new Mesh(
  44661. new BoxGeometry(),
  44662. new MeshBasicMaterial( {
  44663. name: 'PMREM.Background',
  44664. side: BackSide,
  44665. depthWrite: false,
  44666. depthTest: false,
  44667. } )
  44668. );
  44669. }
  44670. const backgroundBox = this._backgroundBox;
  44671. const backgroundMaterial = backgroundBox.material;
  44672. let useSolidColor = false;
  44673. const background = scene.background;
  44674. if ( background ) {
  44675. if ( background.isColor ) {
  44676. backgroundMaterial.color.copy( background );
  44677. scene.background = null;
  44678. useSolidColor = true;
  44679. }
  44680. } else {
  44681. backgroundMaterial.color.copy( _clearColor );
  44682. useSolidColor = true;
  44683. }
  44684. for ( let i = 0; i < 6; i ++ ) {
  44685. const col = i % 3;
  44686. if ( col === 0 ) {
  44687. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44688. cubeCamera.position.set( position.x, position.y, position.z );
  44689. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44690. } else if ( col === 1 ) {
  44691. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44692. cubeCamera.position.set( position.x, position.y, position.z );
  44693. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44694. } else {
  44695. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44696. cubeCamera.position.set( position.x, position.y, position.z );
  44697. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44698. }
  44699. const size = this._cubeSize;
  44700. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44701. renderer.setRenderTarget( cubeUVRenderTarget );
  44702. if ( useSolidColor ) {
  44703. renderer.render( backgroundBox, cubeCamera );
  44704. }
  44705. renderer.render( scene, cubeCamera );
  44706. }
  44707. renderer.toneMapping = toneMapping;
  44708. renderer.autoClear = originalAutoClear;
  44709. scene.background = background;
  44710. }
  44711. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44712. const renderer = this._renderer;
  44713. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44714. if ( isCubeTexture ) {
  44715. if ( this._cubemapMaterial === null ) {
  44716. this._cubemapMaterial = _getCubemapMaterial();
  44717. }
  44718. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44719. } else {
  44720. if ( this._equirectMaterial === null ) {
  44721. this._equirectMaterial = _getEquirectMaterial();
  44722. }
  44723. }
  44724. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44725. const mesh = this._lodMeshes[ 0 ];
  44726. mesh.material = material;
  44727. const uniforms = material.uniforms;
  44728. uniforms[ 'envMap' ].value = texture;
  44729. const size = this._cubeSize;
  44730. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44731. renderer.setRenderTarget( cubeUVRenderTarget );
  44732. renderer.render( mesh, _flatCamera );
  44733. }
  44734. _applyPMREM( cubeUVRenderTarget ) {
  44735. const renderer = this._renderer;
  44736. const autoClear = renderer.autoClear;
  44737. renderer.autoClear = false;
  44738. const n = this._lodMeshes.length;
  44739. // Use GGX VNDF importance sampling
  44740. for ( let i = 1; i < n; i ++ ) {
  44741. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  44742. }
  44743. renderer.autoClear = autoClear;
  44744. }
  44745. /**
  44746. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  44747. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  44748. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  44749. * applies incremental roughness filtering to avoid over-blurring.
  44750. *
  44751. * @private
  44752. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44753. * @param {number} lodIn - Source LOD level to read from
  44754. * @param {number} lodOut - Target LOD level to write to
  44755. */
  44756. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  44757. const renderer = this._renderer;
  44758. const pingPongRenderTarget = this._pingPongRenderTarget;
  44759. const ggxMaterial = this._ggxMaterial;
  44760. const ggxMesh = this._lodMeshes[ lodOut ];
  44761. ggxMesh.material = ggxMaterial;
  44762. const ggxUniforms = ggxMaterial.uniforms;
  44763. // Calculate incremental roughness between LOD levels
  44764. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  44765. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  44766. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  44767. // Apply blur strength mapping for better quality across the roughness range
  44768. const blurStrength = 0.0 + targetRoughness * 1.25;
  44769. const adjustedRoughness = incrementalRoughness * blurStrength;
  44770. // Calculate viewport position based on output LOD level
  44771. const { _lodMax } = this;
  44772. const outputSize = this._sizeLods[ lodOut ];
  44773. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44774. const y = 4 * ( this._cubeSize - outputSize );
  44775. // Read from previous LOD with incremental roughness
  44776. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  44777. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  44778. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  44779. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44780. renderer.setRenderTarget( pingPongRenderTarget );
  44781. renderer.render( ggxMesh, _flatCamera );
  44782. // Copy from pingPong back to cubeUV (simple direct copy)
  44783. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  44784. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  44785. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  44786. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44787. renderer.setRenderTarget( cubeUVRenderTarget );
  44788. renderer.render( ggxMesh, _flatCamera );
  44789. }
  44790. /**
  44791. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44792. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44793. * the blur latitudinally (around the poles), and then longitudinally (towards
  44794. * the poles) to approximate the orthogonally-separable blur. It is least
  44795. * accurate at the poles, but still does a decent job.
  44796. *
  44797. * Used for initial scene blur in fromScene() method when sigma > 0.
  44798. *
  44799. * @private
  44800. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44801. * @param {number} lodIn
  44802. * @param {number} lodOut
  44803. * @param {number} sigma
  44804. * @param {Vector3} [poleAxis]
  44805. */
  44806. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44807. const pingPongRenderTarget = this._pingPongRenderTarget;
  44808. this._halfBlur(
  44809. cubeUVRenderTarget,
  44810. pingPongRenderTarget,
  44811. lodIn,
  44812. lodOut,
  44813. sigma,
  44814. 'latitudinal',
  44815. poleAxis );
  44816. this._halfBlur(
  44817. pingPongRenderTarget,
  44818. cubeUVRenderTarget,
  44819. lodOut,
  44820. lodOut,
  44821. sigma,
  44822. 'longitudinal',
  44823. poleAxis );
  44824. }
  44825. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44826. const renderer = this._renderer;
  44827. const blurMaterial = this._blurMaterial;
  44828. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44829. error(
  44830. 'blur direction must be either latitudinal or longitudinal!' );
  44831. }
  44832. // Number of standard deviations at which to cut off the discrete approximation.
  44833. const STANDARD_DEVIATIONS = 3;
  44834. const blurMesh = this._lodMeshes[ lodOut ];
  44835. blurMesh.material = blurMaterial;
  44836. const blurUniforms = blurMaterial.uniforms;
  44837. const pixels = this._sizeLods[ lodIn ] - 1;
  44838. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44839. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44840. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44841. if ( samples > MAX_SAMPLES ) {
  44842. warn( `sigmaRadians, ${
  44843. sigmaRadians}, is too large and will clip, as it requested ${
  44844. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44845. }
  44846. const weights = [];
  44847. let sum = 0;
  44848. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44849. const x = i / sigmaPixels;
  44850. const weight = Math.exp( - x * x / 2 );
  44851. weights.push( weight );
  44852. if ( i === 0 ) {
  44853. sum += weight;
  44854. } else if ( i < samples ) {
  44855. sum += 2 * weight;
  44856. }
  44857. }
  44858. for ( let i = 0; i < weights.length; i ++ ) {
  44859. weights[ i ] = weights[ i ] / sum;
  44860. }
  44861. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44862. blurUniforms[ 'samples' ].value = samples;
  44863. blurUniforms[ 'weights' ].value = weights;
  44864. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44865. if ( poleAxis ) {
  44866. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44867. }
  44868. const { _lodMax } = this;
  44869. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44870. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44871. const outputSize = this._sizeLods[ lodOut ];
  44872. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44873. const y = 4 * ( this._cubeSize - outputSize );
  44874. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44875. renderer.setRenderTarget( targetOut );
  44876. renderer.render( blurMesh, _flatCamera );
  44877. }
  44878. }
  44879. function _createPlanes( lodMax ) {
  44880. const sizeLods = [];
  44881. const sigmas = [];
  44882. const lodMeshes = [];
  44883. let lod = lodMax;
  44884. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44885. for ( let i = 0; i < totalLods; i ++ ) {
  44886. const sizeLod = Math.pow( 2, lod );
  44887. sizeLods.push( sizeLod );
  44888. let sigma = 1.0 / sizeLod;
  44889. if ( i > lodMax - LOD_MIN ) {
  44890. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44891. } else if ( i === 0 ) {
  44892. sigma = 0;
  44893. }
  44894. sigmas.push( sigma );
  44895. const texelSize = 1.0 / ( sizeLod - 2 );
  44896. const min = - texelSize;
  44897. const max = 1 + texelSize;
  44898. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44899. const cubeFaces = 6;
  44900. const vertices = 6;
  44901. const positionSize = 3;
  44902. const uvSize = 2;
  44903. const faceIndexSize = 1;
  44904. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44905. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44906. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44907. for ( let face = 0; face < cubeFaces; face ++ ) {
  44908. const x = ( face % 3 ) * 2 / 3 - 1;
  44909. const y = face > 2 ? 0 : -1;
  44910. const coordinates = [
  44911. x, y, 0,
  44912. x + 2 / 3, y, 0,
  44913. x + 2 / 3, y + 1, 0,
  44914. x, y, 0,
  44915. x + 2 / 3, y + 1, 0,
  44916. x, y + 1, 0
  44917. ];
  44918. position.set( coordinates, positionSize * vertices * face );
  44919. uv.set( uv1, uvSize * vertices * face );
  44920. const fill = [ face, face, face, face, face, face ];
  44921. faceIndex.set( fill, faceIndexSize * vertices * face );
  44922. }
  44923. const planes = new BufferGeometry();
  44924. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44925. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44926. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44927. lodMeshes.push( new Mesh( planes, null ) );
  44928. if ( lod > LOD_MIN ) {
  44929. lod --;
  44930. }
  44931. }
  44932. return { lodMeshes, sizeLods, sigmas };
  44933. }
  44934. function _createRenderTarget( width, height, params ) {
  44935. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44936. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  44937. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  44938. cubeUVRenderTarget.scissorTest = true;
  44939. return cubeUVRenderTarget;
  44940. }
  44941. function _setViewport( target, x, y, width, height ) {
  44942. target.viewport.set( x, y, width, height );
  44943. target.scissor.set( x, y, width, height );
  44944. }
  44945. function _getGGXShader( lodMax, width, height ) {
  44946. const shaderMaterial = new ShaderMaterial( {
  44947. name: 'PMREMGGXConvolution',
  44948. defines: {
  44949. 'GGX_SAMPLES': GGX_SAMPLES,
  44950. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  44951. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  44952. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  44953. },
  44954. uniforms: {
  44955. 'envMap': { value: null },
  44956. 'roughness': { value: 0.0 },
  44957. 'mipInt': { value: 0 }
  44958. },
  44959. vertexShader: _getCommonVertexShader(),
  44960. fragmentShader: /* glsl */`
  44961. precision highp float;
  44962. precision highp int;
  44963. varying vec3 vOutputDirection;
  44964. uniform sampler2D envMap;
  44965. uniform float roughness;
  44966. uniform float mipInt;
  44967. #define ENVMAP_TYPE_CUBE_UV
  44968. #include <cube_uv_reflection_fragment>
  44969. #define PI 3.14159265359
  44970. // Van der Corput radical inverse
  44971. float radicalInverse_VdC(uint bits) {
  44972. bits = (bits << 16u) | (bits >> 16u);
  44973. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  44974. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  44975. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  44976. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  44977. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  44978. }
  44979. // Hammersley sequence
  44980. vec2 hammersley(uint i, uint N) {
  44981. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  44982. }
  44983. // GGX VNDF importance sampling (Eric Heitz 2018)
  44984. // "Sampling the GGX Distribution of Visible Normals"
  44985. // https://jcgt.org/published/0007/04/01/
  44986. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  44987. float alpha = roughness * roughness;
  44988. // Section 3.2: Transform view direction to hemisphere configuration
  44989. vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
  44990. // Section 4.1: Orthonormal basis
  44991. float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
  44992. vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
  44993. vec3 T2 = cross(Vh, T1);
  44994. // Section 4.2: Parameterization of projected area
  44995. float r = sqrt(Xi.x);
  44996. float phi = 2.0 * PI * Xi.y;
  44997. float t1 = r * cos(phi);
  44998. float t2 = r * sin(phi);
  44999. float s = 0.5 * (1.0 + Vh.z);
  45000. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  45001. // Section 4.3: Reprojection onto hemisphere
  45002. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
  45003. // Section 3.4: Transform back to ellipsoid configuration
  45004. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  45005. }
  45006. void main() {
  45007. vec3 N = normalize(vOutputDirection);
  45008. vec3 V = N; // Assume view direction equals normal for pre-filtering
  45009. vec3 prefilteredColor = vec3(0.0);
  45010. float totalWeight = 0.0;
  45011. // For very low roughness, just sample the environment directly
  45012. if (roughness < 0.001) {
  45013. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  45014. return;
  45015. }
  45016. // Tangent space basis for VNDF sampling
  45017. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  45018. vec3 tangent = normalize(cross(up, N));
  45019. vec3 bitangent = cross(N, tangent);
  45020. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  45021. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  45022. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  45023. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  45024. // Transform H back to world space
  45025. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  45026. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  45027. float NdotL = max(dot(N, L), 0.0);
  45028. if(NdotL > 0.0) {
  45029. // Sample environment at fixed mip level
  45030. // VNDF importance sampling handles the distribution filtering
  45031. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  45032. // Weight by NdotL for the split-sum approximation
  45033. // VNDF PDF naturally accounts for the visible microfacet distribution
  45034. prefilteredColor += sampleColor * NdotL;
  45035. totalWeight += NdotL;
  45036. }
  45037. }
  45038. if (totalWeight > 0.0) {
  45039. prefilteredColor = prefilteredColor / totalWeight;
  45040. }
  45041. gl_FragColor = vec4(prefilteredColor, 1.0);
  45042. }
  45043. `,
  45044. blending: NoBlending,
  45045. depthTest: false,
  45046. depthWrite: false
  45047. } );
  45048. return shaderMaterial;
  45049. }
  45050. function _getBlurShader( lodMax, width, height ) {
  45051. const weights = new Float32Array( MAX_SAMPLES );
  45052. const poleAxis = new Vector3( 0, 1, 0 );
  45053. const shaderMaterial = new ShaderMaterial( {
  45054. name: 'SphericalGaussianBlur',
  45055. defines: {
  45056. 'n': MAX_SAMPLES,
  45057. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45058. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45059. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45060. },
  45061. uniforms: {
  45062. 'envMap': { value: null },
  45063. 'samples': { value: 1 },
  45064. 'weights': { value: weights },
  45065. 'latitudinal': { value: false },
  45066. 'dTheta': { value: 0 },
  45067. 'mipInt': { value: 0 },
  45068. 'poleAxis': { value: poleAxis }
  45069. },
  45070. vertexShader: _getCommonVertexShader(),
  45071. fragmentShader: /* glsl */`
  45072. precision mediump float;
  45073. precision mediump int;
  45074. varying vec3 vOutputDirection;
  45075. uniform sampler2D envMap;
  45076. uniform int samples;
  45077. uniform float weights[ n ];
  45078. uniform bool latitudinal;
  45079. uniform float dTheta;
  45080. uniform float mipInt;
  45081. uniform vec3 poleAxis;
  45082. #define ENVMAP_TYPE_CUBE_UV
  45083. #include <cube_uv_reflection_fragment>
  45084. vec3 getSample( float theta, vec3 axis ) {
  45085. float cosTheta = cos( theta );
  45086. // Rodrigues' axis-angle rotation
  45087. vec3 sampleDirection = vOutputDirection * cosTheta
  45088. + cross( axis, vOutputDirection ) * sin( theta )
  45089. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  45090. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  45091. }
  45092. void main() {
  45093. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  45094. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  45095. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  45096. }
  45097. axis = normalize( axis );
  45098. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  45099. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  45100. for ( int i = 1; i < n; i++ ) {
  45101. if ( i >= samples ) {
  45102. break;
  45103. }
  45104. float theta = dTheta * float( i );
  45105. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  45106. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  45107. }
  45108. }
  45109. `,
  45110. blending: NoBlending,
  45111. depthTest: false,
  45112. depthWrite: false
  45113. } );
  45114. return shaderMaterial;
  45115. }
  45116. function _getEquirectMaterial() {
  45117. return new ShaderMaterial( {
  45118. name: 'EquirectangularToCubeUV',
  45119. uniforms: {
  45120. 'envMap': { value: null }
  45121. },
  45122. vertexShader: _getCommonVertexShader(),
  45123. fragmentShader: /* glsl */`
  45124. precision mediump float;
  45125. precision mediump int;
  45126. varying vec3 vOutputDirection;
  45127. uniform sampler2D envMap;
  45128. #include <common>
  45129. void main() {
  45130. vec3 outputDirection = normalize( vOutputDirection );
  45131. vec2 uv = equirectUv( outputDirection );
  45132. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  45133. }
  45134. `,
  45135. blending: NoBlending,
  45136. depthTest: false,
  45137. depthWrite: false
  45138. } );
  45139. }
  45140. function _getCubemapMaterial() {
  45141. return new ShaderMaterial( {
  45142. name: 'CubemapToCubeUV',
  45143. uniforms: {
  45144. 'envMap': { value: null },
  45145. 'flipEnvMap': { value: -1 }
  45146. },
  45147. vertexShader: _getCommonVertexShader(),
  45148. fragmentShader: /* glsl */`
  45149. precision mediump float;
  45150. precision mediump int;
  45151. uniform float flipEnvMap;
  45152. varying vec3 vOutputDirection;
  45153. uniform samplerCube envMap;
  45154. void main() {
  45155. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  45156. }
  45157. `,
  45158. blending: NoBlending,
  45159. depthTest: false,
  45160. depthWrite: false
  45161. } );
  45162. }
  45163. function _getCommonVertexShader() {
  45164. return /* glsl */`
  45165. precision mediump float;
  45166. precision mediump int;
  45167. attribute float faceIndex;
  45168. varying vec3 vOutputDirection;
  45169. // RH coordinate system; PMREM face-indexing convention
  45170. vec3 getDirection( vec2 uv, float face ) {
  45171. uv = 2.0 * uv - 1.0;
  45172. vec3 direction = vec3( uv, 1.0 );
  45173. if ( face == 0.0 ) {
  45174. direction = direction.zyx; // ( 1, v, u ) pos x
  45175. } else if ( face == 1.0 ) {
  45176. direction = direction.xzy;
  45177. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  45178. } else if ( face == 2.0 ) {
  45179. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  45180. } else if ( face == 3.0 ) {
  45181. direction = direction.zyx;
  45182. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  45183. } else if ( face == 4.0 ) {
  45184. direction = direction.xzy;
  45185. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  45186. } else if ( face == 5.0 ) {
  45187. direction.z *= -1.0; // ( u, v, -1 ) neg z
  45188. }
  45189. return direction;
  45190. }
  45191. void main() {
  45192. vOutputDirection = getDirection( uv, faceIndex );
  45193. gl_Position = vec4( position, 1.0 );
  45194. }
  45195. `;
  45196. }
  45197. function WebGLCubeUVMaps( renderer ) {
  45198. let cubeUVmaps = new WeakMap();
  45199. let pmremGenerator = null;
  45200. function get( texture ) {
  45201. if ( texture && texture.isTexture ) {
  45202. const mapping = texture.mapping;
  45203. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  45204. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45205. // equirect/cube map to cubeUV conversion
  45206. if ( isEquirectMap || isCubeMap ) {
  45207. let renderTarget = cubeUVmaps.get( texture );
  45208. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  45209. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  45210. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45211. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  45212. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45213. cubeUVmaps.set( texture, renderTarget );
  45214. return renderTarget.texture;
  45215. } else {
  45216. if ( renderTarget !== undefined ) {
  45217. return renderTarget.texture;
  45218. } else {
  45219. const image = texture.image;
  45220. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  45221. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45222. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  45223. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45224. cubeUVmaps.set( texture, renderTarget );
  45225. texture.addEventListener( 'dispose', onTextureDispose );
  45226. return renderTarget.texture;
  45227. } else {
  45228. // image not yet ready. try the conversion next frame
  45229. return null;
  45230. }
  45231. }
  45232. }
  45233. }
  45234. }
  45235. return texture;
  45236. }
  45237. function isCubeTextureComplete( image ) {
  45238. let count = 0;
  45239. const length = 6;
  45240. for ( let i = 0; i < length; i ++ ) {
  45241. if ( image[ i ] !== undefined ) count ++;
  45242. }
  45243. return count === length;
  45244. }
  45245. function onTextureDispose( event ) {
  45246. const texture = event.target;
  45247. texture.removeEventListener( 'dispose', onTextureDispose );
  45248. const cubemapUV = cubeUVmaps.get( texture );
  45249. if ( cubemapUV !== undefined ) {
  45250. cubeUVmaps.delete( texture );
  45251. cubemapUV.dispose();
  45252. }
  45253. }
  45254. function dispose() {
  45255. cubeUVmaps = new WeakMap();
  45256. if ( pmremGenerator !== null ) {
  45257. pmremGenerator.dispose();
  45258. pmremGenerator = null;
  45259. }
  45260. }
  45261. return {
  45262. get: get,
  45263. dispose: dispose
  45264. };
  45265. }
  45266. function WebGLExtensions( gl ) {
  45267. const extensions = {};
  45268. function getExtension( name ) {
  45269. if ( extensions[ name ] !== undefined ) {
  45270. return extensions[ name ];
  45271. }
  45272. const extension = gl.getExtension( name );
  45273. extensions[ name ] = extension;
  45274. return extension;
  45275. }
  45276. return {
  45277. has: function ( name ) {
  45278. return getExtension( name ) !== null;
  45279. },
  45280. init: function () {
  45281. getExtension( 'EXT_color_buffer_float' );
  45282. getExtension( 'WEBGL_clip_cull_distance' );
  45283. getExtension( 'OES_texture_float_linear' );
  45284. getExtension( 'EXT_color_buffer_half_float' );
  45285. getExtension( 'WEBGL_multisampled_render_to_texture' );
  45286. getExtension( 'WEBGL_render_shared_exponent' );
  45287. },
  45288. get: function ( name ) {
  45289. const extension = getExtension( name );
  45290. if ( extension === null ) {
  45291. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  45292. }
  45293. return extension;
  45294. }
  45295. };
  45296. }
  45297. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  45298. const geometries = {};
  45299. const wireframeAttributes = new WeakMap();
  45300. function onGeometryDispose( event ) {
  45301. const geometry = event.target;
  45302. if ( geometry.index !== null ) {
  45303. attributes.remove( geometry.index );
  45304. }
  45305. for ( const name in geometry.attributes ) {
  45306. attributes.remove( geometry.attributes[ name ] );
  45307. }
  45308. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45309. delete geometries[ geometry.id ];
  45310. const attribute = wireframeAttributes.get( geometry );
  45311. if ( attribute ) {
  45312. attributes.remove( attribute );
  45313. wireframeAttributes.delete( geometry );
  45314. }
  45315. bindingStates.releaseStatesOfGeometry( geometry );
  45316. if ( geometry.isInstancedBufferGeometry === true ) {
  45317. delete geometry._maxInstanceCount;
  45318. }
  45319. //
  45320. info.memory.geometries --;
  45321. }
  45322. function get( object, geometry ) {
  45323. if ( geometries[ geometry.id ] === true ) return geometry;
  45324. geometry.addEventListener( 'dispose', onGeometryDispose );
  45325. geometries[ geometry.id ] = true;
  45326. info.memory.geometries ++;
  45327. return geometry;
  45328. }
  45329. function update( geometry ) {
  45330. const geometryAttributes = geometry.attributes;
  45331. // Updating index buffer in VAO now. See WebGLBindingStates.
  45332. for ( const name in geometryAttributes ) {
  45333. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45334. }
  45335. }
  45336. function updateWireframeAttribute( geometry ) {
  45337. const indices = [];
  45338. const geometryIndex = geometry.index;
  45339. const geometryPosition = geometry.attributes.position;
  45340. let version = 0;
  45341. if ( geometryIndex !== null ) {
  45342. const array = geometryIndex.array;
  45343. version = geometryIndex.version;
  45344. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45345. const a = array[ i + 0 ];
  45346. const b = array[ i + 1 ];
  45347. const c = array[ i + 2 ];
  45348. indices.push( a, b, b, c, c, a );
  45349. }
  45350. } else if ( geometryPosition !== undefined ) {
  45351. const array = geometryPosition.array;
  45352. version = geometryPosition.version;
  45353. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45354. const a = i + 0;
  45355. const b = i + 1;
  45356. const c = i + 2;
  45357. indices.push( a, b, b, c, c, a );
  45358. }
  45359. } else {
  45360. return;
  45361. }
  45362. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45363. attribute.version = version;
  45364. // Updating index buffer in VAO now. See WebGLBindingStates
  45365. //
  45366. const previousAttribute = wireframeAttributes.get( geometry );
  45367. if ( previousAttribute ) attributes.remove( previousAttribute );
  45368. //
  45369. wireframeAttributes.set( geometry, attribute );
  45370. }
  45371. function getWireframeAttribute( geometry ) {
  45372. const currentAttribute = wireframeAttributes.get( geometry );
  45373. if ( currentAttribute ) {
  45374. const geometryIndex = geometry.index;
  45375. if ( geometryIndex !== null ) {
  45376. // if the attribute is obsolete, create a new one
  45377. if ( currentAttribute.version < geometryIndex.version ) {
  45378. updateWireframeAttribute( geometry );
  45379. }
  45380. }
  45381. } else {
  45382. updateWireframeAttribute( geometry );
  45383. }
  45384. return wireframeAttributes.get( geometry );
  45385. }
  45386. return {
  45387. get: get,
  45388. update: update,
  45389. getWireframeAttribute: getWireframeAttribute
  45390. };
  45391. }
  45392. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45393. let mode;
  45394. function setMode( value ) {
  45395. mode = value;
  45396. }
  45397. let type, bytesPerElement;
  45398. function setIndex( value ) {
  45399. type = value.type;
  45400. bytesPerElement = value.bytesPerElement;
  45401. }
  45402. function render( start, count ) {
  45403. gl.drawElements( mode, count, type, start * bytesPerElement );
  45404. info.update( count, mode, 1 );
  45405. }
  45406. function renderInstances( start, count, primcount ) {
  45407. if ( primcount === 0 ) return;
  45408. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45409. info.update( count, mode, primcount );
  45410. }
  45411. function renderMultiDraw( starts, counts, drawCount ) {
  45412. if ( drawCount === 0 ) return;
  45413. const extension = extensions.get( 'WEBGL_multi_draw' );
  45414. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45415. let elementCount = 0;
  45416. for ( let i = 0; i < drawCount; i ++ ) {
  45417. elementCount += counts[ i ];
  45418. }
  45419. info.update( elementCount, mode, 1 );
  45420. }
  45421. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45422. if ( drawCount === 0 ) return;
  45423. const extension = extensions.get( 'WEBGL_multi_draw' );
  45424. if ( extension === null ) {
  45425. for ( let i = 0; i < starts.length; i ++ ) {
  45426. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45427. }
  45428. } else {
  45429. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45430. let elementCount = 0;
  45431. for ( let i = 0; i < drawCount; i ++ ) {
  45432. elementCount += counts[ i ] * primcount[ i ];
  45433. }
  45434. info.update( elementCount, mode, 1 );
  45435. }
  45436. }
  45437. //
  45438. this.setMode = setMode;
  45439. this.setIndex = setIndex;
  45440. this.render = render;
  45441. this.renderInstances = renderInstances;
  45442. this.renderMultiDraw = renderMultiDraw;
  45443. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45444. }
  45445. function WebGLInfo( gl ) {
  45446. const memory = {
  45447. geometries: 0,
  45448. textures: 0
  45449. };
  45450. const render = {
  45451. frame: 0,
  45452. calls: 0,
  45453. triangles: 0,
  45454. points: 0,
  45455. lines: 0
  45456. };
  45457. function update( count, mode, instanceCount ) {
  45458. render.calls ++;
  45459. switch ( mode ) {
  45460. case gl.TRIANGLES:
  45461. render.triangles += instanceCount * ( count / 3 );
  45462. break;
  45463. case gl.LINES:
  45464. render.lines += instanceCount * ( count / 2 );
  45465. break;
  45466. case gl.LINE_STRIP:
  45467. render.lines += instanceCount * ( count - 1 );
  45468. break;
  45469. case gl.LINE_LOOP:
  45470. render.lines += instanceCount * count;
  45471. break;
  45472. case gl.POINTS:
  45473. render.points += instanceCount * count;
  45474. break;
  45475. default:
  45476. error( 'WebGLInfo: Unknown draw mode:', mode );
  45477. break;
  45478. }
  45479. }
  45480. function reset() {
  45481. render.calls = 0;
  45482. render.triangles = 0;
  45483. render.points = 0;
  45484. render.lines = 0;
  45485. }
  45486. return {
  45487. memory: memory,
  45488. render: render,
  45489. programs: null,
  45490. autoReset: true,
  45491. reset: reset,
  45492. update: update
  45493. };
  45494. }
  45495. function WebGLMorphtargets( gl, capabilities, textures ) {
  45496. const morphTextures = new WeakMap();
  45497. const morph = new Vector4();
  45498. function update( object, geometry, program ) {
  45499. const objectInfluences = object.morphTargetInfluences;
  45500. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45501. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45502. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45503. let entry = morphTextures.get( geometry );
  45504. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45505. if ( entry !== undefined ) entry.texture.dispose();
  45506. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45507. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45508. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45509. const morphTargets = geometry.morphAttributes.position || [];
  45510. const morphNormals = geometry.morphAttributes.normal || [];
  45511. const morphColors = geometry.morphAttributes.color || [];
  45512. let vertexDataCount = 0;
  45513. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45514. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45515. if ( hasMorphColors === true ) vertexDataCount = 3;
  45516. let width = geometry.attributes.position.count * vertexDataCount;
  45517. let height = 1;
  45518. if ( width > capabilities.maxTextureSize ) {
  45519. height = Math.ceil( width / capabilities.maxTextureSize );
  45520. width = capabilities.maxTextureSize;
  45521. }
  45522. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45523. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45524. texture.type = FloatType;
  45525. texture.needsUpdate = true;
  45526. // fill buffer
  45527. const vertexDataStride = vertexDataCount * 4;
  45528. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45529. const morphTarget = morphTargets[ i ];
  45530. const morphNormal = morphNormals[ i ];
  45531. const morphColor = morphColors[ i ];
  45532. const offset = width * height * 4 * i;
  45533. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45534. const stride = j * vertexDataStride;
  45535. if ( hasMorphPosition === true ) {
  45536. morph.fromBufferAttribute( morphTarget, j );
  45537. buffer[ offset + stride + 0 ] = morph.x;
  45538. buffer[ offset + stride + 1 ] = morph.y;
  45539. buffer[ offset + stride + 2 ] = morph.z;
  45540. buffer[ offset + stride + 3 ] = 0;
  45541. }
  45542. if ( hasMorphNormals === true ) {
  45543. morph.fromBufferAttribute( morphNormal, j );
  45544. buffer[ offset + stride + 4 ] = morph.x;
  45545. buffer[ offset + stride + 5 ] = morph.y;
  45546. buffer[ offset + stride + 6 ] = morph.z;
  45547. buffer[ offset + stride + 7 ] = 0;
  45548. }
  45549. if ( hasMorphColors === true ) {
  45550. morph.fromBufferAttribute( morphColor, j );
  45551. buffer[ offset + stride + 8 ] = morph.x;
  45552. buffer[ offset + stride + 9 ] = morph.y;
  45553. buffer[ offset + stride + 10 ] = morph.z;
  45554. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45555. }
  45556. }
  45557. }
  45558. entry = {
  45559. count: morphTargetsCount,
  45560. texture: texture,
  45561. size: new Vector2( width, height )
  45562. };
  45563. morphTextures.set( geometry, entry );
  45564. function disposeTexture() {
  45565. texture.dispose();
  45566. morphTextures.delete( geometry );
  45567. geometry.removeEventListener( 'dispose', disposeTexture );
  45568. }
  45569. geometry.addEventListener( 'dispose', disposeTexture );
  45570. }
  45571. //
  45572. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45573. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45574. } else {
  45575. let morphInfluencesSum = 0;
  45576. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45577. morphInfluencesSum += objectInfluences[ i ];
  45578. }
  45579. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45580. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45581. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45582. }
  45583. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45584. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45585. }
  45586. return {
  45587. update: update
  45588. };
  45589. }
  45590. function WebGLObjects( gl, geometries, attributes, info ) {
  45591. let updateMap = new WeakMap();
  45592. function update( object ) {
  45593. const frame = info.render.frame;
  45594. const geometry = object.geometry;
  45595. const buffergeometry = geometries.get( object, geometry );
  45596. // Update once per frame
  45597. if ( updateMap.get( buffergeometry ) !== frame ) {
  45598. geometries.update( buffergeometry );
  45599. updateMap.set( buffergeometry, frame );
  45600. }
  45601. if ( object.isInstancedMesh ) {
  45602. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45603. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45604. }
  45605. if ( updateMap.get( object ) !== frame ) {
  45606. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45607. if ( object.instanceColor !== null ) {
  45608. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45609. }
  45610. updateMap.set( object, frame );
  45611. }
  45612. }
  45613. if ( object.isSkinnedMesh ) {
  45614. const skeleton = object.skeleton;
  45615. if ( updateMap.get( skeleton ) !== frame ) {
  45616. skeleton.update();
  45617. updateMap.set( skeleton, frame );
  45618. }
  45619. }
  45620. return buffergeometry;
  45621. }
  45622. function dispose() {
  45623. updateMap = new WeakMap();
  45624. }
  45625. function onInstancedMeshDispose( event ) {
  45626. const instancedMesh = event.target;
  45627. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45628. attributes.remove( instancedMesh.instanceMatrix );
  45629. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45630. }
  45631. return {
  45632. update: update,
  45633. dispose: dispose
  45634. };
  45635. }
  45636. const toneMappingMap = {
  45637. [ LinearToneMapping ]: 'LINEAR_TONE_MAPPING',
  45638. [ ReinhardToneMapping ]: 'REINHARD_TONE_MAPPING',
  45639. [ CineonToneMapping ]: 'CINEON_TONE_MAPPING',
  45640. [ ACESFilmicToneMapping ]: 'ACES_FILMIC_TONE_MAPPING',
  45641. [ AgXToneMapping ]: 'AGX_TONE_MAPPING',
  45642. [ NeutralToneMapping ]: 'NEUTRAL_TONE_MAPPING',
  45643. [ CustomToneMapping ]: 'CUSTOM_TONE_MAPPING'
  45644. };
  45645. function WebGLOutput( type, width, height, depth, stencil ) {
  45646. // render targets for scene and post-processing
  45647. const targetA = new WebGLRenderTarget( width, height, {
  45648. type: type,
  45649. depthBuffer: depth,
  45650. stencilBuffer: stencil
  45651. } );
  45652. const targetB = new WebGLRenderTarget( width, height, {
  45653. type: HalfFloatType,
  45654. depthBuffer: false,
  45655. stencilBuffer: false
  45656. } );
  45657. // create fullscreen triangle geometry
  45658. const geometry = new BufferGeometry();
  45659. geometry.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  45660. geometry.setAttribute( 'uv', new Float32BufferAttribute( [ 0, 2, 0, 0, 2, 0 ], 2 ) );
  45661. // create output material with tone mapping support
  45662. const material = new RawShaderMaterial( {
  45663. uniforms: {
  45664. tDiffuse: { value: null }
  45665. },
  45666. vertexShader: /* glsl */`
  45667. precision highp float;
  45668. uniform mat4 modelViewMatrix;
  45669. uniform mat4 projectionMatrix;
  45670. attribute vec3 position;
  45671. attribute vec2 uv;
  45672. varying vec2 vUv;
  45673. void main() {
  45674. vUv = uv;
  45675. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  45676. }`,
  45677. fragmentShader: /* glsl */`
  45678. precision highp float;
  45679. uniform sampler2D tDiffuse;
  45680. varying vec2 vUv;
  45681. #include <tonemapping_pars_fragment>
  45682. #include <colorspace_pars_fragment>
  45683. void main() {
  45684. gl_FragColor = texture2D( tDiffuse, vUv );
  45685. #ifdef LINEAR_TONE_MAPPING
  45686. gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb );
  45687. #elif defined( REINHARD_TONE_MAPPING )
  45688. gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb );
  45689. #elif defined( CINEON_TONE_MAPPING )
  45690. gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb );
  45691. #elif defined( ACES_FILMIC_TONE_MAPPING )
  45692. gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb );
  45693. #elif defined( AGX_TONE_MAPPING )
  45694. gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb );
  45695. #elif defined( NEUTRAL_TONE_MAPPING )
  45696. gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb );
  45697. #elif defined( CUSTOM_TONE_MAPPING )
  45698. gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb );
  45699. #endif
  45700. #ifdef SRGB_TRANSFER
  45701. gl_FragColor = sRGBTransferOETF( gl_FragColor );
  45702. #endif
  45703. }`,
  45704. depthTest: false,
  45705. depthWrite: false
  45706. } );
  45707. const mesh = new Mesh( geometry, material );
  45708. const camera = new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  45709. let _outputColorSpace = null;
  45710. let _outputToneMapping = null;
  45711. let _isCompositing = false;
  45712. let _savedToneMapping;
  45713. let _savedRenderTarget = null;
  45714. let _effects = [];
  45715. let _hasRenderPass = false;
  45716. this.setSize = function ( width, height ) {
  45717. targetA.setSize( width, height );
  45718. targetB.setSize( width, height );
  45719. for ( let i = 0; i < _effects.length; i ++ ) {
  45720. const effect = _effects[ i ];
  45721. if ( effect.setSize ) effect.setSize( width, height );
  45722. }
  45723. };
  45724. this.setEffects = function ( effects ) {
  45725. _effects = effects;
  45726. _hasRenderPass = _effects.length > 0 && _effects[ 0 ].isRenderPass === true;
  45727. const width = targetA.width;
  45728. const height = targetA.height;
  45729. for ( let i = 0; i < _effects.length; i ++ ) {
  45730. const effect = _effects[ i ];
  45731. if ( effect.setSize ) effect.setSize( width, height );
  45732. }
  45733. };
  45734. this.begin = function ( renderer, renderTarget ) {
  45735. // Don't begin during compositing phase (post-processing effects call render())
  45736. if ( _isCompositing ) return false;
  45737. if ( renderer.toneMapping === NoToneMapping && _effects.length === 0 ) return false;
  45738. _savedRenderTarget = renderTarget;
  45739. // resize internal buffers to match render target (e.g. XR resolution)
  45740. if ( renderTarget !== null ) {
  45741. const width = renderTarget.width;
  45742. const height = renderTarget.height;
  45743. if ( targetA.width !== width || targetA.height !== height ) {
  45744. this.setSize( width, height );
  45745. }
  45746. }
  45747. // if first effect is a RenderPass, it will set its own render target
  45748. if ( _hasRenderPass === false ) {
  45749. renderer.setRenderTarget( targetA );
  45750. }
  45751. // disable tone mapping during render - it will be applied in end()
  45752. _savedToneMapping = renderer.toneMapping;
  45753. renderer.toneMapping = NoToneMapping;
  45754. return true;
  45755. };
  45756. this.hasRenderPass = function () {
  45757. return _hasRenderPass;
  45758. };
  45759. this.end = function ( renderer, deltaTime ) {
  45760. // restore tone mapping
  45761. renderer.toneMapping = _savedToneMapping;
  45762. _isCompositing = true;
  45763. // run post-processing effects
  45764. let readBuffer = targetA;
  45765. let writeBuffer = targetB;
  45766. for ( let i = 0; i < _effects.length; i ++ ) {
  45767. const effect = _effects[ i ];
  45768. if ( effect.enabled === false ) continue;
  45769. effect.render( renderer, writeBuffer, readBuffer, deltaTime );
  45770. if ( effect.needsSwap !== false ) {
  45771. const temp = readBuffer;
  45772. readBuffer = writeBuffer;
  45773. writeBuffer = temp;
  45774. }
  45775. }
  45776. // update output material defines if settings changed
  45777. if ( _outputColorSpace !== renderer.outputColorSpace || _outputToneMapping !== renderer.toneMapping ) {
  45778. _outputColorSpace = renderer.outputColorSpace;
  45779. _outputToneMapping = renderer.toneMapping;
  45780. material.defines = {};
  45781. if ( ColorManagement.getTransfer( _outputColorSpace ) === SRGBTransfer ) material.defines.SRGB_TRANSFER = '';
  45782. const toneMapping = toneMappingMap[ _outputToneMapping ];
  45783. if ( toneMapping ) material.defines[ toneMapping ] = '';
  45784. material.needsUpdate = true;
  45785. }
  45786. // final output to canvas (or XR render target)
  45787. material.uniforms.tDiffuse.value = readBuffer.texture;
  45788. renderer.setRenderTarget( _savedRenderTarget );
  45789. renderer.render( mesh, camera );
  45790. _savedRenderTarget = null;
  45791. _isCompositing = false;
  45792. };
  45793. this.isCompositing = function () {
  45794. return _isCompositing;
  45795. };
  45796. this.dispose = function () {
  45797. targetA.dispose();
  45798. targetB.dispose();
  45799. geometry.dispose();
  45800. material.dispose();
  45801. };
  45802. }
  45803. /**
  45804. * Uniforms of a program.
  45805. * Those form a tree structure with a special top-level container for the root,
  45806. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45807. *
  45808. *
  45809. * Properties of inner nodes including the top-level container:
  45810. *
  45811. * .seq - array of nested uniforms
  45812. * .map - nested uniforms by name
  45813. *
  45814. *
  45815. * Methods of all nodes except the top-level container:
  45816. *
  45817. * .setValue( gl, value, [textures] )
  45818. *
  45819. * uploads a uniform value(s)
  45820. * the 'textures' parameter is needed for sampler uniforms
  45821. *
  45822. *
  45823. * Static methods of the top-level container (textures factorizations):
  45824. *
  45825. * .upload( gl, seq, values, textures )
  45826. *
  45827. * sets uniforms in 'seq' to 'values[id].value'
  45828. *
  45829. * .seqWithValue( seq, values ) : filteredSeq
  45830. *
  45831. * filters 'seq' entries with corresponding entry in values
  45832. *
  45833. *
  45834. * Methods of the top-level container (textures factorizations):
  45835. *
  45836. * .setValue( gl, name, value, textures )
  45837. *
  45838. * sets uniform with name 'name' to 'value'
  45839. *
  45840. * .setOptional( gl, obj, prop )
  45841. *
  45842. * like .set for an optional property of the object
  45843. *
  45844. */
  45845. const emptyTexture = /*@__PURE__*/ new Texture();
  45846. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45847. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45848. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45849. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45850. // --- Utilities ---
  45851. // Array Caches (provide typed arrays for temporary by size)
  45852. const arrayCacheF32 = [];
  45853. const arrayCacheI32 = [];
  45854. // Float32Array caches used for uploading Matrix uniforms
  45855. const mat4array = new Float32Array( 16 );
  45856. const mat3array = new Float32Array( 9 );
  45857. const mat2array = new Float32Array( 4 );
  45858. // Flattening for arrays of vectors and matrices
  45859. function flatten( array, nBlocks, blockSize ) {
  45860. const firstElem = array[ 0 ];
  45861. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45862. // unoptimized: ! isNaN( firstElem )
  45863. // see http://jacksondunstan.com/articles/983
  45864. const n = nBlocks * blockSize;
  45865. let r = arrayCacheF32[ n ];
  45866. if ( r === undefined ) {
  45867. r = new Float32Array( n );
  45868. arrayCacheF32[ n ] = r;
  45869. }
  45870. if ( nBlocks !== 0 ) {
  45871. firstElem.toArray( r, 0 );
  45872. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45873. offset += blockSize;
  45874. array[ i ].toArray( r, offset );
  45875. }
  45876. }
  45877. return r;
  45878. }
  45879. function arraysEqual( a, b ) {
  45880. if ( a.length !== b.length ) return false;
  45881. for ( let i = 0, l = a.length; i < l; i ++ ) {
  45882. if ( a[ i ] !== b[ i ] ) return false;
  45883. }
  45884. return true;
  45885. }
  45886. function copyArray( a, b ) {
  45887. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45888. a[ i ] = b[ i ];
  45889. }
  45890. }
  45891. // Texture unit allocation
  45892. function allocTexUnits( textures, n ) {
  45893. let r = arrayCacheI32[ n ];
  45894. if ( r === undefined ) {
  45895. r = new Int32Array( n );
  45896. arrayCacheI32[ n ] = r;
  45897. }
  45898. for ( let i = 0; i !== n; ++ i ) {
  45899. r[ i ] = textures.allocateTextureUnit();
  45900. }
  45901. return r;
  45902. }
  45903. // --- Setters ---
  45904. // Note: Defining these methods externally, because they come in a bunch
  45905. // and this way their names minify.
  45906. // Single scalar
  45907. function setValueV1f( gl, v ) {
  45908. const cache = this.cache;
  45909. if ( cache[ 0 ] === v ) return;
  45910. gl.uniform1f( this.addr, v );
  45911. cache[ 0 ] = v;
  45912. }
  45913. // Single float vector (from flat array or THREE.VectorN)
  45914. function setValueV2f( gl, v ) {
  45915. const cache = this.cache;
  45916. if ( v.x !== undefined ) {
  45917. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45918. gl.uniform2f( this.addr, v.x, v.y );
  45919. cache[ 0 ] = v.x;
  45920. cache[ 1 ] = v.y;
  45921. }
  45922. } else {
  45923. if ( arraysEqual( cache, v ) ) return;
  45924. gl.uniform2fv( this.addr, v );
  45925. copyArray( cache, v );
  45926. }
  45927. }
  45928. function setValueV3f( gl, v ) {
  45929. const cache = this.cache;
  45930. if ( v.x !== undefined ) {
  45931. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45932. gl.uniform3f( this.addr, v.x, v.y, v.z );
  45933. cache[ 0 ] = v.x;
  45934. cache[ 1 ] = v.y;
  45935. cache[ 2 ] = v.z;
  45936. }
  45937. } else if ( v.r !== undefined ) {
  45938. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  45939. gl.uniform3f( this.addr, v.r, v.g, v.b );
  45940. cache[ 0 ] = v.r;
  45941. cache[ 1 ] = v.g;
  45942. cache[ 2 ] = v.b;
  45943. }
  45944. } else {
  45945. if ( arraysEqual( cache, v ) ) return;
  45946. gl.uniform3fv( this.addr, v );
  45947. copyArray( cache, v );
  45948. }
  45949. }
  45950. function setValueV4f( gl, v ) {
  45951. const cache = this.cache;
  45952. if ( v.x !== undefined ) {
  45953. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45954. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  45955. cache[ 0 ] = v.x;
  45956. cache[ 1 ] = v.y;
  45957. cache[ 2 ] = v.z;
  45958. cache[ 3 ] = v.w;
  45959. }
  45960. } else {
  45961. if ( arraysEqual( cache, v ) ) return;
  45962. gl.uniform4fv( this.addr, v );
  45963. copyArray( cache, v );
  45964. }
  45965. }
  45966. // Single matrix (from flat array or THREE.MatrixN)
  45967. function setValueM2( gl, v ) {
  45968. const cache = this.cache;
  45969. const elements = v.elements;
  45970. if ( elements === undefined ) {
  45971. if ( arraysEqual( cache, v ) ) return;
  45972. gl.uniformMatrix2fv( this.addr, false, v );
  45973. copyArray( cache, v );
  45974. } else {
  45975. if ( arraysEqual( cache, elements ) ) return;
  45976. mat2array.set( elements );
  45977. gl.uniformMatrix2fv( this.addr, false, mat2array );
  45978. copyArray( cache, elements );
  45979. }
  45980. }
  45981. function setValueM3( gl, v ) {
  45982. const cache = this.cache;
  45983. const elements = v.elements;
  45984. if ( elements === undefined ) {
  45985. if ( arraysEqual( cache, v ) ) return;
  45986. gl.uniformMatrix3fv( this.addr, false, v );
  45987. copyArray( cache, v );
  45988. } else {
  45989. if ( arraysEqual( cache, elements ) ) return;
  45990. mat3array.set( elements );
  45991. gl.uniformMatrix3fv( this.addr, false, mat3array );
  45992. copyArray( cache, elements );
  45993. }
  45994. }
  45995. function setValueM4( gl, v ) {
  45996. const cache = this.cache;
  45997. const elements = v.elements;
  45998. if ( elements === undefined ) {
  45999. if ( arraysEqual( cache, v ) ) return;
  46000. gl.uniformMatrix4fv( this.addr, false, v );
  46001. copyArray( cache, v );
  46002. } else {
  46003. if ( arraysEqual( cache, elements ) ) return;
  46004. mat4array.set( elements );
  46005. gl.uniformMatrix4fv( this.addr, false, mat4array );
  46006. copyArray( cache, elements );
  46007. }
  46008. }
  46009. // Single integer / boolean
  46010. function setValueV1i( gl, v ) {
  46011. const cache = this.cache;
  46012. if ( cache[ 0 ] === v ) return;
  46013. gl.uniform1i( this.addr, v );
  46014. cache[ 0 ] = v;
  46015. }
  46016. // Single integer / boolean vector (from flat array or THREE.VectorN)
  46017. function setValueV2i( gl, v ) {
  46018. const cache = this.cache;
  46019. if ( v.x !== undefined ) {
  46020. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46021. gl.uniform2i( this.addr, v.x, v.y );
  46022. cache[ 0 ] = v.x;
  46023. cache[ 1 ] = v.y;
  46024. }
  46025. } else {
  46026. if ( arraysEqual( cache, v ) ) return;
  46027. gl.uniform2iv( this.addr, v );
  46028. copyArray( cache, v );
  46029. }
  46030. }
  46031. function setValueV3i( gl, v ) {
  46032. const cache = this.cache;
  46033. if ( v.x !== undefined ) {
  46034. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46035. gl.uniform3i( this.addr, v.x, v.y, v.z );
  46036. cache[ 0 ] = v.x;
  46037. cache[ 1 ] = v.y;
  46038. cache[ 2 ] = v.z;
  46039. }
  46040. } else {
  46041. if ( arraysEqual( cache, v ) ) return;
  46042. gl.uniform3iv( this.addr, v );
  46043. copyArray( cache, v );
  46044. }
  46045. }
  46046. function setValueV4i( gl, v ) {
  46047. const cache = this.cache;
  46048. if ( v.x !== undefined ) {
  46049. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46050. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  46051. cache[ 0 ] = v.x;
  46052. cache[ 1 ] = v.y;
  46053. cache[ 2 ] = v.z;
  46054. cache[ 3 ] = v.w;
  46055. }
  46056. } else {
  46057. if ( arraysEqual( cache, v ) ) return;
  46058. gl.uniform4iv( this.addr, v );
  46059. copyArray( cache, v );
  46060. }
  46061. }
  46062. // Single unsigned integer
  46063. function setValueV1ui( gl, v ) {
  46064. const cache = this.cache;
  46065. if ( cache[ 0 ] === v ) return;
  46066. gl.uniform1ui( this.addr, v );
  46067. cache[ 0 ] = v;
  46068. }
  46069. // Single unsigned integer vector (from flat array or THREE.VectorN)
  46070. function setValueV2ui( gl, v ) {
  46071. const cache = this.cache;
  46072. if ( v.x !== undefined ) {
  46073. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  46074. gl.uniform2ui( this.addr, v.x, v.y );
  46075. cache[ 0 ] = v.x;
  46076. cache[ 1 ] = v.y;
  46077. }
  46078. } else {
  46079. if ( arraysEqual( cache, v ) ) return;
  46080. gl.uniform2uiv( this.addr, v );
  46081. copyArray( cache, v );
  46082. }
  46083. }
  46084. function setValueV3ui( gl, v ) {
  46085. const cache = this.cache;
  46086. if ( v.x !== undefined ) {
  46087. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  46088. gl.uniform3ui( this.addr, v.x, v.y, v.z );
  46089. cache[ 0 ] = v.x;
  46090. cache[ 1 ] = v.y;
  46091. cache[ 2 ] = v.z;
  46092. }
  46093. } else {
  46094. if ( arraysEqual( cache, v ) ) return;
  46095. gl.uniform3uiv( this.addr, v );
  46096. copyArray( cache, v );
  46097. }
  46098. }
  46099. function setValueV4ui( gl, v ) {
  46100. const cache = this.cache;
  46101. if ( v.x !== undefined ) {
  46102. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  46103. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  46104. cache[ 0 ] = v.x;
  46105. cache[ 1 ] = v.y;
  46106. cache[ 2 ] = v.z;
  46107. cache[ 3 ] = v.w;
  46108. }
  46109. } else {
  46110. if ( arraysEqual( cache, v ) ) return;
  46111. gl.uniform4uiv( this.addr, v );
  46112. copyArray( cache, v );
  46113. }
  46114. }
  46115. // Single texture (2D / Cube)
  46116. function setValueT1( gl, v, textures ) {
  46117. const cache = this.cache;
  46118. const unit = textures.allocateTextureUnit();
  46119. if ( cache[ 0 ] !== unit ) {
  46120. gl.uniform1i( this.addr, unit );
  46121. cache[ 0 ] = unit;
  46122. }
  46123. let emptyTexture2D;
  46124. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46125. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  46126. emptyTexture2D = emptyShadowTexture;
  46127. } else {
  46128. emptyTexture2D = emptyTexture;
  46129. }
  46130. textures.setTexture2D( v || emptyTexture2D, unit );
  46131. }
  46132. function setValueT3D1( gl, v, textures ) {
  46133. const cache = this.cache;
  46134. const unit = textures.allocateTextureUnit();
  46135. if ( cache[ 0 ] !== unit ) {
  46136. gl.uniform1i( this.addr, unit );
  46137. cache[ 0 ] = unit;
  46138. }
  46139. textures.setTexture3D( v || empty3dTexture, unit );
  46140. }
  46141. function setValueT6( gl, v, textures ) {
  46142. const cache = this.cache;
  46143. const unit = textures.allocateTextureUnit();
  46144. if ( cache[ 0 ] !== unit ) {
  46145. gl.uniform1i( this.addr, unit );
  46146. cache[ 0 ] = unit;
  46147. }
  46148. textures.setTextureCube( v || emptyCubeTexture, unit );
  46149. }
  46150. function setValueT2DArray1( gl, v, textures ) {
  46151. const cache = this.cache;
  46152. const unit = textures.allocateTextureUnit();
  46153. if ( cache[ 0 ] !== unit ) {
  46154. gl.uniform1i( this.addr, unit );
  46155. cache[ 0 ] = unit;
  46156. }
  46157. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  46158. }
  46159. // Helper to pick the right setter for the singular case
  46160. function getSingularSetter( type ) {
  46161. switch ( type ) {
  46162. case 0x1406: return setValueV1f; // FLOAT
  46163. case 0x8b50: return setValueV2f; // _VEC2
  46164. case 0x8b51: return setValueV3f; // _VEC3
  46165. case 0x8b52: return setValueV4f; // _VEC4
  46166. case 0x8b5a: return setValueM2; // _MAT2
  46167. case 0x8b5b: return setValueM3; // _MAT3
  46168. case 0x8b5c: return setValueM4; // _MAT4
  46169. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  46170. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  46171. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  46172. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  46173. case 0x1405: return setValueV1ui; // UINT
  46174. case 0x8dc6: return setValueV2ui; // _VEC2
  46175. case 0x8dc7: return setValueV3ui; // _VEC3
  46176. case 0x8dc8: return setValueV4ui; // _VEC4
  46177. case 0x8b5e: // SAMPLER_2D
  46178. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46179. case 0x8dca: // INT_SAMPLER_2D
  46180. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46181. case 0x8b62: // SAMPLER_2D_SHADOW
  46182. return setValueT1;
  46183. case 0x8b5f: // SAMPLER_3D
  46184. case 0x8dcb: // INT_SAMPLER_3D
  46185. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46186. return setValueT3D1;
  46187. case 0x8b60: // SAMPLER_CUBE
  46188. case 0x8dcc: // INT_SAMPLER_CUBE
  46189. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46190. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46191. return setValueT6;
  46192. case 0x8dc1: // SAMPLER_2D_ARRAY
  46193. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46194. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46195. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46196. return setValueT2DArray1;
  46197. }
  46198. }
  46199. // Array of scalars
  46200. function setValueV1fArray( gl, v ) {
  46201. gl.uniform1fv( this.addr, v );
  46202. }
  46203. // Array of vectors (from flat array or array of THREE.VectorN)
  46204. function setValueV2fArray( gl, v ) {
  46205. const data = flatten( v, this.size, 2 );
  46206. gl.uniform2fv( this.addr, data );
  46207. }
  46208. function setValueV3fArray( gl, v ) {
  46209. const data = flatten( v, this.size, 3 );
  46210. gl.uniform3fv( this.addr, data );
  46211. }
  46212. function setValueV4fArray( gl, v ) {
  46213. const data = flatten( v, this.size, 4 );
  46214. gl.uniform4fv( this.addr, data );
  46215. }
  46216. // Array of matrices (from flat array or array of THREE.MatrixN)
  46217. function setValueM2Array( gl, v ) {
  46218. const data = flatten( v, this.size, 4 );
  46219. gl.uniformMatrix2fv( this.addr, false, data );
  46220. }
  46221. function setValueM3Array( gl, v ) {
  46222. const data = flatten( v, this.size, 9 );
  46223. gl.uniformMatrix3fv( this.addr, false, data );
  46224. }
  46225. function setValueM4Array( gl, v ) {
  46226. const data = flatten( v, this.size, 16 );
  46227. gl.uniformMatrix4fv( this.addr, false, data );
  46228. }
  46229. // Array of integer / boolean
  46230. function setValueV1iArray( gl, v ) {
  46231. gl.uniform1iv( this.addr, v );
  46232. }
  46233. // Array of integer / boolean vectors (from flat array)
  46234. function setValueV2iArray( gl, v ) {
  46235. gl.uniform2iv( this.addr, v );
  46236. }
  46237. function setValueV3iArray( gl, v ) {
  46238. gl.uniform3iv( this.addr, v );
  46239. }
  46240. function setValueV4iArray( gl, v ) {
  46241. gl.uniform4iv( this.addr, v );
  46242. }
  46243. // Array of unsigned integer
  46244. function setValueV1uiArray( gl, v ) {
  46245. gl.uniform1uiv( this.addr, v );
  46246. }
  46247. // Array of unsigned integer vectors (from flat array)
  46248. function setValueV2uiArray( gl, v ) {
  46249. gl.uniform2uiv( this.addr, v );
  46250. }
  46251. function setValueV3uiArray( gl, v ) {
  46252. gl.uniform3uiv( this.addr, v );
  46253. }
  46254. function setValueV4uiArray( gl, v ) {
  46255. gl.uniform4uiv( this.addr, v );
  46256. }
  46257. // Array of textures (2D / 3D / Cube / 2DArray)
  46258. function setValueT1Array( gl, v, textures ) {
  46259. const cache = this.cache;
  46260. const n = v.length;
  46261. const units = allocTexUnits( textures, n );
  46262. if ( ! arraysEqual( cache, units ) ) {
  46263. gl.uniform1iv( this.addr, units );
  46264. copyArray( cache, units );
  46265. }
  46266. let emptyTexture2D;
  46267. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46268. emptyTexture2D = emptyShadowTexture;
  46269. } else {
  46270. emptyTexture2D = emptyTexture;
  46271. }
  46272. for ( let i = 0; i !== n; ++ i ) {
  46273. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  46274. }
  46275. }
  46276. function setValueT3DArray( gl, v, textures ) {
  46277. const cache = this.cache;
  46278. const n = v.length;
  46279. const units = allocTexUnits( textures, n );
  46280. if ( ! arraysEqual( cache, units ) ) {
  46281. gl.uniform1iv( this.addr, units );
  46282. copyArray( cache, units );
  46283. }
  46284. for ( let i = 0; i !== n; ++ i ) {
  46285. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  46286. }
  46287. }
  46288. function setValueT6Array( gl, v, textures ) {
  46289. const cache = this.cache;
  46290. const n = v.length;
  46291. const units = allocTexUnits( textures, n );
  46292. if ( ! arraysEqual( cache, units ) ) {
  46293. gl.uniform1iv( this.addr, units );
  46294. copyArray( cache, units );
  46295. }
  46296. for ( let i = 0; i !== n; ++ i ) {
  46297. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  46298. }
  46299. }
  46300. function setValueT2DArrayArray( gl, v, textures ) {
  46301. const cache = this.cache;
  46302. const n = v.length;
  46303. const units = allocTexUnits( textures, n );
  46304. if ( ! arraysEqual( cache, units ) ) {
  46305. gl.uniform1iv( this.addr, units );
  46306. copyArray( cache, units );
  46307. }
  46308. for ( let i = 0; i !== n; ++ i ) {
  46309. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  46310. }
  46311. }
  46312. // Helper to pick the right setter for a pure (bottom-level) array
  46313. function getPureArraySetter( type ) {
  46314. switch ( type ) {
  46315. case 0x1406: return setValueV1fArray; // FLOAT
  46316. case 0x8b50: return setValueV2fArray; // _VEC2
  46317. case 0x8b51: return setValueV3fArray; // _VEC3
  46318. case 0x8b52: return setValueV4fArray; // _VEC4
  46319. case 0x8b5a: return setValueM2Array; // _MAT2
  46320. case 0x8b5b: return setValueM3Array; // _MAT3
  46321. case 0x8b5c: return setValueM4Array; // _MAT4
  46322. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  46323. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  46324. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  46325. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  46326. case 0x1405: return setValueV1uiArray; // UINT
  46327. case 0x8dc6: return setValueV2uiArray; // _VEC2
  46328. case 0x8dc7: return setValueV3uiArray; // _VEC3
  46329. case 0x8dc8: return setValueV4uiArray; // _VEC4
  46330. case 0x8b5e: // SAMPLER_2D
  46331. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46332. case 0x8dca: // INT_SAMPLER_2D
  46333. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46334. case 0x8b62: // SAMPLER_2D_SHADOW
  46335. return setValueT1Array;
  46336. case 0x8b5f: // SAMPLER_3D
  46337. case 0x8dcb: // INT_SAMPLER_3D
  46338. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46339. return setValueT3DArray;
  46340. case 0x8b60: // SAMPLER_CUBE
  46341. case 0x8dcc: // INT_SAMPLER_CUBE
  46342. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46343. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46344. return setValueT6Array;
  46345. case 0x8dc1: // SAMPLER_2D_ARRAY
  46346. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46347. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46348. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46349. return setValueT2DArrayArray;
  46350. }
  46351. }
  46352. // --- Uniform Classes ---
  46353. class SingleUniform {
  46354. constructor( id, activeInfo, addr ) {
  46355. this.id = id;
  46356. this.addr = addr;
  46357. this.cache = [];
  46358. this.type = activeInfo.type;
  46359. this.setValue = getSingularSetter( activeInfo.type );
  46360. // this.path = activeInfo.name; // DEBUG
  46361. }
  46362. }
  46363. class PureArrayUniform {
  46364. constructor( id, activeInfo, addr ) {
  46365. this.id = id;
  46366. this.addr = addr;
  46367. this.cache = [];
  46368. this.type = activeInfo.type;
  46369. this.size = activeInfo.size;
  46370. this.setValue = getPureArraySetter( activeInfo.type );
  46371. // this.path = activeInfo.name; // DEBUG
  46372. }
  46373. }
  46374. class StructuredUniform {
  46375. constructor( id ) {
  46376. this.id = id;
  46377. this.seq = [];
  46378. this.map = {};
  46379. }
  46380. setValue( gl, value, textures ) {
  46381. const seq = this.seq;
  46382. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46383. const u = seq[ i ];
  46384. u.setValue( gl, value[ u.id ], textures );
  46385. }
  46386. }
  46387. }
  46388. // --- Top-level ---
  46389. // Parser - builds up the property tree from the path strings
  46390. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  46391. // extracts
  46392. // - the identifier (member name or array index)
  46393. // - followed by an optional right bracket (found when array index)
  46394. // - followed by an optional left bracket or dot (type of subscript)
  46395. //
  46396. // Note: These portions can be read in a non-overlapping fashion and
  46397. // allow straightforward parsing of the hierarchy that WebGL encodes
  46398. // in the uniform names.
  46399. function addUniform( container, uniformObject ) {
  46400. container.seq.push( uniformObject );
  46401. container.map[ uniformObject.id ] = uniformObject;
  46402. }
  46403. function parseUniform( activeInfo, addr, container ) {
  46404. const path = activeInfo.name,
  46405. pathLength = path.length;
  46406. // reset RegExp object, because of the early exit of a previous run
  46407. RePathPart.lastIndex = 0;
  46408. while ( true ) {
  46409. const match = RePathPart.exec( path ),
  46410. matchEnd = RePathPart.lastIndex;
  46411. let id = match[ 1 ];
  46412. const idIsIndex = match[ 2 ] === ']',
  46413. subscript = match[ 3 ];
  46414. if ( idIsIndex ) id = id | 0; // convert to integer
  46415. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  46416. // bare name or "pure" bottom-level array "[0]" suffix
  46417. addUniform( container, subscript === undefined ?
  46418. new SingleUniform( id, activeInfo, addr ) :
  46419. new PureArrayUniform( id, activeInfo, addr ) );
  46420. break;
  46421. } else {
  46422. // step into inner node / create it in case it doesn't exist
  46423. const map = container.map;
  46424. let next = map[ id ];
  46425. if ( next === undefined ) {
  46426. next = new StructuredUniform( id );
  46427. addUniform( container, next );
  46428. }
  46429. container = next;
  46430. }
  46431. }
  46432. }
  46433. // Root Container
  46434. class WebGLUniforms {
  46435. constructor( gl, program ) {
  46436. this.seq = [];
  46437. this.map = {};
  46438. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  46439. for ( let i = 0; i < n; ++ i ) {
  46440. const info = gl.getActiveUniform( program, i ),
  46441. addr = gl.getUniformLocation( program, info.name );
  46442. parseUniform( info, addr, this );
  46443. }
  46444. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  46445. const shadowSamplers = [];
  46446. const otherUniforms = [];
  46447. for ( const u of this.seq ) {
  46448. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  46449. shadowSamplers.push( u );
  46450. } else {
  46451. otherUniforms.push( u );
  46452. }
  46453. }
  46454. if ( shadowSamplers.length > 0 ) {
  46455. this.seq = shadowSamplers.concat( otherUniforms );
  46456. }
  46457. }
  46458. setValue( gl, name, value, textures ) {
  46459. const u = this.map[ name ];
  46460. if ( u !== undefined ) u.setValue( gl, value, textures );
  46461. }
  46462. setOptional( gl, object, name ) {
  46463. const v = object[ name ];
  46464. if ( v !== undefined ) this.setValue( gl, name, v );
  46465. }
  46466. static upload( gl, seq, values, textures ) {
  46467. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46468. const u = seq[ i ],
  46469. v = values[ u.id ];
  46470. if ( v.needsUpdate !== false ) {
  46471. // note: always updating when .needsUpdate is undefined
  46472. u.setValue( gl, v.value, textures );
  46473. }
  46474. }
  46475. }
  46476. static seqWithValue( seq, values ) {
  46477. const r = [];
  46478. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46479. const u = seq[ i ];
  46480. if ( u.id in values ) r.push( u );
  46481. }
  46482. return r;
  46483. }
  46484. }
  46485. function WebGLShader( gl, type, string ) {
  46486. const shader = gl.createShader( type );
  46487. gl.shaderSource( shader, string );
  46488. gl.compileShader( shader );
  46489. return shader;
  46490. }
  46491. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46492. const COMPLETION_STATUS_KHR = 0x91B1;
  46493. let programIdCount = 0;
  46494. function handleSource( string, errorLine ) {
  46495. const lines = string.split( '\n' );
  46496. const lines2 = [];
  46497. const from = Math.max( errorLine - 6, 0 );
  46498. const to = Math.min( errorLine + 6, lines.length );
  46499. for ( let i = from; i < to; i ++ ) {
  46500. const line = i + 1;
  46501. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46502. }
  46503. return lines2.join( '\n' );
  46504. }
  46505. const _m0 = /*@__PURE__*/ new Matrix3();
  46506. function getEncodingComponents( colorSpace ) {
  46507. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  46508. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  46509. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  46510. case LinearTransfer:
  46511. return [ encodingMatrix, 'LinearTransferOETF' ];
  46512. case SRGBTransfer:
  46513. return [ encodingMatrix, 'sRGBTransferOETF' ];
  46514. default:
  46515. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  46516. return [ encodingMatrix, 'LinearTransferOETF' ];
  46517. }
  46518. }
  46519. function getShaderErrors( gl, shader, type ) {
  46520. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46521. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46522. const errors = shaderInfoLog.trim();
  46523. if ( status && errors === '' ) return '';
  46524. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46525. if ( errorMatches ) {
  46526. // --enable-privileged-webgl-extension
  46527. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46528. const errorLine = parseInt( errorMatches[ 1 ] );
  46529. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46530. } else {
  46531. return errors;
  46532. }
  46533. }
  46534. function getTexelEncodingFunction( functionName, colorSpace ) {
  46535. const components = getEncodingComponents( colorSpace );
  46536. return [
  46537. `vec4 ${functionName}( vec4 value ) {`,
  46538. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46539. '}',
  46540. ].join( '\n' );
  46541. }
  46542. const toneMappingFunctions = {
  46543. [ LinearToneMapping ]: 'Linear',
  46544. [ ReinhardToneMapping ]: 'Reinhard',
  46545. [ CineonToneMapping ]: 'Cineon',
  46546. [ ACESFilmicToneMapping ]: 'ACESFilmic',
  46547. [ AgXToneMapping ]: 'AgX',
  46548. [ NeutralToneMapping ]: 'Neutral',
  46549. [ CustomToneMapping ]: 'Custom'
  46550. };
  46551. function getToneMappingFunction( functionName, toneMapping ) {
  46552. const toneMappingName = toneMappingFunctions[ toneMapping ];
  46553. if ( toneMappingName === undefined ) {
  46554. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  46555. return 'vec3 ' + functionName + '( vec3 color ) { return LinearToneMapping( color ); }';
  46556. }
  46557. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46558. }
  46559. const _v0 = /*@__PURE__*/ new Vector3();
  46560. function getLuminanceFunction() {
  46561. ColorManagement.getLuminanceCoefficients( _v0 );
  46562. const r = _v0.x.toFixed( 4 );
  46563. const g = _v0.y.toFixed( 4 );
  46564. const b = _v0.z.toFixed( 4 );
  46565. return [
  46566. 'float luminance( const in vec3 rgb ) {',
  46567. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46568. ' return dot( weights, rgb );',
  46569. '}'
  46570. ].join( '\n' );
  46571. }
  46572. function generateVertexExtensions( parameters ) {
  46573. const chunks = [
  46574. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46575. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46576. ];
  46577. return chunks.filter( filterEmptyLine ).join( '\n' );
  46578. }
  46579. function generateDefines( defines ) {
  46580. const chunks = [];
  46581. for ( const name in defines ) {
  46582. const value = defines[ name ];
  46583. if ( value === false ) continue;
  46584. chunks.push( '#define ' + name + ' ' + value );
  46585. }
  46586. return chunks.join( '\n' );
  46587. }
  46588. function fetchAttributeLocations( gl, program ) {
  46589. const attributes = {};
  46590. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46591. for ( let i = 0; i < n; i ++ ) {
  46592. const info = gl.getActiveAttrib( program, i );
  46593. const name = info.name;
  46594. let locationSize = 1;
  46595. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46596. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46597. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46598. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46599. attributes[ name ] = {
  46600. type: info.type,
  46601. location: gl.getAttribLocation( program, name ),
  46602. locationSize: locationSize
  46603. };
  46604. }
  46605. return attributes;
  46606. }
  46607. function filterEmptyLine( string ) {
  46608. return string !== '';
  46609. }
  46610. function replaceLightNums( string, parameters ) {
  46611. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46612. return string
  46613. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46614. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46615. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46616. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46617. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46618. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46619. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46620. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46621. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46622. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46623. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46624. }
  46625. function replaceClippingPlaneNums( string, parameters ) {
  46626. return string
  46627. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46628. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46629. }
  46630. // Resolve Includes
  46631. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46632. function resolveIncludes( string ) {
  46633. return string.replace( includePattern, includeReplacer );
  46634. }
  46635. const shaderChunkMap = new Map();
  46636. function includeReplacer( match, include ) {
  46637. let string = ShaderChunk[ include ];
  46638. if ( string === undefined ) {
  46639. const newInclude = shaderChunkMap.get( include );
  46640. if ( newInclude !== undefined ) {
  46641. string = ShaderChunk[ newInclude ];
  46642. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46643. } else {
  46644. throw new Error( 'Can not resolve #include <' + include + '>' );
  46645. }
  46646. }
  46647. return resolveIncludes( string );
  46648. }
  46649. // Unroll Loops
  46650. 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;
  46651. function unrollLoops( string ) {
  46652. return string.replace( unrollLoopPattern, loopReplacer );
  46653. }
  46654. function loopReplacer( match, start, end, snippet ) {
  46655. let string = '';
  46656. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46657. string += snippet
  46658. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46659. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46660. }
  46661. return string;
  46662. }
  46663. //
  46664. function generatePrecision( parameters ) {
  46665. let precisionstring = `precision ${parameters.precision} float;
  46666. precision ${parameters.precision} int;
  46667. precision ${parameters.precision} sampler2D;
  46668. precision ${parameters.precision} samplerCube;
  46669. precision ${parameters.precision} sampler3D;
  46670. precision ${parameters.precision} sampler2DArray;
  46671. precision ${parameters.precision} sampler2DShadow;
  46672. precision ${parameters.precision} samplerCubeShadow;
  46673. precision ${parameters.precision} sampler2DArrayShadow;
  46674. precision ${parameters.precision} isampler2D;
  46675. precision ${parameters.precision} isampler3D;
  46676. precision ${parameters.precision} isamplerCube;
  46677. precision ${parameters.precision} isampler2DArray;
  46678. precision ${parameters.precision} usampler2D;
  46679. precision ${parameters.precision} usampler3D;
  46680. precision ${parameters.precision} usamplerCube;
  46681. precision ${parameters.precision} usampler2DArray;
  46682. `;
  46683. if ( parameters.precision === 'highp' ) {
  46684. precisionstring += '\n#define HIGH_PRECISION';
  46685. } else if ( parameters.precision === 'mediump' ) {
  46686. precisionstring += '\n#define MEDIUM_PRECISION';
  46687. } else if ( parameters.precision === 'lowp' ) {
  46688. precisionstring += '\n#define LOW_PRECISION';
  46689. }
  46690. return precisionstring;
  46691. }
  46692. const shadowMapTypeDefines = {
  46693. [ PCFShadowMap ]: 'SHADOWMAP_TYPE_PCF',
  46694. [ VSMShadowMap ]: 'SHADOWMAP_TYPE_VSM'
  46695. };
  46696. function generateShadowMapTypeDefine( parameters ) {
  46697. return shadowMapTypeDefines[ parameters.shadowMapType ] || 'SHADOWMAP_TYPE_BASIC';
  46698. }
  46699. const envMapTypeDefines = {
  46700. [ CubeReflectionMapping ]: 'ENVMAP_TYPE_CUBE',
  46701. [ CubeRefractionMapping ]: 'ENVMAP_TYPE_CUBE',
  46702. [ CubeUVReflectionMapping ]: 'ENVMAP_TYPE_CUBE_UV'
  46703. };
  46704. function generateEnvMapTypeDefine( parameters ) {
  46705. if ( parameters.envMap === false ) return 'ENVMAP_TYPE_CUBE';
  46706. return envMapTypeDefines[ parameters.envMapMode ] || 'ENVMAP_TYPE_CUBE';
  46707. }
  46708. const envMapModeDefines = {
  46709. [ CubeRefractionMapping ]: 'ENVMAP_MODE_REFRACTION'
  46710. };
  46711. function generateEnvMapModeDefine( parameters ) {
  46712. if ( parameters.envMap === false ) return 'ENVMAP_MODE_REFLECTION';
  46713. return envMapModeDefines[ parameters.envMapMode ] || 'ENVMAP_MODE_REFLECTION';
  46714. }
  46715. const envMapBlendingDefines = {
  46716. [ MultiplyOperation ]: 'ENVMAP_BLENDING_MULTIPLY',
  46717. [ MixOperation ]: 'ENVMAP_BLENDING_MIX',
  46718. [ AddOperation ]: 'ENVMAP_BLENDING_ADD'
  46719. };
  46720. function generateEnvMapBlendingDefine( parameters ) {
  46721. if ( parameters.envMap === false ) return 'ENVMAP_BLENDING_NONE';
  46722. return envMapBlendingDefines[ parameters.combine ] || 'ENVMAP_BLENDING_NONE';
  46723. }
  46724. function generateCubeUVSize( parameters ) {
  46725. const imageHeight = parameters.envMapCubeUVHeight;
  46726. if ( imageHeight === null ) return null;
  46727. const maxMip = Math.log2( imageHeight ) - 2;
  46728. const texelHeight = 1.0 / imageHeight;
  46729. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46730. return { texelWidth, texelHeight, maxMip };
  46731. }
  46732. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46733. // TODO Send this event to Three.js DevTools
  46734. // log( 'WebGLProgram', cacheKey );
  46735. const gl = renderer.getContext();
  46736. const defines = parameters.defines;
  46737. let vertexShader = parameters.vertexShader;
  46738. let fragmentShader = parameters.fragmentShader;
  46739. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46740. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46741. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46742. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46743. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46744. const customVertexExtensions = generateVertexExtensions( parameters );
  46745. const customDefines = generateDefines( defines );
  46746. const program = gl.createProgram();
  46747. let prefixVertex, prefixFragment;
  46748. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46749. if ( parameters.isRawShaderMaterial ) {
  46750. prefixVertex = [
  46751. '#define SHADER_TYPE ' + parameters.shaderType,
  46752. '#define SHADER_NAME ' + parameters.shaderName,
  46753. customDefines
  46754. ].filter( filterEmptyLine ).join( '\n' );
  46755. if ( prefixVertex.length > 0 ) {
  46756. prefixVertex += '\n';
  46757. }
  46758. prefixFragment = [
  46759. '#define SHADER_TYPE ' + parameters.shaderType,
  46760. '#define SHADER_NAME ' + parameters.shaderName,
  46761. customDefines
  46762. ].filter( filterEmptyLine ).join( '\n' );
  46763. if ( prefixFragment.length > 0 ) {
  46764. prefixFragment += '\n';
  46765. }
  46766. } else {
  46767. prefixVertex = [
  46768. generatePrecision( parameters ),
  46769. '#define SHADER_TYPE ' + parameters.shaderType,
  46770. '#define SHADER_NAME ' + parameters.shaderName,
  46771. customDefines,
  46772. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46773. parameters.batching ? '#define USE_BATCHING' : '',
  46774. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46775. parameters.instancing ? '#define USE_INSTANCING' : '',
  46776. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46777. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46778. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46779. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46780. parameters.map ? '#define USE_MAP' : '',
  46781. parameters.envMap ? '#define USE_ENVMAP' : '',
  46782. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46783. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46784. parameters.aoMap ? '#define USE_AOMAP' : '',
  46785. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46786. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46787. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46788. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46789. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46790. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46791. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46792. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46793. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46794. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46795. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46796. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46797. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46798. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46799. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46800. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46801. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46802. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46803. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46804. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46805. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46806. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46807. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46808. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46809. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46810. //
  46811. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46812. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46813. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46814. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46815. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46816. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46817. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46818. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46819. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46820. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46821. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46822. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46823. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46824. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46825. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46826. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46827. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46828. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46829. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46830. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46831. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46832. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46833. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46834. //
  46835. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46836. parameters.vertexColors ? '#define USE_COLOR' : '',
  46837. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46838. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46839. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46840. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46841. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46842. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46843. parameters.skinning ? '#define USE_SKINNING' : '',
  46844. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46845. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46846. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46847. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46848. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46849. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46850. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46851. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46852. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46853. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46854. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46855. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46856. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46857. 'uniform mat4 modelMatrix;',
  46858. 'uniform mat4 modelViewMatrix;',
  46859. 'uniform mat4 projectionMatrix;',
  46860. 'uniform mat4 viewMatrix;',
  46861. 'uniform mat3 normalMatrix;',
  46862. 'uniform vec3 cameraPosition;',
  46863. 'uniform bool isOrthographic;',
  46864. '#ifdef USE_INSTANCING',
  46865. ' attribute mat4 instanceMatrix;',
  46866. '#endif',
  46867. '#ifdef USE_INSTANCING_COLOR',
  46868. ' attribute vec3 instanceColor;',
  46869. '#endif',
  46870. '#ifdef USE_INSTANCING_MORPH',
  46871. ' uniform sampler2D morphTexture;',
  46872. '#endif',
  46873. 'attribute vec3 position;',
  46874. 'attribute vec3 normal;',
  46875. 'attribute vec2 uv;',
  46876. '#ifdef USE_UV1',
  46877. ' attribute vec2 uv1;',
  46878. '#endif',
  46879. '#ifdef USE_UV2',
  46880. ' attribute vec2 uv2;',
  46881. '#endif',
  46882. '#ifdef USE_UV3',
  46883. ' attribute vec2 uv3;',
  46884. '#endif',
  46885. '#ifdef USE_TANGENT',
  46886. ' attribute vec4 tangent;',
  46887. '#endif',
  46888. '#if defined( USE_COLOR_ALPHA )',
  46889. ' attribute vec4 color;',
  46890. '#elif defined( USE_COLOR )',
  46891. ' attribute vec3 color;',
  46892. '#endif',
  46893. '#ifdef USE_SKINNING',
  46894. ' attribute vec4 skinIndex;',
  46895. ' attribute vec4 skinWeight;',
  46896. '#endif',
  46897. '\n'
  46898. ].filter( filterEmptyLine ).join( '\n' );
  46899. prefixFragment = [
  46900. generatePrecision( parameters ),
  46901. '#define SHADER_TYPE ' + parameters.shaderType,
  46902. '#define SHADER_NAME ' + parameters.shaderName,
  46903. customDefines,
  46904. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46905. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46906. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  46907. parameters.map ? '#define USE_MAP' : '',
  46908. parameters.matcap ? '#define USE_MATCAP' : '',
  46909. parameters.envMap ? '#define USE_ENVMAP' : '',
  46910. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  46911. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46912. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  46913. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  46914. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  46915. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  46916. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46917. parameters.aoMap ? '#define USE_AOMAP' : '',
  46918. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46919. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46920. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46921. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46922. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46923. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46924. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46925. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  46926. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46927. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46928. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46929. parameters.dispersion ? '#define USE_DISPERSION' : '',
  46930. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  46931. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46932. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46933. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46934. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46935. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46936. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46937. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46938. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46939. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  46940. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46941. parameters.sheen ? '#define USE_SHEEN' : '',
  46942. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46943. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46944. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46945. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46946. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46947. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46948. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  46949. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46950. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46951. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46952. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46953. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46954. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  46955. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46956. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46957. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46958. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46959. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46960. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  46961. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46962. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  46963. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  46964. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46965. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46966. 'uniform mat4 viewMatrix;',
  46967. 'uniform vec3 cameraPosition;',
  46968. 'uniform bool isOrthographic;',
  46969. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  46970. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  46971. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  46972. parameters.dithering ? '#define DITHERING' : '',
  46973. parameters.opaque ? '#define OPAQUE' : '',
  46974. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  46975. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  46976. getLuminanceFunction(),
  46977. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  46978. '\n'
  46979. ].filter( filterEmptyLine ).join( '\n' );
  46980. }
  46981. vertexShader = resolveIncludes( vertexShader );
  46982. vertexShader = replaceLightNums( vertexShader, parameters );
  46983. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  46984. fragmentShader = resolveIncludes( fragmentShader );
  46985. fragmentShader = replaceLightNums( fragmentShader, parameters );
  46986. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  46987. vertexShader = unrollLoops( vertexShader );
  46988. fragmentShader = unrollLoops( fragmentShader );
  46989. if ( parameters.isRawShaderMaterial !== true ) {
  46990. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  46991. versionString = '#version 300 es\n';
  46992. prefixVertex = [
  46993. customVertexExtensions,
  46994. '#define attribute in',
  46995. '#define varying out',
  46996. '#define texture2D texture'
  46997. ].join( '\n' ) + '\n' + prefixVertex;
  46998. prefixFragment = [
  46999. '#define varying in',
  47000. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  47001. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  47002. '#define gl_FragDepthEXT gl_FragDepth',
  47003. '#define texture2D texture',
  47004. '#define textureCube texture',
  47005. '#define texture2DProj textureProj',
  47006. '#define texture2DLodEXT textureLod',
  47007. '#define texture2DProjLodEXT textureProjLod',
  47008. '#define textureCubeLodEXT textureLod',
  47009. '#define texture2DGradEXT textureGrad',
  47010. '#define texture2DProjGradEXT textureProjGrad',
  47011. '#define textureCubeGradEXT textureGrad'
  47012. ].join( '\n' ) + '\n' + prefixFragment;
  47013. }
  47014. const vertexGlsl = versionString + prefixVertex + vertexShader;
  47015. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  47016. // log( '*VERTEX*', vertexGlsl );
  47017. // log( '*FRAGMENT*', fragmentGlsl );
  47018. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  47019. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  47020. gl.attachShader( program, glVertexShader );
  47021. gl.attachShader( program, glFragmentShader );
  47022. // Force a particular attribute to index 0.
  47023. if ( parameters.index0AttributeName !== undefined ) {
  47024. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  47025. } else if ( parameters.morphTargets === true ) {
  47026. // programs with morphTargets displace position out of attribute 0
  47027. gl.bindAttribLocation( program, 0, 'position' );
  47028. }
  47029. gl.linkProgram( program );
  47030. function onFirstUse( self ) {
  47031. // check for link errors
  47032. if ( renderer.debug.checkShaderErrors ) {
  47033. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  47034. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  47035. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  47036. const programLog = programInfoLog.trim();
  47037. const vertexLog = vertexShaderInfoLog.trim();
  47038. const fragmentLog = fragmentShaderInfoLog.trim();
  47039. let runnable = true;
  47040. let haveDiagnostics = true;
  47041. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  47042. runnable = false;
  47043. if ( typeof renderer.debug.onShaderError === 'function' ) {
  47044. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  47045. } else {
  47046. // default error reporting
  47047. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  47048. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  47049. error(
  47050. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  47051. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  47052. 'Material Name: ' + self.name + '\n' +
  47053. 'Material Type: ' + self.type + '\n\n' +
  47054. 'Program Info Log: ' + programLog + '\n' +
  47055. vertexErrors + '\n' +
  47056. fragmentErrors
  47057. );
  47058. }
  47059. } else if ( programLog !== '' ) {
  47060. warn( 'WebGLProgram: Program Info Log:', programLog );
  47061. } else if ( vertexLog === '' || fragmentLog === '' ) {
  47062. haveDiagnostics = false;
  47063. }
  47064. if ( haveDiagnostics ) {
  47065. self.diagnostics = {
  47066. runnable: runnable,
  47067. programLog: programLog,
  47068. vertexShader: {
  47069. log: vertexLog,
  47070. prefix: prefixVertex
  47071. },
  47072. fragmentShader: {
  47073. log: fragmentLog,
  47074. prefix: prefixFragment
  47075. }
  47076. };
  47077. }
  47078. }
  47079. // Clean up
  47080. // Crashes in iOS9 and iOS10. #18402
  47081. // gl.detachShader( program, glVertexShader );
  47082. // gl.detachShader( program, glFragmentShader );
  47083. gl.deleteShader( glVertexShader );
  47084. gl.deleteShader( glFragmentShader );
  47085. cachedUniforms = new WebGLUniforms( gl, program );
  47086. cachedAttributes = fetchAttributeLocations( gl, program );
  47087. }
  47088. // set up caching for uniform locations
  47089. let cachedUniforms;
  47090. this.getUniforms = function () {
  47091. if ( cachedUniforms === undefined ) {
  47092. // Populates cachedUniforms and cachedAttributes
  47093. onFirstUse( this );
  47094. }
  47095. return cachedUniforms;
  47096. };
  47097. // set up caching for attribute locations
  47098. let cachedAttributes;
  47099. this.getAttributes = function () {
  47100. if ( cachedAttributes === undefined ) {
  47101. // Populates cachedAttributes and cachedUniforms
  47102. onFirstUse( this );
  47103. }
  47104. return cachedAttributes;
  47105. };
  47106. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  47107. // flag the program as ready immediately. It may cause a stall when it's first used.
  47108. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  47109. this.isReady = function () {
  47110. if ( programReady === false ) {
  47111. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  47112. }
  47113. return programReady;
  47114. };
  47115. // free resource
  47116. this.destroy = function () {
  47117. bindingStates.releaseStatesOfProgram( this );
  47118. gl.deleteProgram( program );
  47119. this.program = undefined;
  47120. };
  47121. //
  47122. this.type = parameters.shaderType;
  47123. this.name = parameters.shaderName;
  47124. this.id = programIdCount ++;
  47125. this.cacheKey = cacheKey;
  47126. this.usedTimes = 1;
  47127. this.program = program;
  47128. this.vertexShader = glVertexShader;
  47129. this.fragmentShader = glFragmentShader;
  47130. return this;
  47131. }
  47132. let _id = 0;
  47133. class WebGLShaderCache {
  47134. constructor() {
  47135. this.shaderCache = new Map();
  47136. this.materialCache = new Map();
  47137. }
  47138. update( material ) {
  47139. const vertexShader = material.vertexShader;
  47140. const fragmentShader = material.fragmentShader;
  47141. const vertexShaderStage = this._getShaderStage( vertexShader );
  47142. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  47143. const materialShaders = this._getShaderCacheForMaterial( material );
  47144. if ( materialShaders.has( vertexShaderStage ) === false ) {
  47145. materialShaders.add( vertexShaderStage );
  47146. vertexShaderStage.usedTimes ++;
  47147. }
  47148. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  47149. materialShaders.add( fragmentShaderStage );
  47150. fragmentShaderStage.usedTimes ++;
  47151. }
  47152. return this;
  47153. }
  47154. remove( material ) {
  47155. const materialShaders = this.materialCache.get( material );
  47156. for ( const shaderStage of materialShaders ) {
  47157. shaderStage.usedTimes --;
  47158. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  47159. }
  47160. this.materialCache.delete( material );
  47161. return this;
  47162. }
  47163. getVertexShaderID( material ) {
  47164. return this._getShaderStage( material.vertexShader ).id;
  47165. }
  47166. getFragmentShaderID( material ) {
  47167. return this._getShaderStage( material.fragmentShader ).id;
  47168. }
  47169. dispose() {
  47170. this.shaderCache.clear();
  47171. this.materialCache.clear();
  47172. }
  47173. _getShaderCacheForMaterial( material ) {
  47174. const cache = this.materialCache;
  47175. let set = cache.get( material );
  47176. if ( set === undefined ) {
  47177. set = new Set();
  47178. cache.set( material, set );
  47179. }
  47180. return set;
  47181. }
  47182. _getShaderStage( code ) {
  47183. const cache = this.shaderCache;
  47184. let stage = cache.get( code );
  47185. if ( stage === undefined ) {
  47186. stage = new WebGLShaderStage( code );
  47187. cache.set( code, stage );
  47188. }
  47189. return stage;
  47190. }
  47191. }
  47192. class WebGLShaderStage {
  47193. constructor( code ) {
  47194. this.id = _id ++;
  47195. this.code = code;
  47196. this.usedTimes = 0;
  47197. }
  47198. }
  47199. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  47200. const _programLayers = new Layers();
  47201. const _customShaders = new WebGLShaderCache();
  47202. const _activeChannels = new Set();
  47203. const programs = [];
  47204. const programsMap = new Map();
  47205. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  47206. let precision = capabilities.precision;
  47207. const shaderIDs = {
  47208. MeshDepthMaterial: 'depth',
  47209. MeshDistanceMaterial: 'distance',
  47210. MeshNormalMaterial: 'normal',
  47211. MeshBasicMaterial: 'basic',
  47212. MeshLambertMaterial: 'lambert',
  47213. MeshPhongMaterial: 'phong',
  47214. MeshToonMaterial: 'toon',
  47215. MeshStandardMaterial: 'physical',
  47216. MeshPhysicalMaterial: 'physical',
  47217. MeshMatcapMaterial: 'matcap',
  47218. LineBasicMaterial: 'basic',
  47219. LineDashedMaterial: 'dashed',
  47220. PointsMaterial: 'points',
  47221. ShadowMaterial: 'shadow',
  47222. SpriteMaterial: 'sprite'
  47223. };
  47224. function getChannel( value ) {
  47225. _activeChannels.add( value );
  47226. if ( value === 0 ) return 'uv';
  47227. return `uv${ value }`;
  47228. }
  47229. function getParameters( material, lights, shadows, scene, object ) {
  47230. const fog = scene.fog;
  47231. const geometry = object.geometry;
  47232. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  47233. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  47234. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  47235. const shaderID = shaderIDs[ material.type ];
  47236. // heuristics to create shader parameters according to lights in the scene
  47237. // (not to blow over maxLights budget)
  47238. if ( material.precision !== null ) {
  47239. precision = capabilities.getMaxPrecision( material.precision );
  47240. if ( precision !== material.precision ) {
  47241. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  47242. }
  47243. }
  47244. //
  47245. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  47246. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  47247. let morphTextureStride = 0;
  47248. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  47249. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  47250. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  47251. //
  47252. let vertexShader, fragmentShader;
  47253. let customVertexShaderID, customFragmentShaderID;
  47254. if ( shaderID ) {
  47255. const shader = ShaderLib[ shaderID ];
  47256. vertexShader = shader.vertexShader;
  47257. fragmentShader = shader.fragmentShader;
  47258. } else {
  47259. vertexShader = material.vertexShader;
  47260. fragmentShader = material.fragmentShader;
  47261. _customShaders.update( material );
  47262. customVertexShaderID = _customShaders.getVertexShaderID( material );
  47263. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  47264. }
  47265. const currentRenderTarget = renderer.getRenderTarget();
  47266. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  47267. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  47268. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  47269. const HAS_MAP = !! material.map;
  47270. const HAS_MATCAP = !! material.matcap;
  47271. const HAS_ENVMAP = !! envMap;
  47272. const HAS_AOMAP = !! material.aoMap;
  47273. const HAS_LIGHTMAP = !! material.lightMap;
  47274. const HAS_BUMPMAP = !! material.bumpMap;
  47275. const HAS_NORMALMAP = !! material.normalMap;
  47276. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  47277. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  47278. const HAS_METALNESSMAP = !! material.metalnessMap;
  47279. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  47280. const HAS_ANISOTROPY = material.anisotropy > 0;
  47281. const HAS_CLEARCOAT = material.clearcoat > 0;
  47282. const HAS_DISPERSION = material.dispersion > 0;
  47283. const HAS_IRIDESCENCE = material.iridescence > 0;
  47284. const HAS_SHEEN = material.sheen > 0;
  47285. const HAS_TRANSMISSION = material.transmission > 0;
  47286. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  47287. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  47288. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  47289. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  47290. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  47291. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  47292. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  47293. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  47294. const HAS_SPECULARMAP = !! material.specularMap;
  47295. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  47296. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  47297. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  47298. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  47299. const HAS_GRADIENTMAP = !! material.gradientMap;
  47300. const HAS_ALPHAMAP = !! material.alphaMap;
  47301. const HAS_ALPHATEST = material.alphaTest > 0;
  47302. const HAS_ALPHAHASH = !! material.alphaHash;
  47303. const HAS_EXTENSIONS = !! material.extensions;
  47304. let toneMapping = NoToneMapping;
  47305. if ( material.toneMapped ) {
  47306. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  47307. toneMapping = renderer.toneMapping;
  47308. }
  47309. }
  47310. const parameters = {
  47311. shaderID: shaderID,
  47312. shaderType: material.type,
  47313. shaderName: material.name,
  47314. vertexShader: vertexShader,
  47315. fragmentShader: fragmentShader,
  47316. defines: material.defines,
  47317. customVertexShaderID: customVertexShaderID,
  47318. customFragmentShaderID: customFragmentShaderID,
  47319. isRawShaderMaterial: material.isRawShaderMaterial === true,
  47320. glslVersion: material.glslVersion,
  47321. precision: precision,
  47322. batching: IS_BATCHEDMESH,
  47323. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  47324. instancing: IS_INSTANCEDMESH,
  47325. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  47326. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  47327. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  47328. alphaToCoverage: !! material.alphaToCoverage,
  47329. map: HAS_MAP,
  47330. matcap: HAS_MATCAP,
  47331. envMap: HAS_ENVMAP,
  47332. envMapMode: HAS_ENVMAP && envMap.mapping,
  47333. envMapCubeUVHeight: envMapCubeUVHeight,
  47334. aoMap: HAS_AOMAP,
  47335. lightMap: HAS_LIGHTMAP,
  47336. bumpMap: HAS_BUMPMAP,
  47337. normalMap: HAS_NORMALMAP,
  47338. displacementMap: HAS_DISPLACEMENTMAP,
  47339. emissiveMap: HAS_EMISSIVEMAP,
  47340. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  47341. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  47342. metalnessMap: HAS_METALNESSMAP,
  47343. roughnessMap: HAS_ROUGHNESSMAP,
  47344. anisotropy: HAS_ANISOTROPY,
  47345. anisotropyMap: HAS_ANISOTROPYMAP,
  47346. clearcoat: HAS_CLEARCOAT,
  47347. clearcoatMap: HAS_CLEARCOATMAP,
  47348. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  47349. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  47350. dispersion: HAS_DISPERSION,
  47351. iridescence: HAS_IRIDESCENCE,
  47352. iridescenceMap: HAS_IRIDESCENCEMAP,
  47353. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  47354. sheen: HAS_SHEEN,
  47355. sheenColorMap: HAS_SHEEN_COLORMAP,
  47356. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  47357. specularMap: HAS_SPECULARMAP,
  47358. specularColorMap: HAS_SPECULAR_COLORMAP,
  47359. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  47360. transmission: HAS_TRANSMISSION,
  47361. transmissionMap: HAS_TRANSMISSIONMAP,
  47362. thicknessMap: HAS_THICKNESSMAP,
  47363. gradientMap: HAS_GRADIENTMAP,
  47364. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  47365. alphaMap: HAS_ALPHAMAP,
  47366. alphaTest: HAS_ALPHATEST,
  47367. alphaHash: HAS_ALPHAHASH,
  47368. combine: material.combine,
  47369. //
  47370. mapUv: HAS_MAP && getChannel( material.map.channel ),
  47371. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  47372. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  47373. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  47374. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  47375. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  47376. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  47377. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  47378. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  47379. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  47380. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  47381. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  47382. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  47383. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  47384. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  47385. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  47386. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  47387. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  47388. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  47389. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  47390. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  47391. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  47392. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  47393. //
  47394. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  47395. vertexColors: material.vertexColors,
  47396. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  47397. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  47398. fog: !! fog,
  47399. useFog: material.fog === true,
  47400. fogExp2: ( !! fog && fog.isFogExp2 ),
  47401. flatShading: ( material.flatShading === true && material.wireframe === false ),
  47402. sizeAttenuation: material.sizeAttenuation === true,
  47403. logarithmicDepthBuffer: logarithmicDepthBuffer,
  47404. reversedDepthBuffer: reversedDepthBuffer,
  47405. skinning: object.isSkinnedMesh === true,
  47406. morphTargets: geometry.morphAttributes.position !== undefined,
  47407. morphNormals: geometry.morphAttributes.normal !== undefined,
  47408. morphColors: geometry.morphAttributes.color !== undefined,
  47409. morphTargetsCount: morphTargetsCount,
  47410. morphTextureStride: morphTextureStride,
  47411. numDirLights: lights.directional.length,
  47412. numPointLights: lights.point.length,
  47413. numSpotLights: lights.spot.length,
  47414. numSpotLightMaps: lights.spotLightMap.length,
  47415. numRectAreaLights: lights.rectArea.length,
  47416. numHemiLights: lights.hemi.length,
  47417. numDirLightShadows: lights.directionalShadowMap.length,
  47418. numPointLightShadows: lights.pointShadowMap.length,
  47419. numSpotLightShadows: lights.spotShadowMap.length,
  47420. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  47421. numLightProbes: lights.numLightProbes,
  47422. numClippingPlanes: clipping.numPlanes,
  47423. numClipIntersection: clipping.numIntersection,
  47424. dithering: material.dithering,
  47425. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  47426. shadowMapType: renderer.shadowMap.type,
  47427. toneMapping: toneMapping,
  47428. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  47429. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  47430. premultipliedAlpha: material.premultipliedAlpha,
  47431. doubleSided: material.side === DoubleSide,
  47432. flipSided: material.side === BackSide,
  47433. useDepthPacking: material.depthPacking >= 0,
  47434. depthPacking: material.depthPacking || 0,
  47435. index0AttributeName: material.index0AttributeName,
  47436. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  47437. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  47438. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  47439. customProgramCacheKey: material.customProgramCacheKey()
  47440. };
  47441. // the usage of getChannel() determines the active texture channels for this shader
  47442. parameters.vertexUv1s = _activeChannels.has( 1 );
  47443. parameters.vertexUv2s = _activeChannels.has( 2 );
  47444. parameters.vertexUv3s = _activeChannels.has( 3 );
  47445. _activeChannels.clear();
  47446. return parameters;
  47447. }
  47448. function getProgramCacheKey( parameters ) {
  47449. const array = [];
  47450. if ( parameters.shaderID ) {
  47451. array.push( parameters.shaderID );
  47452. } else {
  47453. array.push( parameters.customVertexShaderID );
  47454. array.push( parameters.customFragmentShaderID );
  47455. }
  47456. if ( parameters.defines !== undefined ) {
  47457. for ( const name in parameters.defines ) {
  47458. array.push( name );
  47459. array.push( parameters.defines[ name ] );
  47460. }
  47461. }
  47462. if ( parameters.isRawShaderMaterial === false ) {
  47463. getProgramCacheKeyParameters( array, parameters );
  47464. getProgramCacheKeyBooleans( array, parameters );
  47465. array.push( renderer.outputColorSpace );
  47466. }
  47467. array.push( parameters.customProgramCacheKey );
  47468. return array.join();
  47469. }
  47470. function getProgramCacheKeyParameters( array, parameters ) {
  47471. array.push( parameters.precision );
  47472. array.push( parameters.outputColorSpace );
  47473. array.push( parameters.envMapMode );
  47474. array.push( parameters.envMapCubeUVHeight );
  47475. array.push( parameters.mapUv );
  47476. array.push( parameters.alphaMapUv );
  47477. array.push( parameters.lightMapUv );
  47478. array.push( parameters.aoMapUv );
  47479. array.push( parameters.bumpMapUv );
  47480. array.push( parameters.normalMapUv );
  47481. array.push( parameters.displacementMapUv );
  47482. array.push( parameters.emissiveMapUv );
  47483. array.push( parameters.metalnessMapUv );
  47484. array.push( parameters.roughnessMapUv );
  47485. array.push( parameters.anisotropyMapUv );
  47486. array.push( parameters.clearcoatMapUv );
  47487. array.push( parameters.clearcoatNormalMapUv );
  47488. array.push( parameters.clearcoatRoughnessMapUv );
  47489. array.push( parameters.iridescenceMapUv );
  47490. array.push( parameters.iridescenceThicknessMapUv );
  47491. array.push( parameters.sheenColorMapUv );
  47492. array.push( parameters.sheenRoughnessMapUv );
  47493. array.push( parameters.specularMapUv );
  47494. array.push( parameters.specularColorMapUv );
  47495. array.push( parameters.specularIntensityMapUv );
  47496. array.push( parameters.transmissionMapUv );
  47497. array.push( parameters.thicknessMapUv );
  47498. array.push( parameters.combine );
  47499. array.push( parameters.fogExp2 );
  47500. array.push( parameters.sizeAttenuation );
  47501. array.push( parameters.morphTargetsCount );
  47502. array.push( parameters.morphAttributeCount );
  47503. array.push( parameters.numDirLights );
  47504. array.push( parameters.numPointLights );
  47505. array.push( parameters.numSpotLights );
  47506. array.push( parameters.numSpotLightMaps );
  47507. array.push( parameters.numHemiLights );
  47508. array.push( parameters.numRectAreaLights );
  47509. array.push( parameters.numDirLightShadows );
  47510. array.push( parameters.numPointLightShadows );
  47511. array.push( parameters.numSpotLightShadows );
  47512. array.push( parameters.numSpotLightShadowsWithMaps );
  47513. array.push( parameters.numLightProbes );
  47514. array.push( parameters.shadowMapType );
  47515. array.push( parameters.toneMapping );
  47516. array.push( parameters.numClippingPlanes );
  47517. array.push( parameters.numClipIntersection );
  47518. array.push( parameters.depthPacking );
  47519. }
  47520. function getProgramCacheKeyBooleans( array, parameters ) {
  47521. _programLayers.disableAll();
  47522. if ( parameters.instancing )
  47523. _programLayers.enable( 0 );
  47524. if ( parameters.instancingColor )
  47525. _programLayers.enable( 1 );
  47526. if ( parameters.instancingMorph )
  47527. _programLayers.enable( 2 );
  47528. if ( parameters.matcap )
  47529. _programLayers.enable( 3 );
  47530. if ( parameters.envMap )
  47531. _programLayers.enable( 4 );
  47532. if ( parameters.normalMapObjectSpace )
  47533. _programLayers.enable( 5 );
  47534. if ( parameters.normalMapTangentSpace )
  47535. _programLayers.enable( 6 );
  47536. if ( parameters.clearcoat )
  47537. _programLayers.enable( 7 );
  47538. if ( parameters.iridescence )
  47539. _programLayers.enable( 8 );
  47540. if ( parameters.alphaTest )
  47541. _programLayers.enable( 9 );
  47542. if ( parameters.vertexColors )
  47543. _programLayers.enable( 10 );
  47544. if ( parameters.vertexAlphas )
  47545. _programLayers.enable( 11 );
  47546. if ( parameters.vertexUv1s )
  47547. _programLayers.enable( 12 );
  47548. if ( parameters.vertexUv2s )
  47549. _programLayers.enable( 13 );
  47550. if ( parameters.vertexUv3s )
  47551. _programLayers.enable( 14 );
  47552. if ( parameters.vertexTangents )
  47553. _programLayers.enable( 15 );
  47554. if ( parameters.anisotropy )
  47555. _programLayers.enable( 16 );
  47556. if ( parameters.alphaHash )
  47557. _programLayers.enable( 17 );
  47558. if ( parameters.batching )
  47559. _programLayers.enable( 18 );
  47560. if ( parameters.dispersion )
  47561. _programLayers.enable( 19 );
  47562. if ( parameters.batchingColor )
  47563. _programLayers.enable( 20 );
  47564. if ( parameters.gradientMap )
  47565. _programLayers.enable( 21 );
  47566. array.push( _programLayers.mask );
  47567. _programLayers.disableAll();
  47568. if ( parameters.fog )
  47569. _programLayers.enable( 0 );
  47570. if ( parameters.useFog )
  47571. _programLayers.enable( 1 );
  47572. if ( parameters.flatShading )
  47573. _programLayers.enable( 2 );
  47574. if ( parameters.logarithmicDepthBuffer )
  47575. _programLayers.enable( 3 );
  47576. if ( parameters.reversedDepthBuffer )
  47577. _programLayers.enable( 4 );
  47578. if ( parameters.skinning )
  47579. _programLayers.enable( 5 );
  47580. if ( parameters.morphTargets )
  47581. _programLayers.enable( 6 );
  47582. if ( parameters.morphNormals )
  47583. _programLayers.enable( 7 );
  47584. if ( parameters.morphColors )
  47585. _programLayers.enable( 8 );
  47586. if ( parameters.premultipliedAlpha )
  47587. _programLayers.enable( 9 );
  47588. if ( parameters.shadowMapEnabled )
  47589. _programLayers.enable( 10 );
  47590. if ( parameters.doubleSided )
  47591. _programLayers.enable( 11 );
  47592. if ( parameters.flipSided )
  47593. _programLayers.enable( 12 );
  47594. if ( parameters.useDepthPacking )
  47595. _programLayers.enable( 13 );
  47596. if ( parameters.dithering )
  47597. _programLayers.enable( 14 );
  47598. if ( parameters.transmission )
  47599. _programLayers.enable( 15 );
  47600. if ( parameters.sheen )
  47601. _programLayers.enable( 16 );
  47602. if ( parameters.opaque )
  47603. _programLayers.enable( 17 );
  47604. if ( parameters.pointsUvs )
  47605. _programLayers.enable( 18 );
  47606. if ( parameters.decodeVideoTexture )
  47607. _programLayers.enable( 19 );
  47608. if ( parameters.decodeVideoTextureEmissive )
  47609. _programLayers.enable( 20 );
  47610. if ( parameters.alphaToCoverage )
  47611. _programLayers.enable( 21 );
  47612. array.push( _programLayers.mask );
  47613. }
  47614. function getUniforms( material ) {
  47615. const shaderID = shaderIDs[ material.type ];
  47616. let uniforms;
  47617. if ( shaderID ) {
  47618. const shader = ShaderLib[ shaderID ];
  47619. uniforms = UniformsUtils.clone( shader.uniforms );
  47620. } else {
  47621. uniforms = material.uniforms;
  47622. }
  47623. return uniforms;
  47624. }
  47625. function acquireProgram( parameters, cacheKey ) {
  47626. let program = programsMap.get( cacheKey );
  47627. if ( program !== undefined ) {
  47628. ++ program.usedTimes;
  47629. } else {
  47630. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47631. programs.push( program );
  47632. programsMap.set( cacheKey, program );
  47633. }
  47634. return program;
  47635. }
  47636. function releaseProgram( program ) {
  47637. if ( -- program.usedTimes === 0 ) {
  47638. // Remove from unordered set
  47639. const i = programs.indexOf( program );
  47640. programs[ i ] = programs[ programs.length - 1 ];
  47641. programs.pop();
  47642. // Remove from map
  47643. programsMap.delete( program.cacheKey );
  47644. // Free WebGL resources
  47645. program.destroy();
  47646. }
  47647. }
  47648. function releaseShaderCache( material ) {
  47649. _customShaders.remove( material );
  47650. }
  47651. function dispose() {
  47652. _customShaders.dispose();
  47653. }
  47654. return {
  47655. getParameters: getParameters,
  47656. getProgramCacheKey: getProgramCacheKey,
  47657. getUniforms: getUniforms,
  47658. acquireProgram: acquireProgram,
  47659. releaseProgram: releaseProgram,
  47660. releaseShaderCache: releaseShaderCache,
  47661. // Exposed for resource monitoring & error feedback via renderer.info:
  47662. programs: programs,
  47663. dispose: dispose
  47664. };
  47665. }
  47666. function WebGLProperties() {
  47667. let properties = new WeakMap();
  47668. function has( object ) {
  47669. return properties.has( object );
  47670. }
  47671. function get( object ) {
  47672. let map = properties.get( object );
  47673. if ( map === undefined ) {
  47674. map = {};
  47675. properties.set( object, map );
  47676. }
  47677. return map;
  47678. }
  47679. function remove( object ) {
  47680. properties.delete( object );
  47681. }
  47682. function update( object, key, value ) {
  47683. properties.get( object )[ key ] = value;
  47684. }
  47685. function dispose() {
  47686. properties = new WeakMap();
  47687. }
  47688. return {
  47689. has: has,
  47690. get: get,
  47691. remove: remove,
  47692. update: update,
  47693. dispose: dispose
  47694. };
  47695. }
  47696. function painterSortStable( a, b ) {
  47697. if ( a.groupOrder !== b.groupOrder ) {
  47698. return a.groupOrder - b.groupOrder;
  47699. } else if ( a.renderOrder !== b.renderOrder ) {
  47700. return a.renderOrder - b.renderOrder;
  47701. } else if ( a.material.id !== b.material.id ) {
  47702. return a.material.id - b.material.id;
  47703. } else if ( a.z !== b.z ) {
  47704. return a.z - b.z;
  47705. } else {
  47706. return a.id - b.id;
  47707. }
  47708. }
  47709. function reversePainterSortStable( a, b ) {
  47710. if ( a.groupOrder !== b.groupOrder ) {
  47711. return a.groupOrder - b.groupOrder;
  47712. } else if ( a.renderOrder !== b.renderOrder ) {
  47713. return a.renderOrder - b.renderOrder;
  47714. } else if ( a.z !== b.z ) {
  47715. return b.z - a.z;
  47716. } else {
  47717. return a.id - b.id;
  47718. }
  47719. }
  47720. function WebGLRenderList() {
  47721. const renderItems = [];
  47722. let renderItemsIndex = 0;
  47723. const opaque = [];
  47724. const transmissive = [];
  47725. const transparent = [];
  47726. function init() {
  47727. renderItemsIndex = 0;
  47728. opaque.length = 0;
  47729. transmissive.length = 0;
  47730. transparent.length = 0;
  47731. }
  47732. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47733. let renderItem = renderItems[ renderItemsIndex ];
  47734. if ( renderItem === undefined ) {
  47735. renderItem = {
  47736. id: object.id,
  47737. object: object,
  47738. geometry: geometry,
  47739. material: material,
  47740. groupOrder: groupOrder,
  47741. renderOrder: object.renderOrder,
  47742. z: z,
  47743. group: group
  47744. };
  47745. renderItems[ renderItemsIndex ] = renderItem;
  47746. } else {
  47747. renderItem.id = object.id;
  47748. renderItem.object = object;
  47749. renderItem.geometry = geometry;
  47750. renderItem.material = material;
  47751. renderItem.groupOrder = groupOrder;
  47752. renderItem.renderOrder = object.renderOrder;
  47753. renderItem.z = z;
  47754. renderItem.group = group;
  47755. }
  47756. renderItemsIndex ++;
  47757. return renderItem;
  47758. }
  47759. function push( object, geometry, material, groupOrder, z, group ) {
  47760. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47761. if ( material.transmission > 0.0 ) {
  47762. transmissive.push( renderItem );
  47763. } else if ( material.transparent === true ) {
  47764. transparent.push( renderItem );
  47765. } else {
  47766. opaque.push( renderItem );
  47767. }
  47768. }
  47769. function unshift( object, geometry, material, groupOrder, z, group ) {
  47770. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47771. if ( material.transmission > 0.0 ) {
  47772. transmissive.unshift( renderItem );
  47773. } else if ( material.transparent === true ) {
  47774. transparent.unshift( renderItem );
  47775. } else {
  47776. opaque.unshift( renderItem );
  47777. }
  47778. }
  47779. function sort( customOpaqueSort, customTransparentSort ) {
  47780. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47781. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47782. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47783. }
  47784. function finish() {
  47785. // Clear references from inactive renderItems in the list
  47786. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47787. const renderItem = renderItems[ i ];
  47788. if ( renderItem.id === null ) break;
  47789. renderItem.id = null;
  47790. renderItem.object = null;
  47791. renderItem.geometry = null;
  47792. renderItem.material = null;
  47793. renderItem.group = null;
  47794. }
  47795. }
  47796. return {
  47797. opaque: opaque,
  47798. transmissive: transmissive,
  47799. transparent: transparent,
  47800. init: init,
  47801. push: push,
  47802. unshift: unshift,
  47803. finish: finish,
  47804. sort: sort
  47805. };
  47806. }
  47807. function WebGLRenderLists() {
  47808. let lists = new WeakMap();
  47809. function get( scene, renderCallDepth ) {
  47810. const listArray = lists.get( scene );
  47811. let list;
  47812. if ( listArray === undefined ) {
  47813. list = new WebGLRenderList();
  47814. lists.set( scene, [ list ] );
  47815. } else {
  47816. if ( renderCallDepth >= listArray.length ) {
  47817. list = new WebGLRenderList();
  47818. listArray.push( list );
  47819. } else {
  47820. list = listArray[ renderCallDepth ];
  47821. }
  47822. }
  47823. return list;
  47824. }
  47825. function dispose() {
  47826. lists = new WeakMap();
  47827. }
  47828. return {
  47829. get: get,
  47830. dispose: dispose
  47831. };
  47832. }
  47833. function UniformsCache() {
  47834. const lights = {};
  47835. return {
  47836. get: function ( light ) {
  47837. if ( lights[ light.id ] !== undefined ) {
  47838. return lights[ light.id ];
  47839. }
  47840. let uniforms;
  47841. switch ( light.type ) {
  47842. case 'DirectionalLight':
  47843. uniforms = {
  47844. direction: new Vector3(),
  47845. color: new Color()
  47846. };
  47847. break;
  47848. case 'SpotLight':
  47849. uniforms = {
  47850. position: new Vector3(),
  47851. direction: new Vector3(),
  47852. color: new Color(),
  47853. distance: 0,
  47854. coneCos: 0,
  47855. penumbraCos: 0,
  47856. decay: 0
  47857. };
  47858. break;
  47859. case 'PointLight':
  47860. uniforms = {
  47861. position: new Vector3(),
  47862. color: new Color(),
  47863. distance: 0,
  47864. decay: 0
  47865. };
  47866. break;
  47867. case 'HemisphereLight':
  47868. uniforms = {
  47869. direction: new Vector3(),
  47870. skyColor: new Color(),
  47871. groundColor: new Color()
  47872. };
  47873. break;
  47874. case 'RectAreaLight':
  47875. uniforms = {
  47876. color: new Color(),
  47877. position: new Vector3(),
  47878. halfWidth: new Vector3(),
  47879. halfHeight: new Vector3()
  47880. };
  47881. break;
  47882. }
  47883. lights[ light.id ] = uniforms;
  47884. return uniforms;
  47885. }
  47886. };
  47887. }
  47888. function ShadowUniformsCache() {
  47889. const lights = {};
  47890. return {
  47891. get: function ( light ) {
  47892. if ( lights[ light.id ] !== undefined ) {
  47893. return lights[ light.id ];
  47894. }
  47895. let uniforms;
  47896. switch ( light.type ) {
  47897. case 'DirectionalLight':
  47898. uniforms = {
  47899. shadowIntensity: 1,
  47900. shadowBias: 0,
  47901. shadowNormalBias: 0,
  47902. shadowRadius: 1,
  47903. shadowMapSize: new Vector2()
  47904. };
  47905. break;
  47906. case 'SpotLight':
  47907. uniforms = {
  47908. shadowIntensity: 1,
  47909. shadowBias: 0,
  47910. shadowNormalBias: 0,
  47911. shadowRadius: 1,
  47912. shadowMapSize: new Vector2()
  47913. };
  47914. break;
  47915. case 'PointLight':
  47916. uniforms = {
  47917. shadowIntensity: 1,
  47918. shadowBias: 0,
  47919. shadowNormalBias: 0,
  47920. shadowRadius: 1,
  47921. shadowMapSize: new Vector2(),
  47922. shadowCameraNear: 1,
  47923. shadowCameraFar: 1000
  47924. };
  47925. break;
  47926. // TODO (abelnation): set RectAreaLight shadow uniforms
  47927. }
  47928. lights[ light.id ] = uniforms;
  47929. return uniforms;
  47930. }
  47931. };
  47932. }
  47933. let nextVersion = 0;
  47934. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  47935. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  47936. }
  47937. function WebGLLights( extensions ) {
  47938. const cache = new UniformsCache();
  47939. const shadowCache = ShadowUniformsCache();
  47940. const state = {
  47941. version: 0,
  47942. hash: {
  47943. directionalLength: -1,
  47944. pointLength: -1,
  47945. spotLength: -1,
  47946. rectAreaLength: -1,
  47947. hemiLength: -1,
  47948. numDirectionalShadows: -1,
  47949. numPointShadows: -1,
  47950. numSpotShadows: -1,
  47951. numSpotMaps: -1,
  47952. numLightProbes: -1
  47953. },
  47954. ambient: [ 0, 0, 0 ],
  47955. probe: [],
  47956. directional: [],
  47957. directionalShadow: [],
  47958. directionalShadowMap: [],
  47959. directionalShadowMatrix: [],
  47960. spot: [],
  47961. spotLightMap: [],
  47962. spotShadow: [],
  47963. spotShadowMap: [],
  47964. spotLightMatrix: [],
  47965. rectArea: [],
  47966. rectAreaLTC1: null,
  47967. rectAreaLTC2: null,
  47968. point: [],
  47969. pointShadow: [],
  47970. pointShadowMap: [],
  47971. pointShadowMatrix: [],
  47972. hemi: [],
  47973. numSpotLightShadowsWithMaps: 0,
  47974. numLightProbes: 0
  47975. };
  47976. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  47977. const vector3 = new Vector3();
  47978. const matrix4 = new Matrix4();
  47979. const matrix42 = new Matrix4();
  47980. function setup( lights ) {
  47981. let r = 0, g = 0, b = 0;
  47982. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  47983. let directionalLength = 0;
  47984. let pointLength = 0;
  47985. let spotLength = 0;
  47986. let rectAreaLength = 0;
  47987. let hemiLength = 0;
  47988. let numDirectionalShadows = 0;
  47989. let numPointShadows = 0;
  47990. let numSpotShadows = 0;
  47991. let numSpotMaps = 0;
  47992. let numSpotShadowsWithMaps = 0;
  47993. let numLightProbes = 0;
  47994. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  47995. lights.sort( shadowCastingAndTexturingLightsFirst );
  47996. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47997. const light = lights[ i ];
  47998. const color = light.color;
  47999. const intensity = light.intensity;
  48000. const distance = light.distance;
  48001. let shadowMap = null;
  48002. if ( light.shadow && light.shadow.map ) {
  48003. if ( light.shadow.map.texture.format === RGFormat ) {
  48004. // VSM uses color texture with blurred mean/std_dev
  48005. shadowMap = light.shadow.map.texture;
  48006. } else {
  48007. // Other types use depth texture
  48008. shadowMap = light.shadow.map.depthTexture || light.shadow.map.texture;
  48009. }
  48010. }
  48011. if ( light.isAmbientLight ) {
  48012. r += color.r * intensity;
  48013. g += color.g * intensity;
  48014. b += color.b * intensity;
  48015. } else if ( light.isLightProbe ) {
  48016. for ( let j = 0; j < 9; j ++ ) {
  48017. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  48018. }
  48019. numLightProbes ++;
  48020. } else if ( light.isDirectionalLight ) {
  48021. const uniforms = cache.get( light );
  48022. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48023. if ( light.castShadow ) {
  48024. const shadow = light.shadow;
  48025. const shadowUniforms = shadowCache.get( light );
  48026. shadowUniforms.shadowIntensity = shadow.intensity;
  48027. shadowUniforms.shadowBias = shadow.bias;
  48028. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48029. shadowUniforms.shadowRadius = shadow.radius;
  48030. shadowUniforms.shadowMapSize = shadow.mapSize;
  48031. state.directionalShadow[ directionalLength ] = shadowUniforms;
  48032. state.directionalShadowMap[ directionalLength ] = shadowMap;
  48033. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  48034. numDirectionalShadows ++;
  48035. }
  48036. state.directional[ directionalLength ] = uniforms;
  48037. directionalLength ++;
  48038. } else if ( light.isSpotLight ) {
  48039. const uniforms = cache.get( light );
  48040. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48041. uniforms.color.copy( color ).multiplyScalar( intensity );
  48042. uniforms.distance = distance;
  48043. uniforms.coneCos = Math.cos( light.angle );
  48044. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  48045. uniforms.decay = light.decay;
  48046. state.spot[ spotLength ] = uniforms;
  48047. const shadow = light.shadow;
  48048. if ( light.map ) {
  48049. state.spotLightMap[ numSpotMaps ] = light.map;
  48050. numSpotMaps ++;
  48051. // make sure the lightMatrix is up to date
  48052. // TODO : do it if required only
  48053. shadow.updateMatrices( light );
  48054. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  48055. }
  48056. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  48057. if ( light.castShadow ) {
  48058. const shadowUniforms = shadowCache.get( light );
  48059. shadowUniforms.shadowIntensity = shadow.intensity;
  48060. shadowUniforms.shadowBias = shadow.bias;
  48061. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48062. shadowUniforms.shadowRadius = shadow.radius;
  48063. shadowUniforms.shadowMapSize = shadow.mapSize;
  48064. state.spotShadow[ spotLength ] = shadowUniforms;
  48065. state.spotShadowMap[ spotLength ] = shadowMap;
  48066. numSpotShadows ++;
  48067. }
  48068. spotLength ++;
  48069. } else if ( light.isRectAreaLight ) {
  48070. const uniforms = cache.get( light );
  48071. uniforms.color.copy( color ).multiplyScalar( intensity );
  48072. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48073. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48074. state.rectArea[ rectAreaLength ] = uniforms;
  48075. rectAreaLength ++;
  48076. } else if ( light.isPointLight ) {
  48077. const uniforms = cache.get( light );
  48078. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  48079. uniforms.distance = light.distance;
  48080. uniforms.decay = light.decay;
  48081. if ( light.castShadow ) {
  48082. const shadow = light.shadow;
  48083. const shadowUniforms = shadowCache.get( light );
  48084. shadowUniforms.shadowIntensity = shadow.intensity;
  48085. shadowUniforms.shadowBias = shadow.bias;
  48086. shadowUniforms.shadowNormalBias = shadow.normalBias;
  48087. shadowUniforms.shadowRadius = shadow.radius;
  48088. shadowUniforms.shadowMapSize = shadow.mapSize;
  48089. shadowUniforms.shadowCameraNear = shadow.camera.near;
  48090. shadowUniforms.shadowCameraFar = shadow.camera.far;
  48091. state.pointShadow[ pointLength ] = shadowUniforms;
  48092. state.pointShadowMap[ pointLength ] = shadowMap;
  48093. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  48094. numPointShadows ++;
  48095. }
  48096. state.point[ pointLength ] = uniforms;
  48097. pointLength ++;
  48098. } else if ( light.isHemisphereLight ) {
  48099. const uniforms = cache.get( light );
  48100. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  48101. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  48102. state.hemi[ hemiLength ] = uniforms;
  48103. hemiLength ++;
  48104. }
  48105. }
  48106. if ( rectAreaLength > 0 ) {
  48107. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  48108. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  48109. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  48110. } else {
  48111. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  48112. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  48113. }
  48114. }
  48115. state.ambient[ 0 ] = r;
  48116. state.ambient[ 1 ] = g;
  48117. state.ambient[ 2 ] = b;
  48118. const hash = state.hash;
  48119. if ( hash.directionalLength !== directionalLength ||
  48120. hash.pointLength !== pointLength ||
  48121. hash.spotLength !== spotLength ||
  48122. hash.rectAreaLength !== rectAreaLength ||
  48123. hash.hemiLength !== hemiLength ||
  48124. hash.numDirectionalShadows !== numDirectionalShadows ||
  48125. hash.numPointShadows !== numPointShadows ||
  48126. hash.numSpotShadows !== numSpotShadows ||
  48127. hash.numSpotMaps !== numSpotMaps ||
  48128. hash.numLightProbes !== numLightProbes ) {
  48129. state.directional.length = directionalLength;
  48130. state.spot.length = spotLength;
  48131. state.rectArea.length = rectAreaLength;
  48132. state.point.length = pointLength;
  48133. state.hemi.length = hemiLength;
  48134. state.directionalShadow.length = numDirectionalShadows;
  48135. state.directionalShadowMap.length = numDirectionalShadows;
  48136. state.pointShadow.length = numPointShadows;
  48137. state.pointShadowMap.length = numPointShadows;
  48138. state.spotShadow.length = numSpotShadows;
  48139. state.spotShadowMap.length = numSpotShadows;
  48140. state.directionalShadowMatrix.length = numDirectionalShadows;
  48141. state.pointShadowMatrix.length = numPointShadows;
  48142. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  48143. state.spotLightMap.length = numSpotMaps;
  48144. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  48145. state.numLightProbes = numLightProbes;
  48146. hash.directionalLength = directionalLength;
  48147. hash.pointLength = pointLength;
  48148. hash.spotLength = spotLength;
  48149. hash.rectAreaLength = rectAreaLength;
  48150. hash.hemiLength = hemiLength;
  48151. hash.numDirectionalShadows = numDirectionalShadows;
  48152. hash.numPointShadows = numPointShadows;
  48153. hash.numSpotShadows = numSpotShadows;
  48154. hash.numSpotMaps = numSpotMaps;
  48155. hash.numLightProbes = numLightProbes;
  48156. state.version = nextVersion ++;
  48157. }
  48158. }
  48159. function setupView( lights, camera ) {
  48160. let directionalLength = 0;
  48161. let pointLength = 0;
  48162. let spotLength = 0;
  48163. let rectAreaLength = 0;
  48164. let hemiLength = 0;
  48165. const viewMatrix = camera.matrixWorldInverse;
  48166. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48167. const light = lights[ i ];
  48168. if ( light.isDirectionalLight ) {
  48169. const uniforms = state.directional[ directionalLength ];
  48170. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48171. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48172. uniforms.direction.sub( vector3 );
  48173. uniforms.direction.transformDirection( viewMatrix );
  48174. directionalLength ++;
  48175. } else if ( light.isSpotLight ) {
  48176. const uniforms = state.spot[ spotLength ];
  48177. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48178. uniforms.position.applyMatrix4( viewMatrix );
  48179. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48180. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48181. uniforms.direction.sub( vector3 );
  48182. uniforms.direction.transformDirection( viewMatrix );
  48183. spotLength ++;
  48184. } else if ( light.isRectAreaLight ) {
  48185. const uniforms = state.rectArea[ rectAreaLength ];
  48186. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48187. uniforms.position.applyMatrix4( viewMatrix );
  48188. // extract local rotation of light to derive width/height half vectors
  48189. matrix42.identity();
  48190. matrix4.copy( light.matrixWorld );
  48191. matrix4.premultiply( viewMatrix );
  48192. matrix42.extractRotation( matrix4 );
  48193. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48194. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48195. uniforms.halfWidth.applyMatrix4( matrix42 );
  48196. uniforms.halfHeight.applyMatrix4( matrix42 );
  48197. rectAreaLength ++;
  48198. } else if ( light.isPointLight ) {
  48199. const uniforms = state.point[ pointLength ];
  48200. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48201. uniforms.position.applyMatrix4( viewMatrix );
  48202. pointLength ++;
  48203. } else if ( light.isHemisphereLight ) {
  48204. const uniforms = state.hemi[ hemiLength ];
  48205. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48206. uniforms.direction.transformDirection( viewMatrix );
  48207. hemiLength ++;
  48208. }
  48209. }
  48210. }
  48211. return {
  48212. setup: setup,
  48213. setupView: setupView,
  48214. state: state
  48215. };
  48216. }
  48217. function WebGLRenderState( extensions ) {
  48218. const lights = new WebGLLights( extensions );
  48219. const lightsArray = [];
  48220. const shadowsArray = [];
  48221. function init( camera ) {
  48222. state.camera = camera;
  48223. lightsArray.length = 0;
  48224. shadowsArray.length = 0;
  48225. }
  48226. function pushLight( light ) {
  48227. lightsArray.push( light );
  48228. }
  48229. function pushShadow( shadowLight ) {
  48230. shadowsArray.push( shadowLight );
  48231. }
  48232. function setupLights() {
  48233. lights.setup( lightsArray );
  48234. }
  48235. function setupLightsView( camera ) {
  48236. lights.setupView( lightsArray, camera );
  48237. }
  48238. const state = {
  48239. lightsArray: lightsArray,
  48240. shadowsArray: shadowsArray,
  48241. camera: null,
  48242. lights: lights,
  48243. transmissionRenderTarget: {}
  48244. };
  48245. return {
  48246. init: init,
  48247. state: state,
  48248. setupLights: setupLights,
  48249. setupLightsView: setupLightsView,
  48250. pushLight: pushLight,
  48251. pushShadow: pushShadow
  48252. };
  48253. }
  48254. function WebGLRenderStates( extensions ) {
  48255. let renderStates = new WeakMap();
  48256. function get( scene, renderCallDepth = 0 ) {
  48257. const renderStateArray = renderStates.get( scene );
  48258. let renderState;
  48259. if ( renderStateArray === undefined ) {
  48260. renderState = new WebGLRenderState( extensions );
  48261. renderStates.set( scene, [ renderState ] );
  48262. } else {
  48263. if ( renderCallDepth >= renderStateArray.length ) {
  48264. renderState = new WebGLRenderState( extensions );
  48265. renderStateArray.push( renderState );
  48266. } else {
  48267. renderState = renderStateArray[ renderCallDepth ];
  48268. }
  48269. }
  48270. return renderState;
  48271. }
  48272. function dispose() {
  48273. renderStates = new WeakMap();
  48274. }
  48275. return {
  48276. get: get,
  48277. dispose: dispose
  48278. };
  48279. }
  48280. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  48281. const fragment = "uniform sampler2D shadow_pass;\nuniform vec2 resolution;\nuniform float radius;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg;\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 = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r;\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( max( 0.0, squared_mean - mean * mean ) );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}";
  48282. const _cubeDirections = [
  48283. /*@__PURE__*/ new Vector3( 1, 0, 0 ), /*@__PURE__*/ new Vector3( -1, 0, 0 ), /*@__PURE__*/ new Vector3( 0, 1, 0 ),
  48284. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ), /*@__PURE__*/ new Vector3( 0, 0, -1 )
  48285. ];
  48286. const _cubeUps = [
  48287. /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, 0, 1 ),
  48288. /*@__PURE__*/ new Vector3( 0, 0, -1 ), /*@__PURE__*/ new Vector3( 0, -1, 0 ), /*@__PURE__*/ new Vector3( 0, -1, 0 )
  48289. ];
  48290. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  48291. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  48292. const _lookTarget = /*@__PURE__*/ new Vector3();
  48293. function WebGLShadowMap( renderer, objects, capabilities ) {
  48294. let _frustum = new Frustum();
  48295. const _shadowMapSize = new Vector2(),
  48296. _viewportSize = new Vector2(),
  48297. _viewport = new Vector4(),
  48298. _depthMaterial = new MeshDepthMaterial(),
  48299. _distanceMaterial = new MeshDistanceMaterial(),
  48300. _materialCache = {},
  48301. _maxTextureSize = capabilities.maxTextureSize;
  48302. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  48303. const shadowMaterialVertical = new ShaderMaterial( {
  48304. defines: {
  48305. VSM_SAMPLES: 8
  48306. },
  48307. uniforms: {
  48308. shadow_pass: { value: null },
  48309. resolution: { value: new Vector2() },
  48310. radius: { value: 4.0 }
  48311. },
  48312. vertexShader: vertex,
  48313. fragmentShader: fragment
  48314. } );
  48315. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  48316. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  48317. const fullScreenTri = new BufferGeometry();
  48318. fullScreenTri.setAttribute(
  48319. 'position',
  48320. new BufferAttribute(
  48321. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  48322. 3
  48323. )
  48324. );
  48325. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  48326. const scope = this;
  48327. this.enabled = false;
  48328. this.autoUpdate = true;
  48329. this.needsUpdate = false;
  48330. this.type = PCFShadowMap;
  48331. let _previousType = this.type;
  48332. this.render = function ( lights, scene, camera ) {
  48333. if ( scope.enabled === false ) return;
  48334. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  48335. if ( lights.length === 0 ) return;
  48336. if ( lights.type === PCFSoftShadowMap ) {
  48337. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  48338. lights.type = PCFShadowMap;
  48339. }
  48340. const currentRenderTarget = renderer.getRenderTarget();
  48341. const activeCubeFace = renderer.getActiveCubeFace();
  48342. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  48343. const _state = renderer.state;
  48344. // Set GL state for depth map.
  48345. _state.setBlending( NoBlending );
  48346. if ( _state.buffers.depth.getReversed() === true ) {
  48347. _state.buffers.color.setClear( 0, 0, 0, 0 );
  48348. } else {
  48349. _state.buffers.color.setClear( 1, 1, 1, 1 );
  48350. }
  48351. _state.buffers.depth.setTest( true );
  48352. _state.setScissorTest( false );
  48353. // check for shadow map type changes
  48354. const typeChanged = _previousType !== this.type;
  48355. // When shadow map type changes, materials need recompilation because sampler types change
  48356. // (sampler2DShadow for PCF vs sampler2D for Basic)
  48357. if ( typeChanged ) {
  48358. scene.traverse( function ( object ) {
  48359. if ( object.material ) {
  48360. if ( Array.isArray( object.material ) ) {
  48361. object.material.forEach( mat => mat.needsUpdate = true );
  48362. } else {
  48363. object.material.needsUpdate = true;
  48364. }
  48365. }
  48366. } );
  48367. }
  48368. // render depth map
  48369. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  48370. const light = lights[ i ];
  48371. const shadow = light.shadow;
  48372. if ( shadow === undefined ) {
  48373. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  48374. continue;
  48375. }
  48376. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  48377. _shadowMapSize.copy( shadow.mapSize );
  48378. const shadowFrameExtents = shadow.getFrameExtents();
  48379. _shadowMapSize.multiply( shadowFrameExtents );
  48380. _viewportSize.copy( shadow.mapSize );
  48381. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  48382. if ( _shadowMapSize.x > _maxTextureSize ) {
  48383. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  48384. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  48385. shadow.mapSize.x = _viewportSize.x;
  48386. }
  48387. if ( _shadowMapSize.y > _maxTextureSize ) {
  48388. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  48389. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  48390. shadow.mapSize.y = _viewportSize.y;
  48391. }
  48392. }
  48393. if ( shadow.map === null || typeChanged === true ) {
  48394. if ( shadow.map !== null ) {
  48395. if ( shadow.map.depthTexture !== null ) {
  48396. shadow.map.depthTexture.dispose();
  48397. shadow.map.depthTexture = null;
  48398. }
  48399. shadow.map.dispose();
  48400. }
  48401. if ( this.type === VSMShadowMap ) {
  48402. if ( light.isPointLight ) {
  48403. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  48404. continue;
  48405. }
  48406. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48407. format: RGFormat,
  48408. type: HalfFloatType,
  48409. minFilter: LinearFilter,
  48410. magFilter: LinearFilter,
  48411. generateMipmaps: false
  48412. } );
  48413. shadow.map.texture.name = light.name + '.shadowMap';
  48414. // Native depth texture for VSM - depth is captured here, then blurred into the color texture
  48415. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, FloatType );
  48416. shadow.map.depthTexture.name = light.name + '.shadowMapDepth';
  48417. shadow.map.depthTexture.format = DepthFormat;
  48418. shadow.map.depthTexture.compareFunction = null; // For regular sampling (not shadow comparison)
  48419. shadow.map.depthTexture.minFilter = NearestFilter;
  48420. shadow.map.depthTexture.magFilter = NearestFilter;
  48421. } else {
  48422. if ( light.isPointLight ) {
  48423. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  48424. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  48425. } else {
  48426. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  48427. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  48428. }
  48429. shadow.map.depthTexture.name = light.name + '.shadowMap';
  48430. shadow.map.depthTexture.format = DepthFormat;
  48431. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  48432. if ( this.type === PCFShadowMap ) {
  48433. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  48434. shadow.map.depthTexture.minFilter = LinearFilter;
  48435. shadow.map.depthTexture.magFilter = LinearFilter;
  48436. } else {
  48437. shadow.map.depthTexture.compareFunction = null;
  48438. shadow.map.depthTexture.minFilter = NearestFilter;
  48439. shadow.map.depthTexture.magFilter = NearestFilter;
  48440. }
  48441. }
  48442. shadow.camera.updateProjectionMatrix();
  48443. }
  48444. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  48445. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  48446. for ( let face = 0; face < faceCount; face ++ ) {
  48447. // For cube render targets, render to each face separately
  48448. if ( shadow.map.isWebGLCubeRenderTarget ) {
  48449. renderer.setRenderTarget( shadow.map, face );
  48450. renderer.clear();
  48451. } else {
  48452. // For 2D render targets, use viewports
  48453. if ( face === 0 ) {
  48454. renderer.setRenderTarget( shadow.map );
  48455. renderer.clear();
  48456. }
  48457. const viewport = shadow.getViewport( face );
  48458. _viewport.set(
  48459. _viewportSize.x * viewport.x,
  48460. _viewportSize.y * viewport.y,
  48461. _viewportSize.x * viewport.z,
  48462. _viewportSize.y * viewport.w
  48463. );
  48464. _state.viewport( _viewport );
  48465. }
  48466. if ( light.isPointLight ) {
  48467. const camera = shadow.camera;
  48468. const shadowMatrix = shadow.matrix;
  48469. const far = light.distance || camera.far;
  48470. if ( far !== camera.far ) {
  48471. camera.far = far;
  48472. camera.updateProjectionMatrix();
  48473. }
  48474. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  48475. camera.position.copy( _lightPositionWorld );
  48476. _lookTarget.copy( camera.position );
  48477. _lookTarget.add( _cubeDirections[ face ] );
  48478. camera.up.copy( _cubeUps[ face ] );
  48479. camera.lookAt( _lookTarget );
  48480. camera.updateMatrixWorld();
  48481. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  48482. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  48483. shadow._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  48484. } else {
  48485. shadow.updateMatrices( light );
  48486. }
  48487. _frustum = shadow.getFrustum();
  48488. renderObject( scene, camera, shadow.camera, light, this.type );
  48489. }
  48490. // do blur pass for VSM
  48491. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  48492. VSMPass( shadow, camera );
  48493. }
  48494. shadow.needsUpdate = false;
  48495. }
  48496. _previousType = this.type;
  48497. scope.needsUpdate = false;
  48498. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  48499. };
  48500. function VSMPass( shadow, camera ) {
  48501. const geometry = objects.update( fullScreenMesh );
  48502. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  48503. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  48504. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  48505. shadowMaterialVertical.needsUpdate = true;
  48506. shadowMaterialHorizontal.needsUpdate = true;
  48507. }
  48508. if ( shadow.mapPass === null ) {
  48509. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48510. format: RGFormat,
  48511. type: HalfFloatType
  48512. } );
  48513. }
  48514. // vertical pass - read from native depth texture
  48515. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.depthTexture;
  48516. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  48517. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  48518. renderer.setRenderTarget( shadow.mapPass );
  48519. renderer.clear();
  48520. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  48521. // horizontal pass
  48522. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  48523. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  48524. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  48525. renderer.setRenderTarget( shadow.map );
  48526. renderer.clear();
  48527. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  48528. }
  48529. function getDepthMaterial( object, material, light, type ) {
  48530. let result = null;
  48531. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  48532. if ( customMaterial !== undefined ) {
  48533. result = customMaterial;
  48534. } else {
  48535. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  48536. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  48537. ( material.displacementMap && material.displacementScale !== 0 ) ||
  48538. ( material.alphaMap && material.alphaTest > 0 ) ||
  48539. ( material.map && material.alphaTest > 0 ) ||
  48540. ( material.alphaToCoverage === true ) ) {
  48541. // in this case we need a unique material instance reflecting the
  48542. // appropriate state
  48543. const keyA = result.uuid, keyB = material.uuid;
  48544. let materialsForVariant = _materialCache[ keyA ];
  48545. if ( materialsForVariant === undefined ) {
  48546. materialsForVariant = {};
  48547. _materialCache[ keyA ] = materialsForVariant;
  48548. }
  48549. let cachedMaterial = materialsForVariant[ keyB ];
  48550. if ( cachedMaterial === undefined ) {
  48551. cachedMaterial = result.clone();
  48552. materialsForVariant[ keyB ] = cachedMaterial;
  48553. material.addEventListener( 'dispose', onMaterialDispose );
  48554. }
  48555. result = cachedMaterial;
  48556. }
  48557. }
  48558. result.visible = material.visible;
  48559. result.wireframe = material.wireframe;
  48560. if ( type === VSMShadowMap ) {
  48561. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  48562. } else {
  48563. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  48564. }
  48565. result.alphaMap = material.alphaMap;
  48566. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  48567. result.map = material.map;
  48568. result.clipShadows = material.clipShadows;
  48569. result.clippingPlanes = material.clippingPlanes;
  48570. result.clipIntersection = material.clipIntersection;
  48571. result.displacementMap = material.displacementMap;
  48572. result.displacementScale = material.displacementScale;
  48573. result.displacementBias = material.displacementBias;
  48574. result.wireframeLinewidth = material.wireframeLinewidth;
  48575. result.linewidth = material.linewidth;
  48576. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  48577. const materialProperties = renderer.properties.get( result );
  48578. materialProperties.light = light;
  48579. }
  48580. return result;
  48581. }
  48582. function renderObject( object, camera, shadowCamera, light, type ) {
  48583. if ( object.visible === false ) return;
  48584. const visible = object.layers.test( camera.layers );
  48585. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  48586. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  48587. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  48588. const geometry = objects.update( object );
  48589. const material = object.material;
  48590. if ( Array.isArray( material ) ) {
  48591. const groups = geometry.groups;
  48592. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  48593. const group = groups[ k ];
  48594. const groupMaterial = material[ group.materialIndex ];
  48595. if ( groupMaterial && groupMaterial.visible ) {
  48596. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  48597. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48598. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  48599. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48600. }
  48601. }
  48602. } else if ( material.visible ) {
  48603. const depthMaterial = getDepthMaterial( object, material, light, type );
  48604. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48605. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  48606. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48607. }
  48608. }
  48609. }
  48610. const children = object.children;
  48611. for ( let i = 0, l = children.length; i < l; i ++ ) {
  48612. renderObject( children[ i ], camera, shadowCamera, light, type );
  48613. }
  48614. }
  48615. function onMaterialDispose( event ) {
  48616. const material = event.target;
  48617. material.removeEventListener( 'dispose', onMaterialDispose );
  48618. // make sure to remove the unique distance/depth materials used for shadow map rendering
  48619. for ( const id in _materialCache ) {
  48620. const cache = _materialCache[ id ];
  48621. const uuid = event.target.uuid;
  48622. if ( uuid in cache ) {
  48623. const shadowMaterial = cache[ uuid ];
  48624. shadowMaterial.dispose();
  48625. delete cache[ uuid ];
  48626. }
  48627. }
  48628. }
  48629. }
  48630. const reversedFuncs = {
  48631. [ NeverDepth ]: AlwaysDepth,
  48632. [ LessDepth ]: GreaterDepth,
  48633. [ EqualDepth ]: NotEqualDepth,
  48634. [ LessEqualDepth ]: GreaterEqualDepth,
  48635. [ AlwaysDepth ]: NeverDepth,
  48636. [ GreaterDepth ]: LessDepth,
  48637. [ NotEqualDepth ]: EqualDepth,
  48638. [ GreaterEqualDepth ]: LessEqualDepth,
  48639. };
  48640. function WebGLState( gl, extensions ) {
  48641. function ColorBuffer() {
  48642. let locked = false;
  48643. const color = new Vector4();
  48644. let currentColorMask = null;
  48645. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48646. return {
  48647. setMask: function ( colorMask ) {
  48648. if ( currentColorMask !== colorMask && ! locked ) {
  48649. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48650. currentColorMask = colorMask;
  48651. }
  48652. },
  48653. setLocked: function ( lock ) {
  48654. locked = lock;
  48655. },
  48656. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48657. if ( premultipliedAlpha === true ) {
  48658. r *= a; g *= a; b *= a;
  48659. }
  48660. color.set( r, g, b, a );
  48661. if ( currentColorClear.equals( color ) === false ) {
  48662. gl.clearColor( r, g, b, a );
  48663. currentColorClear.copy( color );
  48664. }
  48665. },
  48666. reset: function () {
  48667. locked = false;
  48668. currentColorMask = null;
  48669. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48670. }
  48671. };
  48672. }
  48673. function DepthBuffer() {
  48674. let locked = false;
  48675. let currentReversed = false;
  48676. let currentDepthMask = null;
  48677. let currentDepthFunc = null;
  48678. let currentDepthClear = null;
  48679. return {
  48680. setReversed: function ( reversed ) {
  48681. if ( currentReversed !== reversed ) {
  48682. const ext = extensions.get( 'EXT_clip_control' );
  48683. if ( reversed ) {
  48684. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48685. } else {
  48686. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48687. }
  48688. currentReversed = reversed;
  48689. const oldDepth = currentDepthClear;
  48690. currentDepthClear = null;
  48691. this.setClear( oldDepth );
  48692. }
  48693. },
  48694. getReversed: function () {
  48695. return currentReversed;
  48696. },
  48697. setTest: function ( depthTest ) {
  48698. if ( depthTest ) {
  48699. enable( gl.DEPTH_TEST );
  48700. } else {
  48701. disable( gl.DEPTH_TEST );
  48702. }
  48703. },
  48704. setMask: function ( depthMask ) {
  48705. if ( currentDepthMask !== depthMask && ! locked ) {
  48706. gl.depthMask( depthMask );
  48707. currentDepthMask = depthMask;
  48708. }
  48709. },
  48710. setFunc: function ( depthFunc ) {
  48711. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48712. if ( currentDepthFunc !== depthFunc ) {
  48713. switch ( depthFunc ) {
  48714. case NeverDepth:
  48715. gl.depthFunc( gl.NEVER );
  48716. break;
  48717. case AlwaysDepth:
  48718. gl.depthFunc( gl.ALWAYS );
  48719. break;
  48720. case LessDepth:
  48721. gl.depthFunc( gl.LESS );
  48722. break;
  48723. case LessEqualDepth:
  48724. gl.depthFunc( gl.LEQUAL );
  48725. break;
  48726. case EqualDepth:
  48727. gl.depthFunc( gl.EQUAL );
  48728. break;
  48729. case GreaterEqualDepth:
  48730. gl.depthFunc( gl.GEQUAL );
  48731. break;
  48732. case GreaterDepth:
  48733. gl.depthFunc( gl.GREATER );
  48734. break;
  48735. case NotEqualDepth:
  48736. gl.depthFunc( gl.NOTEQUAL );
  48737. break;
  48738. default:
  48739. gl.depthFunc( gl.LEQUAL );
  48740. }
  48741. currentDepthFunc = depthFunc;
  48742. }
  48743. },
  48744. setLocked: function ( lock ) {
  48745. locked = lock;
  48746. },
  48747. setClear: function ( depth ) {
  48748. if ( currentDepthClear !== depth ) {
  48749. if ( currentReversed ) {
  48750. depth = 1 - depth;
  48751. }
  48752. gl.clearDepth( depth );
  48753. currentDepthClear = depth;
  48754. }
  48755. },
  48756. reset: function () {
  48757. locked = false;
  48758. currentDepthMask = null;
  48759. currentDepthFunc = null;
  48760. currentDepthClear = null;
  48761. currentReversed = false;
  48762. }
  48763. };
  48764. }
  48765. function StencilBuffer() {
  48766. let locked = false;
  48767. let currentStencilMask = null;
  48768. let currentStencilFunc = null;
  48769. let currentStencilRef = null;
  48770. let currentStencilFuncMask = null;
  48771. let currentStencilFail = null;
  48772. let currentStencilZFail = null;
  48773. let currentStencilZPass = null;
  48774. let currentStencilClear = null;
  48775. return {
  48776. setTest: function ( stencilTest ) {
  48777. if ( ! locked ) {
  48778. if ( stencilTest ) {
  48779. enable( gl.STENCIL_TEST );
  48780. } else {
  48781. disable( gl.STENCIL_TEST );
  48782. }
  48783. }
  48784. },
  48785. setMask: function ( stencilMask ) {
  48786. if ( currentStencilMask !== stencilMask && ! locked ) {
  48787. gl.stencilMask( stencilMask );
  48788. currentStencilMask = stencilMask;
  48789. }
  48790. },
  48791. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48792. if ( currentStencilFunc !== stencilFunc ||
  48793. currentStencilRef !== stencilRef ||
  48794. currentStencilFuncMask !== stencilMask ) {
  48795. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48796. currentStencilFunc = stencilFunc;
  48797. currentStencilRef = stencilRef;
  48798. currentStencilFuncMask = stencilMask;
  48799. }
  48800. },
  48801. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48802. if ( currentStencilFail !== stencilFail ||
  48803. currentStencilZFail !== stencilZFail ||
  48804. currentStencilZPass !== stencilZPass ) {
  48805. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48806. currentStencilFail = stencilFail;
  48807. currentStencilZFail = stencilZFail;
  48808. currentStencilZPass = stencilZPass;
  48809. }
  48810. },
  48811. setLocked: function ( lock ) {
  48812. locked = lock;
  48813. },
  48814. setClear: function ( stencil ) {
  48815. if ( currentStencilClear !== stencil ) {
  48816. gl.clearStencil( stencil );
  48817. currentStencilClear = stencil;
  48818. }
  48819. },
  48820. reset: function () {
  48821. locked = false;
  48822. currentStencilMask = null;
  48823. currentStencilFunc = null;
  48824. currentStencilRef = null;
  48825. currentStencilFuncMask = null;
  48826. currentStencilFail = null;
  48827. currentStencilZFail = null;
  48828. currentStencilZPass = null;
  48829. currentStencilClear = null;
  48830. }
  48831. };
  48832. }
  48833. //
  48834. const colorBuffer = new ColorBuffer();
  48835. const depthBuffer = new DepthBuffer();
  48836. const stencilBuffer = new StencilBuffer();
  48837. const uboBindings = new WeakMap();
  48838. const uboProgramMap = new WeakMap();
  48839. let enabledCapabilities = {};
  48840. let currentBoundFramebuffers = {};
  48841. let currentDrawbuffers = new WeakMap();
  48842. let defaultDrawbuffers = [];
  48843. let currentProgram = null;
  48844. let currentBlendingEnabled = false;
  48845. let currentBlending = null;
  48846. let currentBlendEquation = null;
  48847. let currentBlendSrc = null;
  48848. let currentBlendDst = null;
  48849. let currentBlendEquationAlpha = null;
  48850. let currentBlendSrcAlpha = null;
  48851. let currentBlendDstAlpha = null;
  48852. let currentBlendColor = new Color( 0, 0, 0 );
  48853. let currentBlendAlpha = 0;
  48854. let currentPremultipledAlpha = false;
  48855. let currentFlipSided = null;
  48856. let currentCullFace = null;
  48857. let currentLineWidth = null;
  48858. let currentPolygonOffsetFactor = null;
  48859. let currentPolygonOffsetUnits = null;
  48860. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48861. let lineWidthAvailable = false;
  48862. let version = 0;
  48863. const glVersion = gl.getParameter( gl.VERSION );
  48864. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  48865. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  48866. lineWidthAvailable = ( version >= 1.0 );
  48867. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  48868. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  48869. lineWidthAvailable = ( version >= 2.0 );
  48870. }
  48871. let currentTextureSlot = null;
  48872. let currentBoundTextures = {};
  48873. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48874. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48875. const currentScissor = new Vector4().fromArray( scissorParam );
  48876. const currentViewport = new Vector4().fromArray( viewportParam );
  48877. function createTexture( type, target, count, dimensions ) {
  48878. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  48879. const texture = gl.createTexture();
  48880. gl.bindTexture( type, texture );
  48881. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48882. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48883. for ( let i = 0; i < count; i ++ ) {
  48884. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  48885. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48886. } else {
  48887. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48888. }
  48889. }
  48890. return texture;
  48891. }
  48892. const emptyTextures = {};
  48893. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  48894. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  48895. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  48896. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  48897. // init
  48898. colorBuffer.setClear( 0, 0, 0, 1 );
  48899. depthBuffer.setClear( 1 );
  48900. stencilBuffer.setClear( 0 );
  48901. enable( gl.DEPTH_TEST );
  48902. depthBuffer.setFunc( LessEqualDepth );
  48903. setFlipSided( false );
  48904. setCullFace( CullFaceBack );
  48905. enable( gl.CULL_FACE );
  48906. setBlending( NoBlending );
  48907. //
  48908. function enable( id ) {
  48909. if ( enabledCapabilities[ id ] !== true ) {
  48910. gl.enable( id );
  48911. enabledCapabilities[ id ] = true;
  48912. }
  48913. }
  48914. function disable( id ) {
  48915. if ( enabledCapabilities[ id ] !== false ) {
  48916. gl.disable( id );
  48917. enabledCapabilities[ id ] = false;
  48918. }
  48919. }
  48920. function bindFramebuffer( target, framebuffer ) {
  48921. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48922. gl.bindFramebuffer( target, framebuffer );
  48923. currentBoundFramebuffers[ target ] = framebuffer;
  48924. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48925. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48926. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48927. }
  48928. if ( target === gl.FRAMEBUFFER ) {
  48929. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48930. }
  48931. return true;
  48932. }
  48933. return false;
  48934. }
  48935. function drawBuffers( renderTarget, framebuffer ) {
  48936. let drawBuffers = defaultDrawbuffers;
  48937. let needsUpdate = false;
  48938. if ( renderTarget ) {
  48939. drawBuffers = currentDrawbuffers.get( framebuffer );
  48940. if ( drawBuffers === undefined ) {
  48941. drawBuffers = [];
  48942. currentDrawbuffers.set( framebuffer, drawBuffers );
  48943. }
  48944. const textures = renderTarget.textures;
  48945. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48946. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48947. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48948. }
  48949. drawBuffers.length = textures.length;
  48950. needsUpdate = true;
  48951. }
  48952. } else {
  48953. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48954. drawBuffers[ 0 ] = gl.BACK;
  48955. needsUpdate = true;
  48956. }
  48957. }
  48958. if ( needsUpdate ) {
  48959. gl.drawBuffers( drawBuffers );
  48960. }
  48961. }
  48962. function useProgram( program ) {
  48963. if ( currentProgram !== program ) {
  48964. gl.useProgram( program );
  48965. currentProgram = program;
  48966. return true;
  48967. }
  48968. return false;
  48969. }
  48970. const equationToGL = {
  48971. [ AddEquation ]: gl.FUNC_ADD,
  48972. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48973. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48974. };
  48975. equationToGL[ MinEquation ] = gl.MIN;
  48976. equationToGL[ MaxEquation ] = gl.MAX;
  48977. const factorToGL = {
  48978. [ ZeroFactor ]: gl.ZERO,
  48979. [ OneFactor ]: gl.ONE,
  48980. [ SrcColorFactor ]: gl.SRC_COLOR,
  48981. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48982. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48983. [ DstColorFactor ]: gl.DST_COLOR,
  48984. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48985. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48986. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48987. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48988. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  48989. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  48990. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  48991. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  48992. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  48993. };
  48994. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  48995. if ( blending === NoBlending ) {
  48996. if ( currentBlendingEnabled === true ) {
  48997. disable( gl.BLEND );
  48998. currentBlendingEnabled = false;
  48999. }
  49000. return;
  49001. }
  49002. if ( currentBlendingEnabled === false ) {
  49003. enable( gl.BLEND );
  49004. currentBlendingEnabled = true;
  49005. }
  49006. if ( blending !== CustomBlending ) {
  49007. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  49008. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  49009. gl.blendEquation( gl.FUNC_ADD );
  49010. currentBlendEquation = AddEquation;
  49011. currentBlendEquationAlpha = AddEquation;
  49012. }
  49013. if ( premultipliedAlpha ) {
  49014. switch ( blending ) {
  49015. case NormalBlending:
  49016. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49017. break;
  49018. case AdditiveBlending:
  49019. gl.blendFunc( gl.ONE, gl.ONE );
  49020. break;
  49021. case SubtractiveBlending:
  49022. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  49023. break;
  49024. case MultiplyBlending:
  49025. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  49026. break;
  49027. default:
  49028. error( 'WebGLState: Invalid blending: ', blending );
  49029. break;
  49030. }
  49031. } else {
  49032. switch ( blending ) {
  49033. case NormalBlending:
  49034. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  49035. break;
  49036. case AdditiveBlending:
  49037. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  49038. break;
  49039. case SubtractiveBlending:
  49040. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  49041. break;
  49042. case MultiplyBlending:
  49043. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  49044. break;
  49045. default:
  49046. error( 'WebGLState: Invalid blending: ', blending );
  49047. break;
  49048. }
  49049. }
  49050. currentBlendSrc = null;
  49051. currentBlendDst = null;
  49052. currentBlendSrcAlpha = null;
  49053. currentBlendDstAlpha = null;
  49054. currentBlendColor.set( 0, 0, 0 );
  49055. currentBlendAlpha = 0;
  49056. currentBlending = blending;
  49057. currentPremultipledAlpha = premultipliedAlpha;
  49058. }
  49059. return;
  49060. }
  49061. // custom blending
  49062. blendEquationAlpha = blendEquationAlpha || blendEquation;
  49063. blendSrcAlpha = blendSrcAlpha || blendSrc;
  49064. blendDstAlpha = blendDstAlpha || blendDst;
  49065. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  49066. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  49067. currentBlendEquation = blendEquation;
  49068. currentBlendEquationAlpha = blendEquationAlpha;
  49069. }
  49070. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  49071. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  49072. currentBlendSrc = blendSrc;
  49073. currentBlendDst = blendDst;
  49074. currentBlendSrcAlpha = blendSrcAlpha;
  49075. currentBlendDstAlpha = blendDstAlpha;
  49076. }
  49077. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  49078. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  49079. currentBlendColor.copy( blendColor );
  49080. currentBlendAlpha = blendAlpha;
  49081. }
  49082. currentBlending = blending;
  49083. currentPremultipledAlpha = false;
  49084. }
  49085. function setMaterial( material, frontFaceCW ) {
  49086. material.side === DoubleSide
  49087. ? disable( gl.CULL_FACE )
  49088. : enable( gl.CULL_FACE );
  49089. let flipSided = ( material.side === BackSide );
  49090. if ( frontFaceCW ) flipSided = ! flipSided;
  49091. setFlipSided( flipSided );
  49092. ( material.blending === NormalBlending && material.transparent === false )
  49093. ? setBlending( NoBlending )
  49094. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  49095. depthBuffer.setFunc( material.depthFunc );
  49096. depthBuffer.setTest( material.depthTest );
  49097. depthBuffer.setMask( material.depthWrite );
  49098. colorBuffer.setMask( material.colorWrite );
  49099. const stencilWrite = material.stencilWrite;
  49100. stencilBuffer.setTest( stencilWrite );
  49101. if ( stencilWrite ) {
  49102. stencilBuffer.setMask( material.stencilWriteMask );
  49103. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  49104. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  49105. }
  49106. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  49107. material.alphaToCoverage === true
  49108. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  49109. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49110. }
  49111. //
  49112. function setFlipSided( flipSided ) {
  49113. if ( currentFlipSided !== flipSided ) {
  49114. if ( flipSided ) {
  49115. gl.frontFace( gl.CW );
  49116. } else {
  49117. gl.frontFace( gl.CCW );
  49118. }
  49119. currentFlipSided = flipSided;
  49120. }
  49121. }
  49122. function setCullFace( cullFace ) {
  49123. if ( cullFace !== CullFaceNone ) {
  49124. enable( gl.CULL_FACE );
  49125. if ( cullFace !== currentCullFace ) {
  49126. if ( cullFace === CullFaceBack ) {
  49127. gl.cullFace( gl.BACK );
  49128. } else if ( cullFace === CullFaceFront ) {
  49129. gl.cullFace( gl.FRONT );
  49130. } else {
  49131. gl.cullFace( gl.FRONT_AND_BACK );
  49132. }
  49133. }
  49134. } else {
  49135. disable( gl.CULL_FACE );
  49136. }
  49137. currentCullFace = cullFace;
  49138. }
  49139. function setLineWidth( width ) {
  49140. if ( width !== currentLineWidth ) {
  49141. if ( lineWidthAvailable ) gl.lineWidth( width );
  49142. currentLineWidth = width;
  49143. }
  49144. }
  49145. function setPolygonOffset( polygonOffset, factor, units ) {
  49146. if ( polygonOffset ) {
  49147. enable( gl.POLYGON_OFFSET_FILL );
  49148. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  49149. gl.polygonOffset( factor, units );
  49150. currentPolygonOffsetFactor = factor;
  49151. currentPolygonOffsetUnits = units;
  49152. }
  49153. } else {
  49154. disable( gl.POLYGON_OFFSET_FILL );
  49155. }
  49156. }
  49157. function setScissorTest( scissorTest ) {
  49158. if ( scissorTest ) {
  49159. enable( gl.SCISSOR_TEST );
  49160. } else {
  49161. disable( gl.SCISSOR_TEST );
  49162. }
  49163. }
  49164. // texture
  49165. function activeTexture( webglSlot ) {
  49166. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49167. if ( currentTextureSlot !== webglSlot ) {
  49168. gl.activeTexture( webglSlot );
  49169. currentTextureSlot = webglSlot;
  49170. }
  49171. }
  49172. function bindTexture( webglType, webglTexture, webglSlot ) {
  49173. if ( webglSlot === undefined ) {
  49174. if ( currentTextureSlot === null ) {
  49175. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49176. } else {
  49177. webglSlot = currentTextureSlot;
  49178. }
  49179. }
  49180. let boundTexture = currentBoundTextures[ webglSlot ];
  49181. if ( boundTexture === undefined ) {
  49182. boundTexture = { type: undefined, texture: undefined };
  49183. currentBoundTextures[ webglSlot ] = boundTexture;
  49184. }
  49185. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49186. if ( currentTextureSlot !== webglSlot ) {
  49187. gl.activeTexture( webglSlot );
  49188. currentTextureSlot = webglSlot;
  49189. }
  49190. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  49191. boundTexture.type = webglType;
  49192. boundTexture.texture = webglTexture;
  49193. }
  49194. }
  49195. function unbindTexture() {
  49196. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49197. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49198. gl.bindTexture( boundTexture.type, null );
  49199. boundTexture.type = undefined;
  49200. boundTexture.texture = undefined;
  49201. }
  49202. }
  49203. function compressedTexImage2D() {
  49204. try {
  49205. gl.compressedTexImage2D( ...arguments );
  49206. } catch ( e ) {
  49207. error( 'WebGLState:', e );
  49208. }
  49209. }
  49210. function compressedTexImage3D() {
  49211. try {
  49212. gl.compressedTexImage3D( ...arguments );
  49213. } catch ( e ) {
  49214. error( 'WebGLState:', e );
  49215. }
  49216. }
  49217. function texSubImage2D() {
  49218. try {
  49219. gl.texSubImage2D( ...arguments );
  49220. } catch ( e ) {
  49221. error( 'WebGLState:', e );
  49222. }
  49223. }
  49224. function texSubImage3D() {
  49225. try {
  49226. gl.texSubImage3D( ...arguments );
  49227. } catch ( e ) {
  49228. error( 'WebGLState:', e );
  49229. }
  49230. }
  49231. function compressedTexSubImage2D() {
  49232. try {
  49233. gl.compressedTexSubImage2D( ...arguments );
  49234. } catch ( e ) {
  49235. error( 'WebGLState:', e );
  49236. }
  49237. }
  49238. function compressedTexSubImage3D() {
  49239. try {
  49240. gl.compressedTexSubImage3D( ...arguments );
  49241. } catch ( e ) {
  49242. error( 'WebGLState:', e );
  49243. }
  49244. }
  49245. function texStorage2D() {
  49246. try {
  49247. gl.texStorage2D( ...arguments );
  49248. } catch ( e ) {
  49249. error( 'WebGLState:', e );
  49250. }
  49251. }
  49252. function texStorage3D() {
  49253. try {
  49254. gl.texStorage3D( ...arguments );
  49255. } catch ( e ) {
  49256. error( 'WebGLState:', e );
  49257. }
  49258. }
  49259. function texImage2D() {
  49260. try {
  49261. gl.texImage2D( ...arguments );
  49262. } catch ( e ) {
  49263. error( 'WebGLState:', e );
  49264. }
  49265. }
  49266. function texImage3D() {
  49267. try {
  49268. gl.texImage3D( ...arguments );
  49269. } catch ( e ) {
  49270. error( 'WebGLState:', e );
  49271. }
  49272. }
  49273. //
  49274. function scissor( scissor ) {
  49275. if ( currentScissor.equals( scissor ) === false ) {
  49276. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  49277. currentScissor.copy( scissor );
  49278. }
  49279. }
  49280. function viewport( viewport ) {
  49281. if ( currentViewport.equals( viewport ) === false ) {
  49282. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  49283. currentViewport.copy( viewport );
  49284. }
  49285. }
  49286. function updateUBOMapping( uniformsGroup, program ) {
  49287. let mapping = uboProgramMap.get( program );
  49288. if ( mapping === undefined ) {
  49289. mapping = new WeakMap();
  49290. uboProgramMap.set( program, mapping );
  49291. }
  49292. let blockIndex = mapping.get( uniformsGroup );
  49293. if ( blockIndex === undefined ) {
  49294. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  49295. mapping.set( uniformsGroup, blockIndex );
  49296. }
  49297. }
  49298. function uniformBlockBinding( uniformsGroup, program ) {
  49299. const mapping = uboProgramMap.get( program );
  49300. const blockIndex = mapping.get( uniformsGroup );
  49301. if ( uboBindings.get( program ) !== blockIndex ) {
  49302. // bind shader specific block index to global block point
  49303. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  49304. uboBindings.set( program, blockIndex );
  49305. }
  49306. }
  49307. //
  49308. function reset() {
  49309. // reset state
  49310. gl.disable( gl.BLEND );
  49311. gl.disable( gl.CULL_FACE );
  49312. gl.disable( gl.DEPTH_TEST );
  49313. gl.disable( gl.POLYGON_OFFSET_FILL );
  49314. gl.disable( gl.SCISSOR_TEST );
  49315. gl.disable( gl.STENCIL_TEST );
  49316. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49317. gl.blendEquation( gl.FUNC_ADD );
  49318. gl.blendFunc( gl.ONE, gl.ZERO );
  49319. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49320. gl.blendColor( 0, 0, 0, 0 );
  49321. gl.colorMask( true, true, true, true );
  49322. gl.clearColor( 0, 0, 0, 0 );
  49323. gl.depthMask( true );
  49324. gl.depthFunc( gl.LESS );
  49325. depthBuffer.setReversed( false );
  49326. gl.clearDepth( 1 );
  49327. gl.stencilMask( 0xffffffff );
  49328. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49329. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49330. gl.clearStencil( 0 );
  49331. gl.cullFace( gl.BACK );
  49332. gl.frontFace( gl.CCW );
  49333. gl.polygonOffset( 0, 0 );
  49334. gl.activeTexture( gl.TEXTURE0 );
  49335. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49336. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49337. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49338. gl.useProgram( null );
  49339. gl.lineWidth( 1 );
  49340. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49341. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49342. // reset internals
  49343. enabledCapabilities = {};
  49344. currentTextureSlot = null;
  49345. currentBoundTextures = {};
  49346. currentBoundFramebuffers = {};
  49347. currentDrawbuffers = new WeakMap();
  49348. defaultDrawbuffers = [];
  49349. currentProgram = null;
  49350. currentBlendingEnabled = false;
  49351. currentBlending = null;
  49352. currentBlendEquation = null;
  49353. currentBlendSrc = null;
  49354. currentBlendDst = null;
  49355. currentBlendEquationAlpha = null;
  49356. currentBlendSrcAlpha = null;
  49357. currentBlendDstAlpha = null;
  49358. currentBlendColor = new Color( 0, 0, 0 );
  49359. currentBlendAlpha = 0;
  49360. currentPremultipledAlpha = false;
  49361. currentFlipSided = null;
  49362. currentCullFace = null;
  49363. currentLineWidth = null;
  49364. currentPolygonOffsetFactor = null;
  49365. currentPolygonOffsetUnits = null;
  49366. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49367. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49368. colorBuffer.reset();
  49369. depthBuffer.reset();
  49370. stencilBuffer.reset();
  49371. }
  49372. return {
  49373. buffers: {
  49374. color: colorBuffer,
  49375. depth: depthBuffer,
  49376. stencil: stencilBuffer
  49377. },
  49378. enable: enable,
  49379. disable: disable,
  49380. bindFramebuffer: bindFramebuffer,
  49381. drawBuffers: drawBuffers,
  49382. useProgram: useProgram,
  49383. setBlending: setBlending,
  49384. setMaterial: setMaterial,
  49385. setFlipSided: setFlipSided,
  49386. setCullFace: setCullFace,
  49387. setLineWidth: setLineWidth,
  49388. setPolygonOffset: setPolygonOffset,
  49389. setScissorTest: setScissorTest,
  49390. activeTexture: activeTexture,
  49391. bindTexture: bindTexture,
  49392. unbindTexture: unbindTexture,
  49393. compressedTexImage2D: compressedTexImage2D,
  49394. compressedTexImage3D: compressedTexImage3D,
  49395. texImage2D: texImage2D,
  49396. texImage3D: texImage3D,
  49397. updateUBOMapping: updateUBOMapping,
  49398. uniformBlockBinding: uniformBlockBinding,
  49399. texStorage2D: texStorage2D,
  49400. texStorage3D: texStorage3D,
  49401. texSubImage2D: texSubImage2D,
  49402. texSubImage3D: texSubImage3D,
  49403. compressedTexSubImage2D: compressedTexSubImage2D,
  49404. compressedTexSubImage3D: compressedTexSubImage3D,
  49405. scissor: scissor,
  49406. viewport: viewport,
  49407. reset: reset
  49408. };
  49409. }
  49410. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  49411. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  49412. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49413. const _imageDimensions = new Vector2();
  49414. const _videoTextures = new WeakMap();
  49415. let _canvas;
  49416. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  49417. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  49418. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  49419. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  49420. let useOffscreenCanvas = false;
  49421. try {
  49422. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  49423. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  49424. } catch ( err ) {
  49425. // Ignore any errors
  49426. }
  49427. function createCanvas( width, height ) {
  49428. // Use OffscreenCanvas when available. Specially needed in web workers
  49429. return useOffscreenCanvas ?
  49430. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  49431. }
  49432. function resizeImage( image, needsNewCanvas, maxSize ) {
  49433. let scale = 1;
  49434. const dimensions = getDimensions( image );
  49435. // handle case if texture exceeds max size
  49436. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  49437. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  49438. }
  49439. // only perform resize if necessary
  49440. if ( scale < 1 ) {
  49441. // only perform resize for certain image types
  49442. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  49443. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49444. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  49445. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  49446. const width = Math.floor( scale * dimensions.width );
  49447. const height = Math.floor( scale * dimensions.height );
  49448. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  49449. // cube textures can't reuse the same canvas
  49450. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  49451. canvas.width = width;
  49452. canvas.height = height;
  49453. const context = canvas.getContext( '2d' );
  49454. context.drawImage( image, 0, 0, width, height );
  49455. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  49456. return canvas;
  49457. } else {
  49458. if ( 'data' in image ) {
  49459. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  49460. }
  49461. return image;
  49462. }
  49463. }
  49464. return image;
  49465. }
  49466. function textureNeedsGenerateMipmaps( texture ) {
  49467. return texture.generateMipmaps;
  49468. }
  49469. function generateMipmap( target ) {
  49470. _gl.generateMipmap( target );
  49471. }
  49472. function getTargetType( texture ) {
  49473. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  49474. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  49475. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  49476. return _gl.TEXTURE_2D;
  49477. }
  49478. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  49479. if ( internalFormatName !== null ) {
  49480. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  49481. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49482. }
  49483. let internalFormat = glFormat;
  49484. if ( glFormat === _gl.RED ) {
  49485. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  49486. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  49487. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  49488. }
  49489. if ( glFormat === _gl.RED_INTEGER ) {
  49490. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  49491. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  49492. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  49493. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  49494. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  49495. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  49496. }
  49497. if ( glFormat === _gl.RG ) {
  49498. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  49499. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  49500. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  49501. }
  49502. if ( glFormat === _gl.RG_INTEGER ) {
  49503. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  49504. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  49505. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  49506. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  49507. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  49508. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  49509. }
  49510. if ( glFormat === _gl.RGB_INTEGER ) {
  49511. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  49512. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  49513. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  49514. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  49515. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  49516. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  49517. }
  49518. if ( glFormat === _gl.RGBA_INTEGER ) {
  49519. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  49520. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  49521. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  49522. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  49523. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  49524. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  49525. }
  49526. if ( glFormat === _gl.RGB ) {
  49527. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  49528. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  49529. }
  49530. if ( glFormat === _gl.RGBA ) {
  49531. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49532. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  49533. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  49534. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  49535. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  49536. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  49537. }
  49538. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  49539. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  49540. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  49541. extensions.get( 'EXT_color_buffer_float' );
  49542. }
  49543. return internalFormat;
  49544. }
  49545. function getInternalDepthFormat( useStencil, depthType ) {
  49546. let glInternalFormat;
  49547. if ( useStencil ) {
  49548. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49549. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49550. } else if ( depthType === FloatType ) {
  49551. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  49552. } else if ( depthType === UnsignedShortType ) {
  49553. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49554. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  49555. }
  49556. } else {
  49557. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49558. glInternalFormat = _gl.DEPTH_COMPONENT24;
  49559. } else if ( depthType === FloatType ) {
  49560. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  49561. } else if ( depthType === UnsignedShortType ) {
  49562. glInternalFormat = _gl.DEPTH_COMPONENT16;
  49563. }
  49564. }
  49565. return glInternalFormat;
  49566. }
  49567. function getMipLevels( texture, image ) {
  49568. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  49569. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  49570. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  49571. // user-defined mipmaps
  49572. return texture.mipmaps.length;
  49573. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  49574. return image.mipmaps.length;
  49575. } else {
  49576. // texture without mipmaps (only base level)
  49577. return 1;
  49578. }
  49579. }
  49580. //
  49581. function onTextureDispose( event ) {
  49582. const texture = event.target;
  49583. texture.removeEventListener( 'dispose', onTextureDispose );
  49584. deallocateTexture( texture );
  49585. if ( texture.isVideoTexture ) {
  49586. _videoTextures.delete( texture );
  49587. }
  49588. }
  49589. function onRenderTargetDispose( event ) {
  49590. const renderTarget = event.target;
  49591. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  49592. deallocateRenderTarget( renderTarget );
  49593. }
  49594. //
  49595. function deallocateTexture( texture ) {
  49596. const textureProperties = properties.get( texture );
  49597. if ( textureProperties.__webglInit === undefined ) return;
  49598. // check if it's necessary to remove the WebGLTexture object
  49599. const source = texture.source;
  49600. const webglTextures = _sources.get( source );
  49601. if ( webglTextures ) {
  49602. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49603. webglTexture.usedTimes --;
  49604. // the WebGLTexture object is not used anymore, remove it
  49605. if ( webglTexture.usedTimes === 0 ) {
  49606. deleteTexture( texture );
  49607. }
  49608. // remove the weak map entry if no WebGLTexture uses the source anymore
  49609. if ( Object.keys( webglTextures ).length === 0 ) {
  49610. _sources.delete( source );
  49611. }
  49612. }
  49613. properties.remove( texture );
  49614. }
  49615. function deleteTexture( texture ) {
  49616. const textureProperties = properties.get( texture );
  49617. _gl.deleteTexture( textureProperties.__webglTexture );
  49618. const source = texture.source;
  49619. const webglTextures = _sources.get( source );
  49620. delete webglTextures[ textureProperties.__cacheKey ];
  49621. info.memory.textures --;
  49622. }
  49623. function deallocateRenderTarget( renderTarget ) {
  49624. const renderTargetProperties = properties.get( renderTarget );
  49625. if ( renderTarget.depthTexture ) {
  49626. renderTarget.depthTexture.dispose();
  49627. properties.remove( renderTarget.depthTexture );
  49628. }
  49629. if ( renderTarget.isWebGLCubeRenderTarget ) {
  49630. for ( let i = 0; i < 6; i ++ ) {
  49631. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  49632. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  49633. } else {
  49634. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  49635. }
  49636. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  49637. }
  49638. } else {
  49639. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  49640. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  49641. } else {
  49642. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  49643. }
  49644. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49645. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49646. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49647. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49648. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49649. }
  49650. }
  49651. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49652. }
  49653. const textures = renderTarget.textures;
  49654. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49655. const attachmentProperties = properties.get( textures[ i ] );
  49656. if ( attachmentProperties.__webglTexture ) {
  49657. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49658. info.memory.textures --;
  49659. }
  49660. properties.remove( textures[ i ] );
  49661. }
  49662. properties.remove( renderTarget );
  49663. }
  49664. //
  49665. let textureUnits = 0;
  49666. function resetTextureUnits() {
  49667. textureUnits = 0;
  49668. }
  49669. function allocateTextureUnit() {
  49670. const textureUnit = textureUnits;
  49671. if ( textureUnit >= capabilities.maxTextures ) {
  49672. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49673. }
  49674. textureUnits += 1;
  49675. return textureUnit;
  49676. }
  49677. function getTextureCacheKey( texture ) {
  49678. const array = [];
  49679. array.push( texture.wrapS );
  49680. array.push( texture.wrapT );
  49681. array.push( texture.wrapR || 0 );
  49682. array.push( texture.magFilter );
  49683. array.push( texture.minFilter );
  49684. array.push( texture.anisotropy );
  49685. array.push( texture.internalFormat );
  49686. array.push( texture.format );
  49687. array.push( texture.type );
  49688. array.push( texture.generateMipmaps );
  49689. array.push( texture.premultiplyAlpha );
  49690. array.push( texture.flipY );
  49691. array.push( texture.unpackAlignment );
  49692. array.push( texture.colorSpace );
  49693. return array.join();
  49694. }
  49695. //
  49696. function setTexture2D( texture, slot ) {
  49697. const textureProperties = properties.get( texture );
  49698. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49699. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49700. const image = texture.image;
  49701. if ( image === null ) {
  49702. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  49703. } else if ( image.complete === false ) {
  49704. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  49705. } else {
  49706. uploadTexture( textureProperties, texture, slot );
  49707. return;
  49708. }
  49709. } else if ( texture.isExternalTexture ) {
  49710. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49711. }
  49712. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49713. }
  49714. function setTexture2DArray( texture, slot ) {
  49715. const textureProperties = properties.get( texture );
  49716. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49717. uploadTexture( textureProperties, texture, slot );
  49718. return;
  49719. } else if ( texture.isExternalTexture ) {
  49720. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49721. }
  49722. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49723. }
  49724. function setTexture3D( texture, slot ) {
  49725. const textureProperties = properties.get( texture );
  49726. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49727. uploadTexture( textureProperties, texture, slot );
  49728. return;
  49729. }
  49730. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49731. }
  49732. function setTextureCube( texture, slot ) {
  49733. const textureProperties = properties.get( texture );
  49734. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49735. uploadCubeTexture( textureProperties, texture, slot );
  49736. return;
  49737. }
  49738. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49739. }
  49740. const wrappingToGL = {
  49741. [ RepeatWrapping ]: _gl.REPEAT,
  49742. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49743. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49744. };
  49745. const filterToGL = {
  49746. [ NearestFilter ]: _gl.NEAREST,
  49747. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49748. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49749. [ LinearFilter ]: _gl.LINEAR,
  49750. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49751. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49752. };
  49753. const compareToGL = {
  49754. [ NeverCompare ]: _gl.NEVER,
  49755. [ AlwaysCompare ]: _gl.ALWAYS,
  49756. [ LessCompare ]: _gl.LESS,
  49757. [ LessEqualCompare ]: _gl.LEQUAL,
  49758. [ EqualCompare ]: _gl.EQUAL,
  49759. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49760. [ GreaterCompare ]: _gl.GREATER,
  49761. [ NotEqualCompare ]: _gl.NOTEQUAL
  49762. };
  49763. function setTextureParameters( textureType, texture ) {
  49764. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49765. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49766. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49767. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49768. }
  49769. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49770. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49771. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49772. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49773. }
  49774. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49775. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49776. if ( texture.compareFunction ) {
  49777. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49778. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49779. }
  49780. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49781. if ( texture.magFilter === NearestFilter ) return;
  49782. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49783. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49784. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49785. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49786. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49787. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49788. }
  49789. }
  49790. }
  49791. function initTexture( textureProperties, texture ) {
  49792. let forceUpload = false;
  49793. if ( textureProperties.__webglInit === undefined ) {
  49794. textureProperties.__webglInit = true;
  49795. texture.addEventListener( 'dispose', onTextureDispose );
  49796. }
  49797. // create Source <-> WebGLTextures mapping if necessary
  49798. const source = texture.source;
  49799. let webglTextures = _sources.get( source );
  49800. if ( webglTextures === undefined ) {
  49801. webglTextures = {};
  49802. _sources.set( source, webglTextures );
  49803. }
  49804. // check if there is already a WebGLTexture object for the given texture parameters
  49805. const textureCacheKey = getTextureCacheKey( texture );
  49806. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49807. // if not, create a new instance of WebGLTexture
  49808. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49809. // create new entry
  49810. webglTextures[ textureCacheKey ] = {
  49811. texture: _gl.createTexture(),
  49812. usedTimes: 0
  49813. };
  49814. info.memory.textures ++;
  49815. // when a new instance of WebGLTexture was created, a texture upload is required
  49816. // even if the image contents are identical
  49817. forceUpload = true;
  49818. }
  49819. webglTextures[ textureCacheKey ].usedTimes ++;
  49820. // every time the texture cache key changes, it's necessary to check if an instance of
  49821. // WebGLTexture can be deleted in order to avoid a memory leak.
  49822. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49823. if ( webglTexture !== undefined ) {
  49824. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49825. if ( webglTexture.usedTimes === 0 ) {
  49826. deleteTexture( texture );
  49827. }
  49828. }
  49829. // store references to cache key and WebGLTexture object
  49830. textureProperties.__cacheKey = textureCacheKey;
  49831. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49832. }
  49833. return forceUpload;
  49834. }
  49835. function getRow( index, rowLength, componentStride ) {
  49836. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49837. }
  49838. function updateTexture( texture, image, glFormat, glType ) {
  49839. const componentStride = 4; // only RGBA supported
  49840. const updateRanges = texture.updateRanges;
  49841. if ( updateRanges.length === 0 ) {
  49842. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49843. } else {
  49844. // Before applying update ranges, we merge any adjacent / overlapping
  49845. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49846. // to performance improvements for applications which make heavy use of
  49847. // update ranges. Likely due to GPU command overhead.
  49848. //
  49849. // Note that to reduce garbage collection between frames, we merge the
  49850. // update ranges in-place. This is safe because this method will clear the
  49851. // update ranges once updated.
  49852. updateRanges.sort( ( a, b ) => a.start - b.start );
  49853. // To merge the update ranges in-place, we work from left to right in the
  49854. // existing updateRanges array, merging ranges. This may result in a final
  49855. // array which is smaller than the original. This index tracks the last
  49856. // index representing a merged range, any data after this index can be
  49857. // trimmed once the merge algorithm is completed.
  49858. let mergeIndex = 0;
  49859. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49860. const previousRange = updateRanges[ mergeIndex ];
  49861. const range = updateRanges[ i ];
  49862. // Only merge if in the same row and overlapping/adjacent
  49863. const previousEnd = previousRange.start + previousRange.count;
  49864. const currentRow = getRow( range.start, image.width, componentStride );
  49865. const previousRow = getRow( previousRange.start, image.width, componentStride );
  49866. // We add one here to merge adjacent ranges. This is safe because ranges
  49867. // operate over positive integers.
  49868. if (
  49869. range.start <= previousEnd + 1 &&
  49870. currentRow === previousRow &&
  49871. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  49872. ) {
  49873. previousRange.count = Math.max(
  49874. previousRange.count,
  49875. range.start + range.count - previousRange.start
  49876. );
  49877. } else {
  49878. ++ mergeIndex;
  49879. updateRanges[ mergeIndex ] = range;
  49880. }
  49881. }
  49882. // Trim the array to only contain the merged ranges.
  49883. updateRanges.length = mergeIndex + 1;
  49884. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  49885. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  49886. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  49887. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  49888. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49889. const range = updateRanges[ i ];
  49890. const pixelStart = Math.floor( range.start / componentStride );
  49891. const pixelCount = Math.ceil( range.count / componentStride );
  49892. const x = pixelStart % image.width;
  49893. const y = Math.floor( pixelStart / image.width );
  49894. // Assumes update ranges refer to contiguous memory
  49895. const width = pixelCount;
  49896. const height = 1;
  49897. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  49898. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  49899. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  49900. }
  49901. texture.clearUpdateRanges();
  49902. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49903. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49904. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49905. }
  49906. }
  49907. function uploadTexture( textureProperties, texture, slot ) {
  49908. let textureType = _gl.TEXTURE_2D;
  49909. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  49910. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  49911. const forceUpload = initTexture( textureProperties, texture );
  49912. const source = texture.source;
  49913. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49914. const sourceProperties = properties.get( source );
  49915. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49916. state.activeTexture( _gl.TEXTURE0 + slot );
  49917. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49918. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49919. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49920. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49921. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49922. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49923. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49924. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  49925. image = verifyColorSpace( texture, image );
  49926. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49927. const glType = utils.convert( texture.type );
  49928. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  49929. setTextureParameters( textureType, texture );
  49930. let mipmap;
  49931. const mipmaps = texture.mipmaps;
  49932. const useTexStorage = ( texture.isVideoTexture !== true );
  49933. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49934. const dataReady = source.dataReady;
  49935. const levels = getMipLevels( texture, image );
  49936. if ( texture.isDepthTexture ) {
  49937. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  49938. //
  49939. if ( allocateMemory ) {
  49940. if ( useTexStorage ) {
  49941. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  49942. } else {
  49943. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  49944. }
  49945. }
  49946. } else if ( texture.isDataTexture ) {
  49947. // use manually created mipmaps if available
  49948. // if there are no manual mipmaps
  49949. // set 0 level mipmap and then use GL to generate other mipmap levels
  49950. if ( mipmaps.length > 0 ) {
  49951. if ( useTexStorage && allocateMemory ) {
  49952. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49953. }
  49954. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49955. mipmap = mipmaps[ i ];
  49956. if ( useTexStorage ) {
  49957. if ( dataReady ) {
  49958. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49959. }
  49960. } else {
  49961. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49962. }
  49963. }
  49964. texture.generateMipmaps = false;
  49965. } else {
  49966. if ( useTexStorage ) {
  49967. if ( allocateMemory ) {
  49968. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49969. }
  49970. if ( dataReady ) {
  49971. updateTexture( texture, image, glFormat, glType );
  49972. }
  49973. } else {
  49974. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  49975. }
  49976. }
  49977. } else if ( texture.isCompressedTexture ) {
  49978. if ( texture.isCompressedArrayTexture ) {
  49979. if ( useTexStorage && allocateMemory ) {
  49980. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  49981. }
  49982. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49983. mipmap = mipmaps[ i ];
  49984. if ( texture.format !== RGBAFormat ) {
  49985. if ( glFormat !== null ) {
  49986. if ( useTexStorage ) {
  49987. if ( dataReady ) {
  49988. if ( texture.layerUpdates.size > 0 ) {
  49989. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  49990. for ( const layerIndex of texture.layerUpdates ) {
  49991. const layerData = mipmap.data.subarray(
  49992. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  49993. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  49994. );
  49995. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  49996. }
  49997. texture.clearLayerUpdates();
  49998. } else {
  49999. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  50000. }
  50001. }
  50002. } else {
  50003. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  50004. }
  50005. } else {
  50006. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50007. }
  50008. } else {
  50009. if ( useTexStorage ) {
  50010. if ( dataReady ) {
  50011. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  50012. }
  50013. } else {
  50014. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  50015. }
  50016. }
  50017. }
  50018. } else {
  50019. if ( useTexStorage && allocateMemory ) {
  50020. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  50021. }
  50022. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50023. mipmap = mipmaps[ i ];
  50024. if ( texture.format !== RGBAFormat ) {
  50025. if ( glFormat !== null ) {
  50026. if ( useTexStorage ) {
  50027. if ( dataReady ) {
  50028. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50029. }
  50030. } else {
  50031. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50032. }
  50033. } else {
  50034. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  50035. }
  50036. } else {
  50037. if ( useTexStorage ) {
  50038. if ( dataReady ) {
  50039. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50040. }
  50041. } else {
  50042. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50043. }
  50044. }
  50045. }
  50046. }
  50047. } else if ( texture.isDataArrayTexture ) {
  50048. if ( useTexStorage ) {
  50049. if ( allocateMemory ) {
  50050. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  50051. }
  50052. if ( dataReady ) {
  50053. if ( texture.layerUpdates.size > 0 ) {
  50054. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  50055. for ( const layerIndex of texture.layerUpdates ) {
  50056. const layerData = image.data.subarray(
  50057. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  50058. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  50059. );
  50060. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  50061. }
  50062. texture.clearLayerUpdates();
  50063. } else {
  50064. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50065. }
  50066. }
  50067. } else {
  50068. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50069. }
  50070. } else if ( texture.isData3DTexture ) {
  50071. if ( useTexStorage ) {
  50072. if ( allocateMemory ) {
  50073. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  50074. }
  50075. if ( dataReady ) {
  50076. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  50077. }
  50078. } else {
  50079. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  50080. }
  50081. } else if ( texture.isFramebufferTexture ) {
  50082. if ( allocateMemory ) {
  50083. if ( useTexStorage ) {
  50084. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  50085. } else {
  50086. let width = image.width, height = image.height;
  50087. for ( let i = 0; i < levels; i ++ ) {
  50088. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  50089. width >>= 1;
  50090. height >>= 1;
  50091. }
  50092. }
  50093. }
  50094. } else {
  50095. // regular Texture (image, video, canvas)
  50096. // use manually created mipmaps if available
  50097. // if there are no manual mipmaps
  50098. // set 0 level mipmap and then use GL to generate other mipmap levels
  50099. if ( mipmaps.length > 0 ) {
  50100. if ( useTexStorage && allocateMemory ) {
  50101. const dimensions = getDimensions( mipmaps[ 0 ] );
  50102. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50103. }
  50104. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  50105. mipmap = mipmaps[ i ];
  50106. if ( useTexStorage ) {
  50107. if ( dataReady ) {
  50108. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  50109. }
  50110. } else {
  50111. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  50112. }
  50113. }
  50114. texture.generateMipmaps = false;
  50115. } else {
  50116. if ( useTexStorage ) {
  50117. if ( allocateMemory ) {
  50118. const dimensions = getDimensions( image );
  50119. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  50120. }
  50121. if ( dataReady ) {
  50122. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  50123. }
  50124. } else {
  50125. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  50126. }
  50127. }
  50128. }
  50129. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50130. generateMipmap( textureType );
  50131. }
  50132. sourceProperties.__version = source.version;
  50133. if ( texture.onUpdate ) texture.onUpdate( texture );
  50134. }
  50135. textureProperties.__version = texture.version;
  50136. }
  50137. function uploadCubeTexture( textureProperties, texture, slot ) {
  50138. if ( texture.image.length !== 6 ) return;
  50139. const forceUpload = initTexture( textureProperties, texture );
  50140. const source = texture.source;
  50141. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  50142. const sourceProperties = properties.get( source );
  50143. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  50144. state.activeTexture( _gl.TEXTURE0 + slot );
  50145. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  50146. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  50147. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  50148. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  50149. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  50150. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  50151. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  50152. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  50153. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  50154. const cubeImage = [];
  50155. for ( let i = 0; i < 6; i ++ ) {
  50156. if ( ! isCompressed && ! isDataTexture ) {
  50157. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  50158. } else {
  50159. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  50160. }
  50161. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  50162. }
  50163. const image = cubeImage[ 0 ],
  50164. glFormat = utils.convert( texture.format, texture.colorSpace ),
  50165. glType = utils.convert( texture.type ),
  50166. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50167. const useTexStorage = ( texture.isVideoTexture !== true );
  50168. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50169. const dataReady = source.dataReady;
  50170. let levels = getMipLevels( texture, image );
  50171. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50172. let mipmaps;
  50173. if ( isCompressed ) {
  50174. if ( useTexStorage && allocateMemory ) {
  50175. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  50176. }
  50177. for ( let i = 0; i < 6; i ++ ) {
  50178. mipmaps = cubeImage[ i ].mipmaps;
  50179. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50180. const mipmap = mipmaps[ j ];
  50181. if ( texture.format !== RGBAFormat ) {
  50182. if ( glFormat !== null ) {
  50183. if ( useTexStorage ) {
  50184. if ( dataReady ) {
  50185. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50186. }
  50187. } else {
  50188. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50189. }
  50190. } else {
  50191. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  50192. }
  50193. } else {
  50194. if ( useTexStorage ) {
  50195. if ( dataReady ) {
  50196. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50197. }
  50198. } else {
  50199. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50200. }
  50201. }
  50202. }
  50203. }
  50204. } else {
  50205. mipmaps = texture.mipmaps;
  50206. if ( useTexStorage && allocateMemory ) {
  50207. // TODO: Uniformly handle mipmap definitions
  50208. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  50209. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  50210. if ( mipmaps.length > 0 ) levels ++;
  50211. const dimensions = getDimensions( cubeImage[ 0 ] );
  50212. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  50213. }
  50214. for ( let i = 0; i < 6; i ++ ) {
  50215. if ( isDataTexture ) {
  50216. if ( useTexStorage ) {
  50217. if ( dataReady ) {
  50218. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  50219. }
  50220. } else {
  50221. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  50222. }
  50223. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50224. const mipmap = mipmaps[ j ];
  50225. const mipmapImage = mipmap.image[ i ].image;
  50226. if ( useTexStorage ) {
  50227. if ( dataReady ) {
  50228. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  50229. }
  50230. } else {
  50231. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  50232. }
  50233. }
  50234. } else {
  50235. if ( useTexStorage ) {
  50236. if ( dataReady ) {
  50237. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  50238. }
  50239. } else {
  50240. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  50241. }
  50242. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50243. const mipmap = mipmaps[ j ];
  50244. if ( useTexStorage ) {
  50245. if ( dataReady ) {
  50246. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  50247. }
  50248. } else {
  50249. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  50250. }
  50251. }
  50252. }
  50253. }
  50254. }
  50255. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50256. // We assume images for cube map have the same size.
  50257. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50258. }
  50259. sourceProperties.__version = source.version;
  50260. if ( texture.onUpdate ) texture.onUpdate( texture );
  50261. }
  50262. textureProperties.__version = texture.version;
  50263. }
  50264. // Render targets
  50265. // Setup storage for target texture and bind it to correct framebuffer
  50266. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  50267. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50268. const glType = utils.convert( texture.type );
  50269. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50270. const renderTargetProperties = properties.get( renderTarget );
  50271. const textureProperties = properties.get( texture );
  50272. textureProperties.__renderTarget = renderTarget;
  50273. if ( ! renderTargetProperties.__hasExternalTextures ) {
  50274. const width = Math.max( 1, renderTarget.width >> level );
  50275. const height = Math.max( 1, renderTarget.height >> level );
  50276. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  50277. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  50278. } else {
  50279. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  50280. }
  50281. }
  50282. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50283. if ( useMultisampledRTT( renderTarget ) ) {
  50284. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  50285. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  50286. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  50287. }
  50288. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50289. }
  50290. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  50291. function setupRenderBufferStorage( renderbuffer, renderTarget, useMultisample ) {
  50292. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50293. if ( renderTarget.depthBuffer ) {
  50294. // retrieve the depth attachment types
  50295. const depthTexture = renderTarget.depthTexture;
  50296. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  50297. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  50298. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50299. // set up the attachment
  50300. if ( useMultisampledRTT( renderTarget ) ) {
  50301. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50302. } else if ( useMultisample ) {
  50303. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50304. } else {
  50305. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50306. }
  50307. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50308. } else {
  50309. const textures = renderTarget.textures;
  50310. for ( let i = 0; i < textures.length; i ++ ) {
  50311. const texture = textures[ i ];
  50312. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50313. const glType = utils.convert( texture.type );
  50314. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50315. if ( useMultisampledRTT( renderTarget ) ) {
  50316. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50317. } else if ( useMultisample ) {
  50318. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, getRenderTargetSamples( renderTarget ), glInternalFormat, renderTarget.width, renderTarget.height );
  50319. } else {
  50320. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50321. }
  50322. }
  50323. }
  50324. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50325. }
  50326. // Setup resources for a Depth Texture for a FBO (needs an extension)
  50327. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  50328. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50329. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50330. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  50331. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  50332. }
  50333. const textureProperties = properties.get( renderTarget.depthTexture );
  50334. textureProperties.__renderTarget = renderTarget;
  50335. // upload an empty depth texture with framebuffer size
  50336. if ( ! textureProperties.__webglTexture ||
  50337. renderTarget.depthTexture.image.width !== renderTarget.width ||
  50338. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  50339. renderTarget.depthTexture.image.width = renderTarget.width;
  50340. renderTarget.depthTexture.image.height = renderTarget.height;
  50341. renderTarget.depthTexture.needsUpdate = true;
  50342. }
  50343. if ( isCube ) {
  50344. // For cube depth textures, initialize and bind without uploading image data
  50345. if ( textureProperties.__webglInit === undefined ) {
  50346. textureProperties.__webglInit = true;
  50347. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  50348. }
  50349. // Only create and allocate storage once
  50350. if ( textureProperties.__webglTexture === undefined ) {
  50351. textureProperties.__webglTexture = _gl.createTexture();
  50352. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50353. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  50354. // Allocate storage for all 6 faces with correct depth texture format
  50355. const glFormat = utils.convert( renderTarget.depthTexture.format );
  50356. const glType = utils.convert( renderTarget.depthTexture.type );
  50357. // Use proper internal format for depth textures
  50358. let glInternalFormat;
  50359. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50360. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50361. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50362. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50363. }
  50364. for ( let i = 0; i < 6; i ++ ) {
  50365. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  50366. }
  50367. }
  50368. } else {
  50369. setTexture2D( renderTarget.depthTexture, 0 );
  50370. }
  50371. const webglDepthTexture = textureProperties.__webglTexture;
  50372. const samples = getRenderTargetSamples( renderTarget );
  50373. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  50374. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50375. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50376. if ( useMultisampledRTT( renderTarget ) ) {
  50377. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50378. } else {
  50379. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50380. }
  50381. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50382. if ( useMultisampledRTT( renderTarget ) ) {
  50383. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50384. } else {
  50385. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50386. }
  50387. } else {
  50388. throw new Error( 'Unknown depthTexture format' );
  50389. }
  50390. }
  50391. // Setup GL resources for a non-texture depth buffer
  50392. function setupDepthRenderbuffer( renderTarget ) {
  50393. const renderTargetProperties = properties.get( renderTarget );
  50394. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50395. // if the bound depth texture has changed
  50396. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  50397. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  50398. const depthTexture = renderTarget.depthTexture;
  50399. if ( renderTargetProperties.__depthDisposeCallback ) {
  50400. renderTargetProperties.__depthDisposeCallback();
  50401. }
  50402. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  50403. if ( depthTexture ) {
  50404. const disposeEvent = () => {
  50405. delete renderTargetProperties.__boundDepthTexture;
  50406. delete renderTargetProperties.__depthDisposeCallback;
  50407. depthTexture.removeEventListener( 'dispose', disposeEvent );
  50408. };
  50409. depthTexture.addEventListener( 'dispose', disposeEvent );
  50410. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  50411. }
  50412. renderTargetProperties.__boundDepthTexture = depthTexture;
  50413. }
  50414. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  50415. if ( isCube ) {
  50416. // For cube render targets with depth texture, setup each face
  50417. for ( let i = 0; i < 6; i ++ ) {
  50418. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  50419. }
  50420. } else {
  50421. const mipmaps = renderTarget.texture.mipmaps;
  50422. if ( mipmaps && mipmaps.length > 0 ) {
  50423. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  50424. } else {
  50425. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  50426. }
  50427. }
  50428. } else {
  50429. if ( isCube ) {
  50430. renderTargetProperties.__webglDepthbuffer = [];
  50431. for ( let i = 0; i < 6; i ++ ) {
  50432. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  50433. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  50434. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  50435. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  50436. } else {
  50437. // attach buffer if it's been created already
  50438. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50439. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  50440. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50441. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50442. }
  50443. }
  50444. } else {
  50445. const mipmaps = renderTarget.texture.mipmaps;
  50446. if ( mipmaps && mipmaps.length > 0 ) {
  50447. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50448. } else {
  50449. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50450. }
  50451. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  50452. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  50453. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  50454. } else {
  50455. // attach buffer if it's been created already
  50456. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50457. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  50458. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50459. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50460. }
  50461. }
  50462. }
  50463. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50464. }
  50465. // rebind framebuffer with external textures
  50466. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  50467. const renderTargetProperties = properties.get( renderTarget );
  50468. if ( colorTexture !== undefined ) {
  50469. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  50470. }
  50471. if ( depthTexture !== undefined ) {
  50472. setupDepthRenderbuffer( renderTarget );
  50473. }
  50474. }
  50475. // Set up GL resources for the render target
  50476. function setupRenderTarget( renderTarget ) {
  50477. const texture = renderTarget.texture;
  50478. const renderTargetProperties = properties.get( renderTarget );
  50479. const textureProperties = properties.get( texture );
  50480. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  50481. const textures = renderTarget.textures;
  50482. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50483. const isMultipleRenderTargets = ( textures.length > 1 );
  50484. if ( ! isMultipleRenderTargets ) {
  50485. if ( textureProperties.__webglTexture === undefined ) {
  50486. textureProperties.__webglTexture = _gl.createTexture();
  50487. }
  50488. textureProperties.__version = texture.version;
  50489. info.memory.textures ++;
  50490. }
  50491. // Setup framebuffer
  50492. if ( isCube ) {
  50493. renderTargetProperties.__webglFramebuffer = [];
  50494. for ( let i = 0; i < 6; i ++ ) {
  50495. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50496. renderTargetProperties.__webglFramebuffer[ i ] = [];
  50497. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50498. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  50499. }
  50500. } else {
  50501. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  50502. }
  50503. }
  50504. } else {
  50505. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50506. renderTargetProperties.__webglFramebuffer = [];
  50507. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50508. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  50509. }
  50510. } else {
  50511. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  50512. }
  50513. if ( isMultipleRenderTargets ) {
  50514. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50515. const attachmentProperties = properties.get( textures[ i ] );
  50516. if ( attachmentProperties.__webglTexture === undefined ) {
  50517. attachmentProperties.__webglTexture = _gl.createTexture();
  50518. info.memory.textures ++;
  50519. }
  50520. }
  50521. }
  50522. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  50523. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  50524. renderTargetProperties.__webglColorRenderbuffer = [];
  50525. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50526. for ( let i = 0; i < textures.length; i ++ ) {
  50527. const texture = textures[ i ];
  50528. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  50529. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50530. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50531. const glType = utils.convert( texture.type );
  50532. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  50533. const samples = getRenderTargetSamples( renderTarget );
  50534. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50535. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50536. }
  50537. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50538. if ( renderTarget.depthBuffer ) {
  50539. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  50540. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  50541. }
  50542. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50543. }
  50544. }
  50545. // Setup color buffer
  50546. if ( isCube ) {
  50547. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50548. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50549. for ( let i = 0; i < 6; i ++ ) {
  50550. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50551. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50552. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  50553. }
  50554. } else {
  50555. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  50556. }
  50557. }
  50558. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50559. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50560. }
  50561. state.unbindTexture();
  50562. } else if ( isMultipleRenderTargets ) {
  50563. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50564. const attachment = textures[ i ];
  50565. const attachmentProperties = properties.get( attachment );
  50566. let glTextureType = _gl.TEXTURE_2D;
  50567. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50568. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50569. }
  50570. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  50571. setTextureParameters( glTextureType, attachment );
  50572. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  50573. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  50574. generateMipmap( glTextureType );
  50575. }
  50576. }
  50577. state.unbindTexture();
  50578. } else {
  50579. let glTextureType = _gl.TEXTURE_2D;
  50580. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50581. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50582. }
  50583. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  50584. setTextureParameters( glTextureType, texture );
  50585. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50586. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50587. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  50588. }
  50589. } else {
  50590. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  50591. }
  50592. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50593. generateMipmap( glTextureType );
  50594. }
  50595. state.unbindTexture();
  50596. }
  50597. // Setup depth and stencil buffers
  50598. if ( renderTarget.depthBuffer ) {
  50599. setupDepthRenderbuffer( renderTarget );
  50600. }
  50601. }
  50602. function updateRenderTargetMipmap( renderTarget ) {
  50603. const textures = renderTarget.textures;
  50604. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50605. const texture = textures[ i ];
  50606. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50607. const targetType = getTargetType( renderTarget );
  50608. const webglTexture = properties.get( texture ).__webglTexture;
  50609. state.bindTexture( targetType, webglTexture );
  50610. generateMipmap( targetType );
  50611. state.unbindTexture();
  50612. }
  50613. }
  50614. }
  50615. const invalidationArrayRead = [];
  50616. const invalidationArrayDraw = [];
  50617. function updateMultisampleRenderTarget( renderTarget ) {
  50618. if ( renderTarget.samples > 0 ) {
  50619. if ( useMultisampledRTT( renderTarget ) === false ) {
  50620. const textures = renderTarget.textures;
  50621. const width = renderTarget.width;
  50622. const height = renderTarget.height;
  50623. let mask = _gl.COLOR_BUFFER_BIT;
  50624. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50625. const renderTargetProperties = properties.get( renderTarget );
  50626. const isMultipleRenderTargets = ( textures.length > 1 );
  50627. // If MRT we need to remove FBO attachments
  50628. if ( isMultipleRenderTargets ) {
  50629. for ( let i = 0; i < textures.length; i ++ ) {
  50630. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50631. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  50632. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50633. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  50634. }
  50635. }
  50636. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50637. const mipmaps = renderTarget.texture.mipmaps;
  50638. if ( mipmaps && mipmaps.length > 0 ) {
  50639. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50640. } else {
  50641. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50642. }
  50643. for ( let i = 0; i < textures.length; i ++ ) {
  50644. if ( renderTarget.resolveDepthBuffer ) {
  50645. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  50646. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  50647. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  50648. }
  50649. if ( isMultipleRenderTargets ) {
  50650. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50651. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50652. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  50653. }
  50654. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  50655. if ( supportsInvalidateFramebuffer === true ) {
  50656. invalidationArrayRead.length = 0;
  50657. invalidationArrayDraw.length = 0;
  50658. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  50659. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  50660. invalidationArrayRead.push( depthStyle );
  50661. invalidationArrayDraw.push( depthStyle );
  50662. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  50663. }
  50664. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  50665. }
  50666. }
  50667. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  50668. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  50669. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  50670. if ( isMultipleRenderTargets ) {
  50671. for ( let i = 0; i < textures.length; i ++ ) {
  50672. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50673. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50674. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50675. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50676. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  50677. }
  50678. }
  50679. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50680. } else {
  50681. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50682. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50683. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50684. }
  50685. }
  50686. }
  50687. }
  50688. function getRenderTargetSamples( renderTarget ) {
  50689. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50690. }
  50691. function useMultisampledRTT( renderTarget ) {
  50692. const renderTargetProperties = properties.get( renderTarget );
  50693. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50694. }
  50695. function updateVideoTexture( texture ) {
  50696. const frame = info.render.frame;
  50697. // Check the last frame we updated the VideoTexture
  50698. if ( _videoTextures.get( texture ) !== frame ) {
  50699. _videoTextures.set( texture, frame );
  50700. texture.update();
  50701. }
  50702. }
  50703. function verifyColorSpace( texture, image ) {
  50704. const colorSpace = texture.colorSpace;
  50705. const format = texture.format;
  50706. const type = texture.type;
  50707. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50708. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50709. // sRGB
  50710. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50711. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50712. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50713. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50714. }
  50715. } else {
  50716. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  50717. }
  50718. }
  50719. return image;
  50720. }
  50721. function getDimensions( image ) {
  50722. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50723. // if intrinsic data are not available, fallback to width/height
  50724. _imageDimensions.width = image.naturalWidth || image.width;
  50725. _imageDimensions.height = image.naturalHeight || image.height;
  50726. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50727. _imageDimensions.width = image.displayWidth;
  50728. _imageDimensions.height = image.displayHeight;
  50729. } else {
  50730. _imageDimensions.width = image.width;
  50731. _imageDimensions.height = image.height;
  50732. }
  50733. return _imageDimensions;
  50734. }
  50735. //
  50736. this.allocateTextureUnit = allocateTextureUnit;
  50737. this.resetTextureUnits = resetTextureUnits;
  50738. this.setTexture2D = setTexture2D;
  50739. this.setTexture2DArray = setTexture2DArray;
  50740. this.setTexture3D = setTexture3D;
  50741. this.setTextureCube = setTextureCube;
  50742. this.rebindTextures = rebindTextures;
  50743. this.setupRenderTarget = setupRenderTarget;
  50744. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50745. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50746. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50747. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50748. this.useMultisampledRTT = useMultisampledRTT;
  50749. this.isReversedDepthBuffer = function () {
  50750. return state.buffers.depth.getReversed();
  50751. };
  50752. }
  50753. function WebGLUtils( gl, extensions ) {
  50754. function convert( p, colorSpace = NoColorSpace ) {
  50755. let extension;
  50756. const transfer = ColorManagement.getTransfer( colorSpace );
  50757. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50758. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50759. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50760. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50761. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  50762. if ( p === ByteType ) return gl.BYTE;
  50763. if ( p === ShortType ) return gl.SHORT;
  50764. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50765. if ( p === IntType ) return gl.INT;
  50766. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50767. if ( p === FloatType ) return gl.FLOAT;
  50768. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50769. if ( p === AlphaFormat ) return gl.ALPHA;
  50770. if ( p === RGBFormat ) return gl.RGB;
  50771. if ( p === RGBAFormat ) return gl.RGBA;
  50772. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50773. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50774. // WebGL2 formats.
  50775. if ( p === RedFormat ) return gl.RED;
  50776. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50777. if ( p === RGFormat ) return gl.RG;
  50778. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50779. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50780. // S3TC
  50781. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50782. if ( transfer === SRGBTransfer ) {
  50783. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50784. if ( extension !== null ) {
  50785. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50786. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50787. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50788. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50789. } else {
  50790. return null;
  50791. }
  50792. } else {
  50793. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50794. if ( extension !== null ) {
  50795. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50796. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50797. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50798. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50799. } else {
  50800. return null;
  50801. }
  50802. }
  50803. }
  50804. // PVRTC
  50805. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50806. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50807. if ( extension !== null ) {
  50808. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50809. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50810. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50811. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50812. } else {
  50813. return null;
  50814. }
  50815. }
  50816. // ETC
  50817. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format || p === R11_EAC_Format || p === SIGNED_R11_EAC_Format || p === RG11_EAC_Format || p === SIGNED_RG11_EAC_Format ) {
  50818. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50819. if ( extension !== null ) {
  50820. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50821. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50822. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  50823. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  50824. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  50825. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  50826. } else {
  50827. return null;
  50828. }
  50829. }
  50830. // ASTC
  50831. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50832. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50833. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50834. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50835. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50836. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50837. if ( extension !== null ) {
  50838. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50839. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50840. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50841. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50842. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50843. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50844. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50845. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50846. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50847. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50848. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50849. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50850. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50851. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50852. } else {
  50853. return null;
  50854. }
  50855. }
  50856. // BPTC
  50857. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50858. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50859. if ( extension !== null ) {
  50860. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50861. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50862. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50863. } else {
  50864. return null;
  50865. }
  50866. }
  50867. // RGTC
  50868. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  50869. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  50870. if ( extension !== null ) {
  50871. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  50872. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  50873. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  50874. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  50875. } else {
  50876. return null;
  50877. }
  50878. }
  50879. //
  50880. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  50881. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  50882. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  50883. }
  50884. return { convert: convert };
  50885. }
  50886. const _occlusion_vertex = `
  50887. void main() {
  50888. gl_Position = vec4( position, 1.0 );
  50889. }`;
  50890. const _occlusion_fragment = `
  50891. uniform sampler2DArray depthColor;
  50892. uniform float depthWidth;
  50893. uniform float depthHeight;
  50894. void main() {
  50895. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  50896. if ( coord.x >= 1.0 ) {
  50897. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  50898. } else {
  50899. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  50900. }
  50901. }`;
  50902. /**
  50903. * A XR module that manages the access to the Depth Sensing API.
  50904. */
  50905. class WebXRDepthSensing {
  50906. /**
  50907. * Constructs a new depth sensing module.
  50908. */
  50909. constructor() {
  50910. /**
  50911. * An opaque texture representing the depth of the user's environment.
  50912. *
  50913. * @type {?ExternalTexture}
  50914. */
  50915. this.texture = null;
  50916. /**
  50917. * A plane mesh for visualizing the depth texture.
  50918. *
  50919. * @type {?Mesh}
  50920. */
  50921. this.mesh = null;
  50922. /**
  50923. * The depth near value.
  50924. *
  50925. * @type {number}
  50926. */
  50927. this.depthNear = 0;
  50928. /**
  50929. * The depth near far.
  50930. *
  50931. * @type {number}
  50932. */
  50933. this.depthFar = 0;
  50934. }
  50935. /**
  50936. * Inits the depth sensing module
  50937. *
  50938. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  50939. * @param {XRRenderState} renderState - The XR render state.
  50940. */
  50941. init( depthData, renderState ) {
  50942. if ( this.texture === null ) {
  50943. const texture = new ExternalTexture( depthData.texture );
  50944. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  50945. this.depthNear = depthData.depthNear;
  50946. this.depthFar = depthData.depthFar;
  50947. }
  50948. this.texture = texture;
  50949. }
  50950. }
  50951. /**
  50952. * Returns a plane mesh that visualizes the depth texture.
  50953. *
  50954. * @param {ArrayCamera} cameraXR - The XR camera.
  50955. * @return {?Mesh} The plane mesh.
  50956. */
  50957. getMesh( cameraXR ) {
  50958. if ( this.texture !== null ) {
  50959. if ( this.mesh === null ) {
  50960. const viewport = cameraXR.cameras[ 0 ].viewport;
  50961. const material = new ShaderMaterial( {
  50962. vertexShader: _occlusion_vertex,
  50963. fragmentShader: _occlusion_fragment,
  50964. uniforms: {
  50965. depthColor: { value: this.texture },
  50966. depthWidth: { value: viewport.z },
  50967. depthHeight: { value: viewport.w }
  50968. }
  50969. } );
  50970. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  50971. }
  50972. }
  50973. return this.mesh;
  50974. }
  50975. /**
  50976. * Resets the module
  50977. */
  50978. reset() {
  50979. this.texture = null;
  50980. this.mesh = null;
  50981. }
  50982. /**
  50983. * Returns a texture representing the depth of the user's environment.
  50984. *
  50985. * @return {?ExternalTexture} The depth texture.
  50986. */
  50987. getDepthTexture() {
  50988. return this.texture;
  50989. }
  50990. }
  50991. /**
  50992. * This class represents an abstraction of the WebXR Device API and is
  50993. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  50994. * interface that allows users to enable/disable XR and perform XR related
  50995. * tasks like for instance retrieving controllers.
  50996. *
  50997. * @augments EventDispatcher
  50998. * @hideconstructor
  50999. */
  51000. class WebXRManager extends EventDispatcher {
  51001. /**
  51002. * Constructs a new WebGL renderer.
  51003. *
  51004. * @param {WebGLRenderer} renderer - The renderer.
  51005. * @param {WebGL2RenderingContext} gl - The rendering context.
  51006. */
  51007. constructor( renderer, gl ) {
  51008. super();
  51009. const scope = this;
  51010. let session = null;
  51011. let framebufferScaleFactor = 1.0;
  51012. let referenceSpace = null;
  51013. let referenceSpaceType = 'local-floor';
  51014. // Set default foveation to maximum.
  51015. let foveation = 1.0;
  51016. let customReferenceSpace = null;
  51017. let pose = null;
  51018. let glBinding = null;
  51019. let glProjLayer = null;
  51020. let glBaseLayer = null;
  51021. let xrFrame = null;
  51022. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  51023. const depthSensing = new WebXRDepthSensing();
  51024. const cameraAccessTextures = {};
  51025. const attributes = gl.getContextAttributes();
  51026. let initialRenderTarget = null;
  51027. let newRenderTarget = null;
  51028. const controllers = [];
  51029. const controllerInputSources = [];
  51030. const currentSize = new Vector2();
  51031. let currentPixelRatio = null;
  51032. //
  51033. const cameraL = new PerspectiveCamera();
  51034. cameraL.viewport = new Vector4();
  51035. const cameraR = new PerspectiveCamera();
  51036. cameraR.viewport = new Vector4();
  51037. const cameras = [ cameraL, cameraR ];
  51038. const cameraXR = new ArrayCamera();
  51039. let _currentDepthNear = null;
  51040. let _currentDepthFar = null;
  51041. //
  51042. /**
  51043. * Whether the manager's XR camera should be automatically updated or not.
  51044. *
  51045. * @type {boolean}
  51046. * @default true
  51047. */
  51048. this.cameraAutoUpdate = true;
  51049. /**
  51050. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  51051. * if you are going to use XR in your app.
  51052. *
  51053. * @type {boolean}
  51054. * @default false
  51055. */
  51056. this.enabled = false;
  51057. /**
  51058. * Whether XR presentation is active or not.
  51059. *
  51060. * @type {boolean}
  51061. * @readonly
  51062. * @default false
  51063. */
  51064. this.isPresenting = false;
  51065. /**
  51066. * Returns a group representing the `target ray` space of the XR controller.
  51067. * Use this space for visualizing 3D objects that support the user in pointing
  51068. * tasks like UI interaction.
  51069. *
  51070. * @param {number} index - The index of the controller.
  51071. * @return {Group} A group representing the `target ray` space.
  51072. */
  51073. this.getController = function ( index ) {
  51074. let controller = controllers[ index ];
  51075. if ( controller === undefined ) {
  51076. controller = new WebXRController();
  51077. controllers[ index ] = controller;
  51078. }
  51079. return controller.getTargetRaySpace();
  51080. };
  51081. /**
  51082. * Returns a group representing the `grip` space of the XR controller.
  51083. * Use this space for visualizing 3D objects that support the user in pointing
  51084. * tasks like UI interaction.
  51085. *
  51086. * Note: If you want to show something in the user's hand AND offer a
  51087. * pointing ray at the same time, you'll want to attached the handheld object
  51088. * to the group returned by `getControllerGrip()` and the ray to the
  51089. * group returned by `getController()`. The idea is to have two
  51090. * different groups in two different coordinate spaces for the same WebXR
  51091. * controller.
  51092. *
  51093. * @param {number} index - The index of the controller.
  51094. * @return {Group} A group representing the `grip` space.
  51095. */
  51096. this.getControllerGrip = function ( index ) {
  51097. let controller = controllers[ index ];
  51098. if ( controller === undefined ) {
  51099. controller = new WebXRController();
  51100. controllers[ index ] = controller;
  51101. }
  51102. return controller.getGripSpace();
  51103. };
  51104. /**
  51105. * Returns a group representing the `hand` space of the XR controller.
  51106. * Use this space for visualizing 3D objects that support the user in pointing
  51107. * tasks like UI interaction.
  51108. *
  51109. * @param {number} index - The index of the controller.
  51110. * @return {Group} A group representing the `hand` space.
  51111. */
  51112. this.getHand = function ( index ) {
  51113. let controller = controllers[ index ];
  51114. if ( controller === undefined ) {
  51115. controller = new WebXRController();
  51116. controllers[ index ] = controller;
  51117. }
  51118. return controller.getHandSpace();
  51119. };
  51120. //
  51121. function onSessionEvent( event ) {
  51122. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  51123. if ( controllerIndex === -1 ) {
  51124. return;
  51125. }
  51126. const controller = controllers[ controllerIndex ];
  51127. if ( controller !== undefined ) {
  51128. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  51129. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  51130. }
  51131. }
  51132. function onSessionEnd() {
  51133. session.removeEventListener( 'select', onSessionEvent );
  51134. session.removeEventListener( 'selectstart', onSessionEvent );
  51135. session.removeEventListener( 'selectend', onSessionEvent );
  51136. session.removeEventListener( 'squeeze', onSessionEvent );
  51137. session.removeEventListener( 'squeezestart', onSessionEvent );
  51138. session.removeEventListener( 'squeezeend', onSessionEvent );
  51139. session.removeEventListener( 'end', onSessionEnd );
  51140. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  51141. for ( let i = 0; i < controllers.length; i ++ ) {
  51142. const inputSource = controllerInputSources[ i ];
  51143. if ( inputSource === null ) continue;
  51144. controllerInputSources[ i ] = null;
  51145. controllers[ i ].disconnect( inputSource );
  51146. }
  51147. _currentDepthNear = null;
  51148. _currentDepthFar = null;
  51149. depthSensing.reset();
  51150. for ( const key in cameraAccessTextures ) {
  51151. delete cameraAccessTextures[ key ];
  51152. }
  51153. // restore framebuffer/rendering state
  51154. renderer.setRenderTarget( initialRenderTarget );
  51155. glBaseLayer = null;
  51156. glProjLayer = null;
  51157. glBinding = null;
  51158. session = null;
  51159. newRenderTarget = null;
  51160. //
  51161. animation.stop();
  51162. scope.isPresenting = false;
  51163. renderer.setPixelRatio( currentPixelRatio );
  51164. renderer.setSize( currentSize.width, currentSize.height, false );
  51165. scope.dispatchEvent( { type: 'sessionend' } );
  51166. }
  51167. /**
  51168. * Sets the framebuffer scale factor.
  51169. *
  51170. * This method can not be used during a XR session.
  51171. *
  51172. * @param {number} value - The framebuffer scale factor.
  51173. */
  51174. this.setFramebufferScaleFactor = function ( value ) {
  51175. framebufferScaleFactor = value;
  51176. if ( scope.isPresenting === true ) {
  51177. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  51178. }
  51179. };
  51180. /**
  51181. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  51182. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  51183. * improve tracking. Default is `local-floor`. Valid values can be found here
  51184. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  51185. *
  51186. * This method can not be used during a XR session.
  51187. *
  51188. * @param {string} value - The reference space type.
  51189. */
  51190. this.setReferenceSpaceType = function ( value ) {
  51191. referenceSpaceType = value;
  51192. if ( scope.isPresenting === true ) {
  51193. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  51194. }
  51195. };
  51196. /**
  51197. * Returns the XR reference space.
  51198. *
  51199. * @return {XRReferenceSpace} The XR reference space.
  51200. */
  51201. this.getReferenceSpace = function () {
  51202. return customReferenceSpace || referenceSpace;
  51203. };
  51204. /**
  51205. * Sets a custom XR reference space.
  51206. *
  51207. * @param {XRReferenceSpace} space - The XR reference space.
  51208. */
  51209. this.setReferenceSpace = function ( space ) {
  51210. customReferenceSpace = space;
  51211. };
  51212. /**
  51213. * Returns the current base layer.
  51214. *
  51215. * This is an `XRProjectionLayer` when the targeted XR device supports the
  51216. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  51217. *
  51218. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  51219. */
  51220. this.getBaseLayer = function () {
  51221. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  51222. };
  51223. /**
  51224. * Returns the current XR binding.
  51225. *
  51226. * Creates a new binding if needed and the browser is
  51227. * capable of doing so.
  51228. *
  51229. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  51230. */
  51231. this.getBinding = function () {
  51232. if ( glBinding === null && supportsGlBinding ) {
  51233. glBinding = new XRWebGLBinding( session, gl );
  51234. }
  51235. return glBinding;
  51236. };
  51237. /**
  51238. * Returns the current XR frame.
  51239. *
  51240. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  51241. */
  51242. this.getFrame = function () {
  51243. return xrFrame;
  51244. };
  51245. /**
  51246. * Returns the current XR session.
  51247. *
  51248. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  51249. */
  51250. this.getSession = function () {
  51251. return session;
  51252. };
  51253. /**
  51254. * After a XR session has been requested usually with one of the `*Button` modules, it
  51255. * is injected into the renderer with this method. This method triggers the start of
  51256. * the actual XR rendering.
  51257. *
  51258. * @async
  51259. * @param {XRSession} value - The XR session to set.
  51260. * @return {Promise} A Promise that resolves when the session has been set.
  51261. */
  51262. this.setSession = async function ( value ) {
  51263. session = value;
  51264. if ( session !== null ) {
  51265. initialRenderTarget = renderer.getRenderTarget();
  51266. session.addEventListener( 'select', onSessionEvent );
  51267. session.addEventListener( 'selectstart', onSessionEvent );
  51268. session.addEventListener( 'selectend', onSessionEvent );
  51269. session.addEventListener( 'squeeze', onSessionEvent );
  51270. session.addEventListener( 'squeezestart', onSessionEvent );
  51271. session.addEventListener( 'squeezeend', onSessionEvent );
  51272. session.addEventListener( 'end', onSessionEnd );
  51273. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  51274. if ( attributes.xrCompatible !== true ) {
  51275. await gl.makeXRCompatible();
  51276. }
  51277. currentPixelRatio = renderer.getPixelRatio();
  51278. renderer.getSize( currentSize );
  51279. // Check that the browser implements the necessary APIs to use an
  51280. // XRProjectionLayer rather than an XRWebGLLayer
  51281. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  51282. if ( ! supportsLayers ) {
  51283. const layerInit = {
  51284. antialias: attributes.antialias,
  51285. alpha: true,
  51286. depth: attributes.depth,
  51287. stencil: attributes.stencil,
  51288. framebufferScaleFactor: framebufferScaleFactor
  51289. };
  51290. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  51291. session.updateRenderState( { baseLayer: glBaseLayer } );
  51292. renderer.setPixelRatio( 1 );
  51293. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  51294. newRenderTarget = new WebGLRenderTarget(
  51295. glBaseLayer.framebufferWidth,
  51296. glBaseLayer.framebufferHeight,
  51297. {
  51298. format: RGBAFormat,
  51299. type: UnsignedByteType,
  51300. colorSpace: renderer.outputColorSpace,
  51301. stencilBuffer: attributes.stencil,
  51302. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  51303. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  51304. }
  51305. );
  51306. } else {
  51307. let depthFormat = null;
  51308. let depthType = null;
  51309. let glDepthFormat = null;
  51310. if ( attributes.depth ) {
  51311. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51312. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  51313. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  51314. }
  51315. const projectionlayerInit = {
  51316. colorFormat: gl.RGBA8,
  51317. depthFormat: glDepthFormat,
  51318. scaleFactor: framebufferScaleFactor
  51319. };
  51320. glBinding = this.getBinding();
  51321. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  51322. session.updateRenderState( { layers: [ glProjLayer ] } );
  51323. renderer.setPixelRatio( 1 );
  51324. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  51325. newRenderTarget = new WebGLRenderTarget(
  51326. glProjLayer.textureWidth,
  51327. glProjLayer.textureHeight,
  51328. {
  51329. format: RGBAFormat,
  51330. type: UnsignedByteType,
  51331. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  51332. stencilBuffer: attributes.stencil,
  51333. colorSpace: renderer.outputColorSpace,
  51334. samples: attributes.antialias ? 4 : 0,
  51335. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  51336. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  51337. } );
  51338. }
  51339. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  51340. this.setFoveation( foveation );
  51341. customReferenceSpace = null;
  51342. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  51343. animation.setContext( session );
  51344. animation.start();
  51345. scope.isPresenting = true;
  51346. scope.dispatchEvent( { type: 'sessionstart' } );
  51347. }
  51348. };
  51349. /**
  51350. * Returns the environment blend mode from the current XR session.
  51351. *
  51352. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  51353. */
  51354. this.getEnvironmentBlendMode = function () {
  51355. if ( session !== null ) {
  51356. return session.environmentBlendMode;
  51357. }
  51358. };
  51359. /**
  51360. * Returns the current depth texture computed via depth sensing.
  51361. *
  51362. * See {@link WebXRDepthSensing#getDepthTexture}.
  51363. *
  51364. * @return {?Texture} The depth texture.
  51365. */
  51366. this.getDepthTexture = function () {
  51367. return depthSensing.getDepthTexture();
  51368. };
  51369. function onInputSourcesChange( event ) {
  51370. // Notify disconnected
  51371. for ( let i = 0; i < event.removed.length; i ++ ) {
  51372. const inputSource = event.removed[ i ];
  51373. const index = controllerInputSources.indexOf( inputSource );
  51374. if ( index >= 0 ) {
  51375. controllerInputSources[ index ] = null;
  51376. controllers[ index ].disconnect( inputSource );
  51377. }
  51378. }
  51379. // Notify connected
  51380. for ( let i = 0; i < event.added.length; i ++ ) {
  51381. const inputSource = event.added[ i ];
  51382. let controllerIndex = controllerInputSources.indexOf( inputSource );
  51383. if ( controllerIndex === -1 ) {
  51384. // Assign input source a controller that currently has no input source
  51385. for ( let i = 0; i < controllers.length; i ++ ) {
  51386. if ( i >= controllerInputSources.length ) {
  51387. controllerInputSources.push( inputSource );
  51388. controllerIndex = i;
  51389. break;
  51390. } else if ( controllerInputSources[ i ] === null ) {
  51391. controllerInputSources[ i ] = inputSource;
  51392. controllerIndex = i;
  51393. break;
  51394. }
  51395. }
  51396. // If all controllers do currently receive input we ignore new ones
  51397. if ( controllerIndex === -1 ) break;
  51398. }
  51399. const controller = controllers[ controllerIndex ];
  51400. if ( controller ) {
  51401. controller.connect( inputSource );
  51402. }
  51403. }
  51404. }
  51405. //
  51406. const cameraLPos = new Vector3();
  51407. const cameraRPos = new Vector3();
  51408. /**
  51409. * Assumes 2 cameras that are parallel and share an X-axis, and that
  51410. * the cameras' projection and world matrices have already been set.
  51411. * And that near and far planes are identical for both cameras.
  51412. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  51413. *
  51414. * @param {ArrayCamera} camera - The camera to update.
  51415. * @param {PerspectiveCamera} cameraL - The left camera.
  51416. * @param {PerspectiveCamera} cameraR - The right camera.
  51417. */
  51418. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  51419. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  51420. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  51421. const ipd = cameraLPos.distanceTo( cameraRPos );
  51422. const projL = cameraL.projectionMatrix.elements;
  51423. const projR = cameraR.projectionMatrix.elements;
  51424. // VR systems will have identical far and near planes, and
  51425. // most likely identical top and bottom frustum extents.
  51426. // Use the left camera for these values.
  51427. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  51428. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  51429. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  51430. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  51431. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  51432. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  51433. const left = near * leftFov;
  51434. const right = near * rightFov;
  51435. // Calculate the new camera's position offset from the
  51436. // left camera. xOffset should be roughly half `ipd`.
  51437. const zOffset = ipd / ( - leftFov + rightFov );
  51438. const xOffset = zOffset * - leftFov;
  51439. // TODO: Better way to apply this offset?
  51440. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  51441. camera.translateX( xOffset );
  51442. camera.translateZ( zOffset );
  51443. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  51444. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51445. // Check if the projection uses an infinite far plane.
  51446. if ( projL[ 10 ] === -1 ) {
  51447. // Use the projection matrix from the left eye.
  51448. // The camera offset is sufficient to include the view volumes
  51449. // of both eyes (assuming symmetric projections).
  51450. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  51451. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  51452. } else {
  51453. // Find the union of the frustum values of the cameras and scale
  51454. // the values so that the near plane's position does not change in world space,
  51455. // although must now be relative to the new union camera.
  51456. const near2 = near + zOffset;
  51457. const far2 = far + zOffset;
  51458. const left2 = left - xOffset;
  51459. const right2 = right + ( ipd - xOffset );
  51460. const top2 = topFov * far / far2 * near2;
  51461. const bottom2 = bottomFov * far / far2 * near2;
  51462. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  51463. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51464. }
  51465. }
  51466. function updateCamera( camera, parent ) {
  51467. if ( parent === null ) {
  51468. camera.matrixWorld.copy( camera.matrix );
  51469. } else {
  51470. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  51471. }
  51472. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51473. }
  51474. /**
  51475. * Updates the state of the XR camera. Use this method on app level if you
  51476. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  51477. * camera of the scene as a parameter. The passed in camera's transformation
  51478. * is automatically adjusted to the position of the XR camera when calling
  51479. * this method.
  51480. *
  51481. * @param {Camera} camera - The camera.
  51482. */
  51483. this.updateCamera = function ( camera ) {
  51484. if ( session === null ) return;
  51485. let depthNear = camera.near;
  51486. let depthFar = camera.far;
  51487. if ( depthSensing.texture !== null ) {
  51488. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  51489. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  51490. }
  51491. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  51492. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  51493. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  51494. // Note that the new renderState won't apply until the next frame. See #18320
  51495. session.updateRenderState( {
  51496. depthNear: cameraXR.near,
  51497. depthFar: cameraXR.far
  51498. } );
  51499. _currentDepthNear = cameraXR.near;
  51500. _currentDepthFar = cameraXR.far;
  51501. }
  51502. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  51503. cameraXR.layers.mask = camera.layers.mask | 0b110;
  51504. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  51505. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  51506. const parent = camera.parent;
  51507. const cameras = cameraXR.cameras;
  51508. updateCamera( cameraXR, parent );
  51509. for ( let i = 0; i < cameras.length; i ++ ) {
  51510. updateCamera( cameras[ i ], parent );
  51511. }
  51512. // update projection matrix for proper view frustum culling
  51513. if ( cameras.length === 2 ) {
  51514. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  51515. } else {
  51516. // assume single camera setup (AR)
  51517. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  51518. }
  51519. // update user camera and its children
  51520. updateUserCamera( camera, cameraXR, parent );
  51521. };
  51522. function updateUserCamera( camera, cameraXR, parent ) {
  51523. if ( parent === null ) {
  51524. camera.matrix.copy( cameraXR.matrixWorld );
  51525. } else {
  51526. camera.matrix.copy( parent.matrixWorld );
  51527. camera.matrix.invert();
  51528. camera.matrix.multiply( cameraXR.matrixWorld );
  51529. }
  51530. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51531. camera.updateMatrixWorld( true );
  51532. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  51533. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  51534. if ( camera.isPerspectiveCamera ) {
  51535. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  51536. camera.zoom = 1;
  51537. }
  51538. }
  51539. /**
  51540. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  51541. * of the active XR session. For each view it holds a separate camera object.
  51542. *
  51543. * The camera's `fov` is currently not used and does not reflect the fov of
  51544. * the XR camera. If you need the fov on app level, you have to compute in
  51545. * manually from the XR camera's projection matrices.
  51546. *
  51547. * @return {ArrayCamera} The XR camera.
  51548. */
  51549. this.getCamera = function () {
  51550. return cameraXR;
  51551. };
  51552. /**
  51553. * Returns the amount of foveation used by the XR compositor for the projection layer.
  51554. *
  51555. * @return {number|undefined} The amount of foveation.
  51556. */
  51557. this.getFoveation = function () {
  51558. if ( glProjLayer === null && glBaseLayer === null ) {
  51559. return undefined;
  51560. }
  51561. return foveation;
  51562. };
  51563. /**
  51564. * Sets the foveation value.
  51565. *
  51566. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  51567. * and `1` means maximum foveation (the edges render at lower resolution).
  51568. */
  51569. this.setFoveation = function ( value ) {
  51570. // 0 = no foveation = full resolution
  51571. // 1 = maximum foveation = the edges render at lower resolution
  51572. foveation = value;
  51573. if ( glProjLayer !== null ) {
  51574. glProjLayer.fixedFoveation = value;
  51575. }
  51576. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  51577. glBaseLayer.fixedFoveation = value;
  51578. }
  51579. };
  51580. /**
  51581. * Returns `true` if depth sensing is supported.
  51582. *
  51583. * @return {boolean} Whether depth sensing is supported or not.
  51584. */
  51585. this.hasDepthSensing = function () {
  51586. return depthSensing.texture !== null;
  51587. };
  51588. /**
  51589. * Returns the depth sensing mesh.
  51590. *
  51591. * See {@link WebXRDepthSensing#getMesh}.
  51592. *
  51593. * @return {Mesh} The depth sensing mesh.
  51594. */
  51595. this.getDepthSensingMesh = function () {
  51596. return depthSensing.getMesh( cameraXR );
  51597. };
  51598. /**
  51599. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  51600. * Only available during the current animation loop.
  51601. *
  51602. * @param {XRCamera} xrCamera - The camera to query.
  51603. * @return {?Texture} An opaque texture representing the current raw camera frame.
  51604. */
  51605. this.getCameraTexture = function ( xrCamera ) {
  51606. return cameraAccessTextures[ xrCamera ];
  51607. };
  51608. // Animation Loop
  51609. let onAnimationFrameCallback = null;
  51610. function onAnimationFrame( time, frame ) {
  51611. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  51612. xrFrame = frame;
  51613. if ( pose !== null ) {
  51614. const views = pose.views;
  51615. if ( glBaseLayer !== null ) {
  51616. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  51617. renderer.setRenderTarget( newRenderTarget );
  51618. }
  51619. let cameraXRNeedsUpdate = false;
  51620. // check if it's necessary to rebuild cameraXR's camera list
  51621. if ( views.length !== cameraXR.cameras.length ) {
  51622. cameraXR.cameras.length = 0;
  51623. cameraXRNeedsUpdate = true;
  51624. }
  51625. for ( let i = 0; i < views.length; i ++ ) {
  51626. const view = views[ i ];
  51627. let viewport = null;
  51628. if ( glBaseLayer !== null ) {
  51629. viewport = glBaseLayer.getViewport( view );
  51630. } else {
  51631. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  51632. viewport = glSubImage.viewport;
  51633. // For side-by-side projection, we only produce a single texture for both eyes.
  51634. if ( i === 0 ) {
  51635. renderer.setRenderTargetTextures(
  51636. newRenderTarget,
  51637. glSubImage.colorTexture,
  51638. glSubImage.depthStencilTexture );
  51639. renderer.setRenderTarget( newRenderTarget );
  51640. }
  51641. }
  51642. let camera = cameras[ i ];
  51643. if ( camera === undefined ) {
  51644. camera = new PerspectiveCamera();
  51645. camera.layers.enable( i );
  51646. camera.viewport = new Vector4();
  51647. cameras[ i ] = camera;
  51648. }
  51649. camera.matrix.fromArray( view.transform.matrix );
  51650. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51651. camera.projectionMatrix.fromArray( view.projectionMatrix );
  51652. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51653. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  51654. if ( i === 0 ) {
  51655. cameraXR.matrix.copy( camera.matrix );
  51656. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  51657. }
  51658. if ( cameraXRNeedsUpdate === true ) {
  51659. cameraXR.cameras.push( camera );
  51660. }
  51661. }
  51662. //
  51663. const enabledFeatures = session.enabledFeatures;
  51664. const gpuDepthSensingEnabled = enabledFeatures &&
  51665. enabledFeatures.includes( 'depth-sensing' ) &&
  51666. session.depthUsage == 'gpu-optimized';
  51667. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  51668. glBinding = scope.getBinding();
  51669. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51670. if ( depthData && depthData.isValid && depthData.texture ) {
  51671. depthSensing.init( depthData, session.renderState );
  51672. }
  51673. }
  51674. const cameraAccessEnabled = enabledFeatures &&
  51675. enabledFeatures.includes( 'camera-access' );
  51676. if ( cameraAccessEnabled && supportsGlBinding ) {
  51677. renderer.state.unbindTexture();
  51678. glBinding = scope.getBinding();
  51679. for ( let i = 0; i < views.length; i ++ ) {
  51680. const camera = views[ i ].camera;
  51681. if ( camera ) {
  51682. let cameraTex = cameraAccessTextures[ camera ];
  51683. if ( ! cameraTex ) {
  51684. cameraTex = new ExternalTexture();
  51685. cameraAccessTextures[ camera ] = cameraTex;
  51686. }
  51687. const glTexture = glBinding.getCameraImage( camera );
  51688. cameraTex.sourceTexture = glTexture;
  51689. }
  51690. }
  51691. }
  51692. }
  51693. //
  51694. for ( let i = 0; i < controllers.length; i ++ ) {
  51695. const inputSource = controllerInputSources[ i ];
  51696. const controller = controllers[ i ];
  51697. if ( inputSource !== null && controller !== undefined ) {
  51698. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51699. }
  51700. }
  51701. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51702. if ( frame.detectedPlanes ) {
  51703. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51704. }
  51705. xrFrame = null;
  51706. }
  51707. const animation = new WebGLAnimation();
  51708. animation.setAnimationLoop( onAnimationFrame );
  51709. this.setAnimationLoop = function ( callback ) {
  51710. onAnimationFrameCallback = callback;
  51711. };
  51712. this.dispose = function () {};
  51713. }
  51714. }
  51715. const _e1 = /*@__PURE__*/ new Euler();
  51716. const _m1 = /*@__PURE__*/ new Matrix4();
  51717. function WebGLMaterials( renderer, properties ) {
  51718. function refreshTransformUniform( map, uniform ) {
  51719. if ( map.matrixAutoUpdate === true ) {
  51720. map.updateMatrix();
  51721. }
  51722. uniform.value.copy( map.matrix );
  51723. }
  51724. function refreshFogUniforms( uniforms, fog ) {
  51725. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51726. if ( fog.isFog ) {
  51727. uniforms.fogNear.value = fog.near;
  51728. uniforms.fogFar.value = fog.far;
  51729. } else if ( fog.isFogExp2 ) {
  51730. uniforms.fogDensity.value = fog.density;
  51731. }
  51732. }
  51733. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51734. if ( material.isMeshBasicMaterial ) {
  51735. refreshUniformsCommon( uniforms, material );
  51736. } else if ( material.isMeshLambertMaterial ) {
  51737. refreshUniformsCommon( uniforms, material );
  51738. } else if ( material.isMeshToonMaterial ) {
  51739. refreshUniformsCommon( uniforms, material );
  51740. refreshUniformsToon( uniforms, material );
  51741. } else if ( material.isMeshPhongMaterial ) {
  51742. refreshUniformsCommon( uniforms, material );
  51743. refreshUniformsPhong( uniforms, material );
  51744. } else if ( material.isMeshStandardMaterial ) {
  51745. refreshUniformsCommon( uniforms, material );
  51746. refreshUniformsStandard( uniforms, material );
  51747. if ( material.isMeshPhysicalMaterial ) {
  51748. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51749. }
  51750. } else if ( material.isMeshMatcapMaterial ) {
  51751. refreshUniformsCommon( uniforms, material );
  51752. refreshUniformsMatcap( uniforms, material );
  51753. } else if ( material.isMeshDepthMaterial ) {
  51754. refreshUniformsCommon( uniforms, material );
  51755. } else if ( material.isMeshDistanceMaterial ) {
  51756. refreshUniformsCommon( uniforms, material );
  51757. refreshUniformsDistance( uniforms, material );
  51758. } else if ( material.isMeshNormalMaterial ) {
  51759. refreshUniformsCommon( uniforms, material );
  51760. } else if ( material.isLineBasicMaterial ) {
  51761. refreshUniformsLine( uniforms, material );
  51762. if ( material.isLineDashedMaterial ) {
  51763. refreshUniformsDash( uniforms, material );
  51764. }
  51765. } else if ( material.isPointsMaterial ) {
  51766. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51767. } else if ( material.isSpriteMaterial ) {
  51768. refreshUniformsSprites( uniforms, material );
  51769. } else if ( material.isShadowMaterial ) {
  51770. uniforms.color.value.copy( material.color );
  51771. uniforms.opacity.value = material.opacity;
  51772. } else if ( material.isShaderMaterial ) {
  51773. material.uniformsNeedUpdate = false; // #15581
  51774. }
  51775. }
  51776. function refreshUniformsCommon( uniforms, material ) {
  51777. uniforms.opacity.value = material.opacity;
  51778. if ( material.color ) {
  51779. uniforms.diffuse.value.copy( material.color );
  51780. }
  51781. if ( material.emissive ) {
  51782. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51783. }
  51784. if ( material.map ) {
  51785. uniforms.map.value = material.map;
  51786. refreshTransformUniform( material.map, uniforms.mapTransform );
  51787. }
  51788. if ( material.alphaMap ) {
  51789. uniforms.alphaMap.value = material.alphaMap;
  51790. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51791. }
  51792. if ( material.bumpMap ) {
  51793. uniforms.bumpMap.value = material.bumpMap;
  51794. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51795. uniforms.bumpScale.value = material.bumpScale;
  51796. if ( material.side === BackSide ) {
  51797. uniforms.bumpScale.value *= -1;
  51798. }
  51799. }
  51800. if ( material.normalMap ) {
  51801. uniforms.normalMap.value = material.normalMap;
  51802. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51803. uniforms.normalScale.value.copy( material.normalScale );
  51804. if ( material.side === BackSide ) {
  51805. uniforms.normalScale.value.negate();
  51806. }
  51807. }
  51808. if ( material.displacementMap ) {
  51809. uniforms.displacementMap.value = material.displacementMap;
  51810. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51811. uniforms.displacementScale.value = material.displacementScale;
  51812. uniforms.displacementBias.value = material.displacementBias;
  51813. }
  51814. if ( material.emissiveMap ) {
  51815. uniforms.emissiveMap.value = material.emissiveMap;
  51816. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51817. }
  51818. if ( material.specularMap ) {
  51819. uniforms.specularMap.value = material.specularMap;
  51820. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51821. }
  51822. if ( material.alphaTest > 0 ) {
  51823. uniforms.alphaTest.value = material.alphaTest;
  51824. }
  51825. const materialProperties = properties.get( material );
  51826. const envMap = materialProperties.envMap;
  51827. const envMapRotation = materialProperties.envMapRotation;
  51828. if ( envMap ) {
  51829. uniforms.envMap.value = envMap;
  51830. _e1.copy( envMapRotation );
  51831. // accommodate left-handed frame
  51832. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51833. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51834. // environment maps which are not cube render targets or PMREMs follow a different convention
  51835. _e1.y *= -1;
  51836. _e1.z *= -1;
  51837. }
  51838. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51839. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51840. uniforms.reflectivity.value = material.reflectivity;
  51841. uniforms.ior.value = material.ior;
  51842. uniforms.refractionRatio.value = material.refractionRatio;
  51843. }
  51844. if ( material.lightMap ) {
  51845. uniforms.lightMap.value = material.lightMap;
  51846. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51847. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51848. }
  51849. if ( material.aoMap ) {
  51850. uniforms.aoMap.value = material.aoMap;
  51851. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51852. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51853. }
  51854. }
  51855. function refreshUniformsLine( uniforms, material ) {
  51856. uniforms.diffuse.value.copy( material.color );
  51857. uniforms.opacity.value = material.opacity;
  51858. if ( material.map ) {
  51859. uniforms.map.value = material.map;
  51860. refreshTransformUniform( material.map, uniforms.mapTransform );
  51861. }
  51862. }
  51863. function refreshUniformsDash( uniforms, material ) {
  51864. uniforms.dashSize.value = material.dashSize;
  51865. uniforms.totalSize.value = material.dashSize + material.gapSize;
  51866. uniforms.scale.value = material.scale;
  51867. }
  51868. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  51869. uniforms.diffuse.value.copy( material.color );
  51870. uniforms.opacity.value = material.opacity;
  51871. uniforms.size.value = material.size * pixelRatio;
  51872. uniforms.scale.value = height * 0.5;
  51873. if ( material.map ) {
  51874. uniforms.map.value = material.map;
  51875. refreshTransformUniform( material.map, uniforms.uvTransform );
  51876. }
  51877. if ( material.alphaMap ) {
  51878. uniforms.alphaMap.value = material.alphaMap;
  51879. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51880. }
  51881. if ( material.alphaTest > 0 ) {
  51882. uniforms.alphaTest.value = material.alphaTest;
  51883. }
  51884. }
  51885. function refreshUniformsSprites( uniforms, material ) {
  51886. uniforms.diffuse.value.copy( material.color );
  51887. uniforms.opacity.value = material.opacity;
  51888. uniforms.rotation.value = material.rotation;
  51889. if ( material.map ) {
  51890. uniforms.map.value = material.map;
  51891. refreshTransformUniform( material.map, uniforms.mapTransform );
  51892. }
  51893. if ( material.alphaMap ) {
  51894. uniforms.alphaMap.value = material.alphaMap;
  51895. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51896. }
  51897. if ( material.alphaTest > 0 ) {
  51898. uniforms.alphaTest.value = material.alphaTest;
  51899. }
  51900. }
  51901. function refreshUniformsPhong( uniforms, material ) {
  51902. uniforms.specular.value.copy( material.specular );
  51903. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  51904. }
  51905. function refreshUniformsToon( uniforms, material ) {
  51906. if ( material.gradientMap ) {
  51907. uniforms.gradientMap.value = material.gradientMap;
  51908. }
  51909. }
  51910. function refreshUniformsStandard( uniforms, material ) {
  51911. uniforms.metalness.value = material.metalness;
  51912. if ( material.metalnessMap ) {
  51913. uniforms.metalnessMap.value = material.metalnessMap;
  51914. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  51915. }
  51916. uniforms.roughness.value = material.roughness;
  51917. if ( material.roughnessMap ) {
  51918. uniforms.roughnessMap.value = material.roughnessMap;
  51919. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  51920. }
  51921. if ( material.envMap ) {
  51922. //uniforms.envMap.value = material.envMap; // part of uniforms common
  51923. uniforms.envMapIntensity.value = material.envMapIntensity;
  51924. }
  51925. }
  51926. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  51927. uniforms.ior.value = material.ior; // also part of uniforms common
  51928. if ( material.sheen > 0 ) {
  51929. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  51930. uniforms.sheenRoughness.value = material.sheenRoughness;
  51931. if ( material.sheenColorMap ) {
  51932. uniforms.sheenColorMap.value = material.sheenColorMap;
  51933. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  51934. }
  51935. if ( material.sheenRoughnessMap ) {
  51936. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  51937. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  51938. }
  51939. }
  51940. if ( material.clearcoat > 0 ) {
  51941. uniforms.clearcoat.value = material.clearcoat;
  51942. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  51943. if ( material.clearcoatMap ) {
  51944. uniforms.clearcoatMap.value = material.clearcoatMap;
  51945. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  51946. }
  51947. if ( material.clearcoatRoughnessMap ) {
  51948. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  51949. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  51950. }
  51951. if ( material.clearcoatNormalMap ) {
  51952. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  51953. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  51954. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  51955. if ( material.side === BackSide ) {
  51956. uniforms.clearcoatNormalScale.value.negate();
  51957. }
  51958. }
  51959. }
  51960. if ( material.dispersion > 0 ) {
  51961. uniforms.dispersion.value = material.dispersion;
  51962. }
  51963. if ( material.iridescence > 0 ) {
  51964. uniforms.iridescence.value = material.iridescence;
  51965. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  51966. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  51967. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  51968. if ( material.iridescenceMap ) {
  51969. uniforms.iridescenceMap.value = material.iridescenceMap;
  51970. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  51971. }
  51972. if ( material.iridescenceThicknessMap ) {
  51973. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  51974. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  51975. }
  51976. }
  51977. if ( material.transmission > 0 ) {
  51978. uniforms.transmission.value = material.transmission;
  51979. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  51980. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  51981. if ( material.transmissionMap ) {
  51982. uniforms.transmissionMap.value = material.transmissionMap;
  51983. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  51984. }
  51985. uniforms.thickness.value = material.thickness;
  51986. if ( material.thicknessMap ) {
  51987. uniforms.thicknessMap.value = material.thicknessMap;
  51988. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  51989. }
  51990. uniforms.attenuationDistance.value = material.attenuationDistance;
  51991. uniforms.attenuationColor.value.copy( material.attenuationColor );
  51992. }
  51993. if ( material.anisotropy > 0 ) {
  51994. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  51995. if ( material.anisotropyMap ) {
  51996. uniforms.anisotropyMap.value = material.anisotropyMap;
  51997. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  51998. }
  51999. }
  52000. uniforms.specularIntensity.value = material.specularIntensity;
  52001. uniforms.specularColor.value.copy( material.specularColor );
  52002. if ( material.specularColorMap ) {
  52003. uniforms.specularColorMap.value = material.specularColorMap;
  52004. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  52005. }
  52006. if ( material.specularIntensityMap ) {
  52007. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  52008. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  52009. }
  52010. }
  52011. function refreshUniformsMatcap( uniforms, material ) {
  52012. if ( material.matcap ) {
  52013. uniforms.matcap.value = material.matcap;
  52014. }
  52015. }
  52016. function refreshUniformsDistance( uniforms, material ) {
  52017. const light = properties.get( material ).light;
  52018. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  52019. uniforms.nearDistance.value = light.shadow.camera.near;
  52020. uniforms.farDistance.value = light.shadow.camera.far;
  52021. }
  52022. return {
  52023. refreshFogUniforms: refreshFogUniforms,
  52024. refreshMaterialUniforms: refreshMaterialUniforms
  52025. };
  52026. }
  52027. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  52028. let buffers = {};
  52029. let updateList = {};
  52030. let allocatedBindingPoints = [];
  52031. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  52032. function bind( uniformsGroup, program ) {
  52033. const webglProgram = program.program;
  52034. state.uniformBlockBinding( uniformsGroup, webglProgram );
  52035. }
  52036. function update( uniformsGroup, program ) {
  52037. let buffer = buffers[ uniformsGroup.id ];
  52038. if ( buffer === undefined ) {
  52039. prepareUniformsGroup( uniformsGroup );
  52040. buffer = createBuffer( uniformsGroup );
  52041. buffers[ uniformsGroup.id ] = buffer;
  52042. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  52043. }
  52044. // ensure to update the binding points/block indices mapping for this program
  52045. const webglProgram = program.program;
  52046. state.updateUBOMapping( uniformsGroup, webglProgram );
  52047. // update UBO once per frame
  52048. const frame = info.render.frame;
  52049. if ( updateList[ uniformsGroup.id ] !== frame ) {
  52050. updateBufferData( uniformsGroup );
  52051. updateList[ uniformsGroup.id ] = frame;
  52052. }
  52053. }
  52054. function createBuffer( uniformsGroup ) {
  52055. // the setup of an UBO is independent of a particular shader program but global
  52056. const bindingPointIndex = allocateBindingPointIndex();
  52057. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  52058. const buffer = gl.createBuffer();
  52059. const size = uniformsGroup.__size;
  52060. const usage = uniformsGroup.usage;
  52061. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52062. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  52063. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52064. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  52065. return buffer;
  52066. }
  52067. function allocateBindingPointIndex() {
  52068. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  52069. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  52070. allocatedBindingPoints.push( i );
  52071. return i;
  52072. }
  52073. }
  52074. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  52075. return 0;
  52076. }
  52077. function updateBufferData( uniformsGroup ) {
  52078. const buffer = buffers[ uniformsGroup.id ];
  52079. const uniforms = uniformsGroup.uniforms;
  52080. const cache = uniformsGroup.__cache;
  52081. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  52082. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  52083. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52084. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52085. const uniform = uniformArray[ j ];
  52086. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  52087. const offset = uniform.__offset;
  52088. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52089. let arrayOffset = 0;
  52090. for ( let k = 0; k < values.length; k ++ ) {
  52091. const value = values[ k ];
  52092. const info = getUniformSize( value );
  52093. // TODO add integer and struct support
  52094. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52095. uniform.__data[ 0 ] = value;
  52096. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  52097. } else if ( value.isMatrix3 ) {
  52098. // manually converting 3x3 to 3x4
  52099. uniform.__data[ 0 ] = value.elements[ 0 ];
  52100. uniform.__data[ 1 ] = value.elements[ 1 ];
  52101. uniform.__data[ 2 ] = value.elements[ 2 ];
  52102. uniform.__data[ 3 ] = 0;
  52103. uniform.__data[ 4 ] = value.elements[ 3 ];
  52104. uniform.__data[ 5 ] = value.elements[ 4 ];
  52105. uniform.__data[ 6 ] = value.elements[ 5 ];
  52106. uniform.__data[ 7 ] = 0;
  52107. uniform.__data[ 8 ] = value.elements[ 6 ];
  52108. uniform.__data[ 9 ] = value.elements[ 7 ];
  52109. uniform.__data[ 10 ] = value.elements[ 8 ];
  52110. uniform.__data[ 11 ] = 0;
  52111. } else {
  52112. value.toArray( uniform.__data, arrayOffset );
  52113. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  52114. }
  52115. }
  52116. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  52117. }
  52118. }
  52119. }
  52120. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  52121. }
  52122. function hasUniformChanged( uniform, index, indexArray, cache ) {
  52123. const value = uniform.value;
  52124. const indexString = index + '_' + indexArray;
  52125. if ( cache[ indexString ] === undefined ) {
  52126. // cache entry does not exist so far
  52127. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52128. cache[ indexString ] = value;
  52129. } else {
  52130. cache[ indexString ] = value.clone();
  52131. }
  52132. return true;
  52133. } else {
  52134. const cachedObject = cache[ indexString ];
  52135. // compare current value with cached entry
  52136. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52137. if ( cachedObject !== value ) {
  52138. cache[ indexString ] = value;
  52139. return true;
  52140. }
  52141. } else {
  52142. if ( cachedObject.equals( value ) === false ) {
  52143. cachedObject.copy( value );
  52144. return true;
  52145. }
  52146. }
  52147. }
  52148. return false;
  52149. }
  52150. function prepareUniformsGroup( uniformsGroup ) {
  52151. // determine total buffer size according to the STD140 layout
  52152. // Hint: STD140 is the only supported layout in WebGL 2
  52153. const uniforms = uniformsGroup.uniforms;
  52154. let offset = 0; // global buffer offset in bytes
  52155. const chunkSize = 16; // size of a chunk in bytes
  52156. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  52157. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52158. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52159. const uniform = uniformArray[ j ];
  52160. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52161. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  52162. const value = values[ k ];
  52163. const info = getUniformSize( value );
  52164. const chunkOffset = offset % chunkSize; // offset in the current chunk
  52165. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  52166. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  52167. offset += chunkPadding;
  52168. // Check for chunk overflow
  52169. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  52170. // Add padding and adjust offset
  52171. offset += ( chunkSize - chunkStart );
  52172. }
  52173. // the following two properties will be used for partial buffer updates
  52174. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  52175. uniform.__offset = offset;
  52176. // Update the global offset
  52177. offset += info.storage;
  52178. }
  52179. }
  52180. }
  52181. // ensure correct final padding
  52182. const chunkOffset = offset % chunkSize;
  52183. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  52184. //
  52185. uniformsGroup.__size = offset;
  52186. uniformsGroup.__cache = {};
  52187. return this;
  52188. }
  52189. function getUniformSize( value ) {
  52190. const info = {
  52191. boundary: 0, // bytes
  52192. storage: 0 // bytes
  52193. };
  52194. // determine sizes according to STD140
  52195. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52196. // float/int/bool
  52197. info.boundary = 4;
  52198. info.storage = 4;
  52199. } else if ( value.isVector2 ) {
  52200. // vec2
  52201. info.boundary = 8;
  52202. info.storage = 8;
  52203. } else if ( value.isVector3 || value.isColor ) {
  52204. // vec3
  52205. info.boundary = 16;
  52206. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  52207. } else if ( value.isVector4 ) {
  52208. // vec4
  52209. info.boundary = 16;
  52210. info.storage = 16;
  52211. } else if ( value.isMatrix3 ) {
  52212. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  52213. info.boundary = 48;
  52214. info.storage = 48;
  52215. } else if ( value.isMatrix4 ) {
  52216. // mat4
  52217. info.boundary = 64;
  52218. info.storage = 64;
  52219. } else if ( value.isTexture ) {
  52220. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  52221. } else {
  52222. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  52223. }
  52224. return info;
  52225. }
  52226. function onUniformsGroupsDispose( event ) {
  52227. const uniformsGroup = event.target;
  52228. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  52229. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  52230. allocatedBindingPoints.splice( index, 1 );
  52231. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  52232. delete buffers[ uniformsGroup.id ];
  52233. delete updateList[ uniformsGroup.id ];
  52234. }
  52235. function dispose() {
  52236. for ( const id in buffers ) {
  52237. gl.deleteBuffer( buffers[ id ] );
  52238. }
  52239. allocatedBindingPoints = [];
  52240. buffers = {};
  52241. updateList = {};
  52242. }
  52243. return {
  52244. bind: bind,
  52245. update: update,
  52246. dispose: dispose
  52247. };
  52248. }
  52249. /**
  52250. * Precomputed DFG LUT for Image-Based Lighting
  52251. * Resolution: 16x16
  52252. * Samples: 4096 per texel
  52253. * Format: RG16F (2 half floats per texel: scale, bias)
  52254. */
  52255. const DATA = new Uint16Array( [
  52256. 0x30b5, 0x3ad1, 0x314c, 0x3a4d, 0x33d2, 0x391c, 0x35ef, 0x3828, 0x37f3, 0x36a6, 0x38d1, 0x3539, 0x3979, 0x3410, 0x39f8, 0x3252, 0x3a53, 0x30f0, 0x3a94, 0x2fc9, 0x3abf, 0x2e35, 0x3ada, 0x2d05, 0x3ae8, 0x2c1f, 0x3aed, 0x2ae0, 0x3aea, 0x29d1, 0x3ae1, 0x28ff,
  52257. 0x3638, 0x38e4, 0x364a, 0x38ce, 0x3699, 0x385e, 0x374e, 0x372c, 0x3839, 0x35a4, 0x38dc, 0x3462, 0x396e, 0x32c4, 0x39de, 0x3134, 0x3a2b, 0x3003, 0x3a59, 0x2e3a, 0x3a6d, 0x2ce1, 0x3a6e, 0x2bba, 0x3a5f, 0x2a33, 0x3a49, 0x290a, 0x3a2d, 0x2826, 0x3a0a, 0x26e8,
  52258. 0x3894, 0x36d7, 0x3897, 0x36c9, 0x38a3, 0x3675, 0x38bc, 0x35ac, 0x38ee, 0x349c, 0x393e, 0x3332, 0x3997, 0x3186, 0x39e2, 0x3038, 0x3a13, 0x2e75, 0x3a29, 0x2cf5, 0x3a2d, 0x2bac, 0x3a21, 0x29ff, 0x3a04, 0x28bc, 0x39dc, 0x2790, 0x39ad, 0x261a, 0x3978, 0x24fa,
  52259. 0x39ac, 0x34a8, 0x39ac, 0x34a3, 0x39ae, 0x3480, 0x39ae, 0x3423, 0x39b1, 0x330e, 0x39c2, 0x31a9, 0x39e0, 0x3063, 0x39fc, 0x2eb5, 0x3a0c, 0x2d1d, 0x3a14, 0x2bcf, 0x3a07, 0x29ff, 0x39e9, 0x28a3, 0x39be, 0x273c, 0x3989, 0x25b3, 0x394a, 0x2488, 0x3907, 0x2345,
  52260. 0x3a77, 0x3223, 0x3a76, 0x321f, 0x3a73, 0x3204, 0x3a6a, 0x31b3, 0x3a58, 0x3114, 0x3a45, 0x303b, 0x3a34, 0x2eb6, 0x3a26, 0x2d31, 0x3a1e, 0x2bef, 0x3a0b, 0x2a0d, 0x39ec, 0x28a1, 0x39c0, 0x271b, 0x3987, 0x2580, 0x3944, 0x2449, 0x38fa, 0x22bd, 0x38ac, 0x2155,
  52261. 0x3b07, 0x2fca, 0x3b06, 0x2fca, 0x3b00, 0x2fb8, 0x3af4, 0x2f7c, 0x3adb, 0x2eea, 0x3ab4, 0x2e00, 0x3a85, 0x2cec, 0x3a5e, 0x2bc5, 0x3a36, 0x2a00, 0x3a0d, 0x2899, 0x39dc, 0x2707, 0x39a0, 0x2562, 0x395a, 0x2424, 0x390b, 0x2268, 0x38b7, 0x20fd, 0x385f, 0x1fd1,
  52262. 0x3b69, 0x2cb9, 0x3b68, 0x2cbb, 0x3b62, 0x2cbb, 0x3b56, 0x2cae, 0x3b3b, 0x2c78, 0x3b0d, 0x2c0a, 0x3acf, 0x2ae3, 0x3a92, 0x2998, 0x3a54, 0x2867, 0x3a17, 0x26d0, 0x39d3, 0x253c, 0x3989, 0x2402, 0x3935, 0x2226, 0x38dc, 0x20bd, 0x387d, 0x1f54, 0x381d, 0x1db3,
  52263. 0x3ba9, 0x296b, 0x3ba8, 0x296f, 0x3ba3, 0x297b, 0x3b98, 0x2987, 0x3b7f, 0x2976, 0x3b4e, 0x2927, 0x3b0e, 0x2895, 0x3ac2, 0x27b7, 0x3a73, 0x263b, 0x3a23, 0x24e7, 0x39d0, 0x239b, 0x3976, 0x21d9, 0x3917, 0x207e, 0x38b2, 0x1ee7, 0x384b, 0x1d53, 0x37c7, 0x1c1e,
  52264. 0x3bd2, 0x25cb, 0x3bd1, 0x25d3, 0x3bcd, 0x25f0, 0x3bc2, 0x261f, 0x3bad, 0x2645, 0x3b7d, 0x262d, 0x3b3e, 0x25c4, 0x3aec, 0x250f, 0x3a93, 0x243a, 0x3a32, 0x22ce, 0x39d0, 0x215b, 0x3969, 0x202a, 0x38fe, 0x1e6e, 0x388f, 0x1cf1, 0x381f, 0x1b9b, 0x3762, 0x19dd,
  52265. 0x3be9, 0x21ab, 0x3be9, 0x21b7, 0x3be5, 0x21e5, 0x3bdd, 0x2241, 0x3bc9, 0x22a7, 0x3ba0, 0x22ec, 0x3b62, 0x22cd, 0x3b0f, 0x2247, 0x3aae, 0x2175, 0x3a44, 0x2088, 0x39d4, 0x1f49, 0x3960, 0x1dbe, 0x38e9, 0x1c77, 0x3870, 0x1ae8, 0x37f1, 0x1953, 0x3708, 0x181b,
  52266. 0x3bf6, 0x1cea, 0x3bf6, 0x1cfb, 0x3bf3, 0x1d38, 0x3bec, 0x1dbd, 0x3bda, 0x1e7c, 0x3bb7, 0x1f25, 0x3b7d, 0x1f79, 0x3b2c, 0x1f4c, 0x3ac6, 0x1ea6, 0x3a55, 0x1dbb, 0x39da, 0x1cbd, 0x395a, 0x1b9d, 0x38d8, 0x1a00, 0x3855, 0x18ac, 0x37ab, 0x173c, 0x36b7, 0x1598,
  52267. 0x3bfc, 0x1736, 0x3bfc, 0x1759, 0x3bf9, 0x17e7, 0x3bf4, 0x1896, 0x3be4, 0x1997, 0x3bc6, 0x1aa8, 0x3b91, 0x1b84, 0x3b43, 0x1bd2, 0x3ade, 0x1b8a, 0x3a65, 0x1acd, 0x39e2, 0x19d3, 0x3957, 0x18cd, 0x38ca, 0x17b3, 0x383e, 0x1613, 0x376d, 0x14bf, 0x366f, 0x135e,
  52268. 0x3bff, 0x101b, 0x3bff, 0x1039, 0x3bfc, 0x10c8, 0x3bf9, 0x1226, 0x3bea, 0x1428, 0x3bcf, 0x1584, 0x3b9f, 0x16c5, 0x3b54, 0x179a, 0x3af0, 0x17ce, 0x3a76, 0x1771, 0x39ea, 0x16a4, 0x3956, 0x15a7, 0x38bf, 0x14a7, 0x3829, 0x1379, 0x3735, 0x11ea, 0x362d, 0x10a1,
  52269. 0x3c00, 0x061b, 0x3c00, 0x066a, 0x3bfe, 0x081c, 0x3bfa, 0x0a4c, 0x3bed, 0x0d16, 0x3bd5, 0x0fb3, 0x3ba9, 0x114d, 0x3b63, 0x127c, 0x3b01, 0x132f, 0x3a85, 0x1344, 0x39f4, 0x12d2, 0x3957, 0x120d, 0x38b5, 0x1122, 0x3817, 0x103c, 0x3703, 0x0ed3, 0x35f0, 0x0d6d,
  52270. 0x3c00, 0x007a, 0x3c00, 0x0089, 0x3bfe, 0x011d, 0x3bfb, 0x027c, 0x3bf0, 0x04fa, 0x3bda, 0x0881, 0x3bb1, 0x0acd, 0x3b6f, 0x0c97, 0x3b10, 0x0d7b, 0x3a93, 0x0df1, 0x39fe, 0x0def, 0x3959, 0x0d8a, 0x38af, 0x0ce9, 0x3808, 0x0c31, 0x36d5, 0x0af0, 0x35b9, 0x09a3,
  52271. 0x3c00, 0x0000, 0x3c00, 0x0001, 0x3bff, 0x0015, 0x3bfb, 0x0059, 0x3bf2, 0x00fd, 0x3bdd, 0x01df, 0x3bb7, 0x031c, 0x3b79, 0x047c, 0x3b1d, 0x05d4, 0x3aa0, 0x06d5, 0x3a08, 0x075a, 0x395d, 0x075e, 0x38aa, 0x06f7, 0x37f4, 0x0648, 0x36ac, 0x0576, 0x3586, 0x049f
  52272. ] );
  52273. let lut = null;
  52274. function getDFGLUT() {
  52275. if ( lut === null ) {
  52276. lut = new DataTexture( DATA, 16, 16, RGFormat, HalfFloatType );
  52277. lut.name = 'DFG_LUT';
  52278. lut.minFilter = LinearFilter;
  52279. lut.magFilter = LinearFilter;
  52280. lut.wrapS = ClampToEdgeWrapping;
  52281. lut.wrapT = ClampToEdgeWrapping;
  52282. lut.generateMipmaps = false;
  52283. lut.needsUpdate = true;
  52284. }
  52285. return lut;
  52286. }
  52287. /**
  52288. * This renderer uses WebGL 2 to display scenes.
  52289. *
  52290. * WebGL 1 is not supported since `r163`.
  52291. */
  52292. class WebGLRenderer {
  52293. /**
  52294. * Constructs a new WebGL renderer.
  52295. *
  52296. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  52297. */
  52298. constructor( parameters = {} ) {
  52299. const {
  52300. canvas = createCanvasElement(),
  52301. context = null,
  52302. depth = true,
  52303. stencil = false,
  52304. alpha = false,
  52305. antialias = false,
  52306. premultipliedAlpha = true,
  52307. preserveDrawingBuffer = false,
  52308. powerPreference = 'default',
  52309. failIfMajorPerformanceCaveat = false,
  52310. reversedDepthBuffer = false,
  52311. outputBufferType = UnsignedByteType,
  52312. } = parameters;
  52313. /**
  52314. * This flag can be used for type testing.
  52315. *
  52316. * @type {boolean}
  52317. * @readonly
  52318. * @default true
  52319. */
  52320. this.isWebGLRenderer = true;
  52321. let _alpha;
  52322. if ( context !== null ) {
  52323. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  52324. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  52325. }
  52326. _alpha = context.getContextAttributes().alpha;
  52327. } else {
  52328. _alpha = alpha;
  52329. }
  52330. const _outputBufferType = outputBufferType;
  52331. const INTEGER_FORMATS = new Set( [
  52332. RGBAIntegerFormat,
  52333. RGIntegerFormat,
  52334. RedIntegerFormat
  52335. ] );
  52336. const UNSIGNED_TYPES = new Set( [
  52337. UnsignedByteType,
  52338. UnsignedIntType,
  52339. UnsignedShortType,
  52340. UnsignedInt248Type,
  52341. UnsignedShort4444Type,
  52342. UnsignedShort5551Type
  52343. ] );
  52344. const uintClearColor = new Uint32Array( 4 );
  52345. const intClearColor = new Int32Array( 4 );
  52346. let currentRenderList = null;
  52347. let currentRenderState = null;
  52348. // render() can be called from within a callback triggered by another render.
  52349. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  52350. const renderListStack = [];
  52351. const renderStateStack = [];
  52352. // internal render target for non-UnsignedByteType color buffer
  52353. let output = null;
  52354. // public properties
  52355. /**
  52356. * A canvas where the renderer draws its output.This is automatically created by the renderer
  52357. * in the constructor (if not provided already); you just need to add it to your page like so:
  52358. * ```js
  52359. * document.body.appendChild( renderer.domElement );
  52360. * ```
  52361. *
  52362. * @type {HTMLCanvasElement|OffscreenCanvas}
  52363. */
  52364. this.domElement = canvas;
  52365. /**
  52366. * A object with debug configuration settings.
  52367. *
  52368. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  52369. * checked for errors during compilation and linkage process. It may be useful to disable
  52370. * this check in production for performance gain. It is strongly recommended to keep these
  52371. * checks enabled during development. If the shader does not compile and link - it will not
  52372. * work and associated material will not render.
  52373. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  52374. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  52375. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  52376. * Assigning a custom function disables the default error reporting.
  52377. *
  52378. * @type {Object}
  52379. */
  52380. this.debug = {
  52381. /**
  52382. * Enables error checking and reporting when shader programs are being compiled.
  52383. * @type {boolean}
  52384. */
  52385. checkShaderErrors: true,
  52386. /**
  52387. * Callback for custom error reporting.
  52388. * @type {?Function}
  52389. */
  52390. onShaderError: null
  52391. };
  52392. // clearing
  52393. /**
  52394. * Whether the renderer should automatically clear its output before rendering a frame or not.
  52395. *
  52396. * @type {boolean}
  52397. * @default true
  52398. */
  52399. this.autoClear = true;
  52400. /**
  52401. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52402. * the color buffer or not.
  52403. *
  52404. * @type {boolean}
  52405. * @default true
  52406. */
  52407. this.autoClearColor = true;
  52408. /**
  52409. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52410. * the depth buffer or not.
  52411. *
  52412. * @type {boolean}
  52413. * @default true
  52414. */
  52415. this.autoClearDepth = true;
  52416. /**
  52417. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52418. * the stencil buffer or not.
  52419. *
  52420. * @type {boolean}
  52421. * @default true
  52422. */
  52423. this.autoClearStencil = true;
  52424. // scene graph
  52425. /**
  52426. * Whether the renderer should sort objects or not.
  52427. *
  52428. * Note: Sorting is used to attempt to properly render objects that have some
  52429. * degree of transparency. By definition, sorting objects may not work in all
  52430. * cases. Depending on the needs of application, it may be necessary to turn
  52431. * off sorting and use other methods to deal with transparency rendering e.g.
  52432. * manually determining each object's rendering order.
  52433. *
  52434. * @type {boolean}
  52435. * @default true
  52436. */
  52437. this.sortObjects = true;
  52438. // user-defined clipping
  52439. /**
  52440. * User-defined clipping planes specified in world space. These planes apply globally.
  52441. * Points in space whose dot product with the plane is negative are cut away.
  52442. *
  52443. * @type {Array<Plane>}
  52444. */
  52445. this.clippingPlanes = [];
  52446. /**
  52447. * Whether the renderer respects object-level clipping planes or not.
  52448. *
  52449. * @type {boolean}
  52450. * @default false
  52451. */
  52452. this.localClippingEnabled = false;
  52453. // tone mapping
  52454. /**
  52455. * The tone mapping technique of the renderer.
  52456. *
  52457. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  52458. * @default NoToneMapping
  52459. */
  52460. this.toneMapping = NoToneMapping;
  52461. /**
  52462. * Exposure level of tone mapping.
  52463. *
  52464. * @type {number}
  52465. * @default 1
  52466. */
  52467. this.toneMappingExposure = 1.0;
  52468. // transmission
  52469. /**
  52470. * The normalized resolution scale for the transmission render target, measured in percentage
  52471. * of viewport dimensions. Lowering this value can result in significant performance improvements
  52472. * when using {@link MeshPhysicalMaterial#transmission}.
  52473. *
  52474. * @type {number}
  52475. * @default 1
  52476. */
  52477. this.transmissionResolutionScale = 1.0;
  52478. // internal properties
  52479. const _this = this;
  52480. let _isContextLost = false;
  52481. // internal state cache
  52482. this._outputColorSpace = SRGBColorSpace;
  52483. let _currentActiveCubeFace = 0;
  52484. let _currentActiveMipmapLevel = 0;
  52485. let _currentRenderTarget = null;
  52486. let _currentMaterialId = -1;
  52487. let _currentCamera = null;
  52488. const _currentViewport = new Vector4();
  52489. const _currentScissor = new Vector4();
  52490. let _currentScissorTest = null;
  52491. const _currentClearColor = new Color( 0x000000 );
  52492. let _currentClearAlpha = 0;
  52493. //
  52494. let _width = canvas.width;
  52495. let _height = canvas.height;
  52496. let _pixelRatio = 1;
  52497. let _opaqueSort = null;
  52498. let _transparentSort = null;
  52499. const _viewport = new Vector4( 0, 0, _width, _height );
  52500. const _scissor = new Vector4( 0, 0, _width, _height );
  52501. let _scissorTest = false;
  52502. // frustum
  52503. const _frustum = new Frustum();
  52504. // clipping
  52505. let _clippingEnabled = false;
  52506. let _localClippingEnabled = false;
  52507. // camera matrices cache
  52508. const _projScreenMatrix = new Matrix4();
  52509. const _vector3 = new Vector3();
  52510. const _vector4 = new Vector4();
  52511. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  52512. let _renderBackground = false;
  52513. function getTargetPixelRatio() {
  52514. return _currentRenderTarget === null ? _pixelRatio : 1;
  52515. }
  52516. // initialize
  52517. let _gl = context;
  52518. function getContext( contextName, contextAttributes ) {
  52519. return canvas.getContext( contextName, contextAttributes );
  52520. }
  52521. try {
  52522. const contextAttributes = {
  52523. alpha: true,
  52524. depth,
  52525. stencil,
  52526. antialias,
  52527. premultipliedAlpha,
  52528. preserveDrawingBuffer,
  52529. powerPreference,
  52530. failIfMajorPerformanceCaveat,
  52531. };
  52532. // OffscreenCanvas does not have setAttribute, see #22811
  52533. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  52534. // event listeners must be registered before WebGL context is created, see #12753
  52535. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  52536. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  52537. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52538. if ( _gl === null ) {
  52539. const contextName = 'webgl2';
  52540. _gl = getContext( contextName, contextAttributes );
  52541. if ( _gl === null ) {
  52542. if ( getContext( contextName ) ) {
  52543. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  52544. } else {
  52545. throw new Error( 'Error creating WebGL context.' );
  52546. }
  52547. }
  52548. }
  52549. } catch ( e ) {
  52550. error( 'WebGLRenderer: ' + e.message );
  52551. throw e;
  52552. }
  52553. let extensions, capabilities, state, info;
  52554. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  52555. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  52556. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  52557. let utils, bindingStates, uniformsGroups;
  52558. function initGLContext() {
  52559. extensions = new WebGLExtensions( _gl );
  52560. extensions.init();
  52561. utils = new WebGLUtils( _gl, extensions );
  52562. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  52563. state = new WebGLState( _gl, extensions );
  52564. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  52565. state.buffers.depth.setReversed( true );
  52566. }
  52567. info = new WebGLInfo( _gl );
  52568. properties = new WebGLProperties();
  52569. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  52570. cubemaps = new WebGLCubeMaps( _this );
  52571. cubeuvmaps = new WebGLCubeUVMaps( _this );
  52572. attributes = new WebGLAttributes( _gl );
  52573. bindingStates = new WebGLBindingStates( _gl, attributes );
  52574. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  52575. objects = new WebGLObjects( _gl, geometries, attributes, info );
  52576. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  52577. clipping = new WebGLClipping( properties );
  52578. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  52579. materials = new WebGLMaterials( _this, properties );
  52580. renderLists = new WebGLRenderLists();
  52581. renderStates = new WebGLRenderStates( extensions );
  52582. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  52583. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  52584. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  52585. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  52586. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  52587. info.programs = programCache.programs;
  52588. /**
  52589. * Holds details about the capabilities of the current rendering context.
  52590. *
  52591. * @name WebGLRenderer#capabilities
  52592. * @type {WebGLRenderer~Capabilities}
  52593. */
  52594. _this.capabilities = capabilities;
  52595. /**
  52596. * Provides methods for retrieving and testing WebGL extensions.
  52597. *
  52598. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  52599. * and return the extension object if available.
  52600. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  52601. *
  52602. * @name WebGLRenderer#extensions
  52603. * @type {Object}
  52604. */
  52605. _this.extensions = extensions;
  52606. /**
  52607. * Used to track properties of other objects like native WebGL objects.
  52608. *
  52609. * @name WebGLRenderer#properties
  52610. * @type {Object}
  52611. */
  52612. _this.properties = properties;
  52613. /**
  52614. * Manages the render lists of the renderer.
  52615. *
  52616. * @name WebGLRenderer#renderLists
  52617. * @type {Object}
  52618. */
  52619. _this.renderLists = renderLists;
  52620. /**
  52621. * Interface for managing shadows.
  52622. *
  52623. * @name WebGLRenderer#shadowMap
  52624. * @type {WebGLRenderer~ShadowMap}
  52625. */
  52626. _this.shadowMap = shadowMap;
  52627. /**
  52628. * Interface for managing the WebGL state.
  52629. *
  52630. * @name WebGLRenderer#state
  52631. * @type {Object}
  52632. */
  52633. _this.state = state;
  52634. /**
  52635. * Holds a series of statistical information about the GPU memory
  52636. * and the rendering process. Useful for debugging and monitoring.
  52637. *
  52638. * By default these data are reset at each render call but when having
  52639. * multiple render passes per frame (e.g. when using post processing) it can
  52640. * be preferred to reset with a custom pattern. First, set `autoReset` to
  52641. * `false`.
  52642. * ```js
  52643. * renderer.info.autoReset = false;
  52644. * ```
  52645. * Call `reset()` whenever you have finished to render a single frame.
  52646. * ```js
  52647. * renderer.info.reset();
  52648. * ```
  52649. *
  52650. * @name WebGLRenderer#info
  52651. * @type {WebGLRenderer~Info}
  52652. */
  52653. _this.info = info;
  52654. }
  52655. initGLContext();
  52656. // initialize internal render target for non-UnsignedByteType color buffer
  52657. if ( _outputBufferType !== UnsignedByteType ) {
  52658. output = new WebGLOutput( _outputBufferType, canvas.width, canvas.height, depth, stencil );
  52659. }
  52660. // xr
  52661. const xr = new WebXRManager( _this, _gl );
  52662. /**
  52663. * A reference to the XR manager.
  52664. *
  52665. * @type {WebXRManager}
  52666. */
  52667. this.xr = xr;
  52668. /**
  52669. * Returns the rendering context.
  52670. *
  52671. * @return {WebGL2RenderingContext} The rendering context.
  52672. */
  52673. this.getContext = function () {
  52674. return _gl;
  52675. };
  52676. /**
  52677. * Returns the rendering context attributes.
  52678. *
  52679. * @return {WebGLContextAttributes} The rendering context attributes.
  52680. */
  52681. this.getContextAttributes = function () {
  52682. return _gl.getContextAttributes();
  52683. };
  52684. /**
  52685. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52686. */
  52687. this.forceContextLoss = function () {
  52688. const extension = extensions.get( 'WEBGL_lose_context' );
  52689. if ( extension ) extension.loseContext();
  52690. };
  52691. /**
  52692. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52693. */
  52694. this.forceContextRestore = function () {
  52695. const extension = extensions.get( 'WEBGL_lose_context' );
  52696. if ( extension ) extension.restoreContext();
  52697. };
  52698. /**
  52699. * Returns the pixel ratio.
  52700. *
  52701. * @return {number} The pixel ratio.
  52702. */
  52703. this.getPixelRatio = function () {
  52704. return _pixelRatio;
  52705. };
  52706. /**
  52707. * Sets the given pixel ratio and resizes the canvas if necessary.
  52708. *
  52709. * @param {number} value - The pixel ratio.
  52710. */
  52711. this.setPixelRatio = function ( value ) {
  52712. if ( value === undefined ) return;
  52713. _pixelRatio = value;
  52714. this.setSize( _width, _height, false );
  52715. };
  52716. /**
  52717. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  52718. *
  52719. * @param {Vector2} target - The method writes the result in this target object.
  52720. * @return {Vector2} The renderer's size in logical pixels.
  52721. */
  52722. this.getSize = function ( target ) {
  52723. return target.set( _width, _height );
  52724. };
  52725. /**
  52726. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52727. * into account, and also sets the viewport to fit that size, starting in (0,
  52728. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  52729. *
  52730. * @param {number} width - The width in logical pixels.
  52731. * @param {number} height - The height in logical pixels.
  52732. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52733. */
  52734. this.setSize = function ( width, height, updateStyle = true ) {
  52735. if ( xr.isPresenting ) {
  52736. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52737. return;
  52738. }
  52739. _width = width;
  52740. _height = height;
  52741. canvas.width = Math.floor( width * _pixelRatio );
  52742. canvas.height = Math.floor( height * _pixelRatio );
  52743. if ( updateStyle === true ) {
  52744. canvas.style.width = width + 'px';
  52745. canvas.style.height = height + 'px';
  52746. }
  52747. if ( output !== null ) {
  52748. output.setSize( canvas.width, canvas.height );
  52749. }
  52750. this.setViewport( 0, 0, width, height );
  52751. };
  52752. /**
  52753. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52754. *
  52755. * @param {Vector2} target - The method writes the result in this target object.
  52756. * @return {Vector2} The drawing buffer size.
  52757. */
  52758. this.getDrawingBufferSize = function ( target ) {
  52759. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52760. };
  52761. /**
  52762. * This method allows to define the drawing buffer size by specifying
  52763. * width, height and pixel ratio all at once. The size of the drawing
  52764. * buffer is computed with this formula:
  52765. * ```js
  52766. * size.x = width * pixelRatio;
  52767. * size.y = height * pixelRatio;
  52768. * ```
  52769. *
  52770. * @param {number} width - The width in logical pixels.
  52771. * @param {number} height - The height in logical pixels.
  52772. * @param {number} pixelRatio - The pixel ratio.
  52773. */
  52774. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52775. _width = width;
  52776. _height = height;
  52777. _pixelRatio = pixelRatio;
  52778. canvas.width = Math.floor( width * pixelRatio );
  52779. canvas.height = Math.floor( height * pixelRatio );
  52780. this.setViewport( 0, 0, width, height );
  52781. };
  52782. /**
  52783. * Sets the post-processing effects to be applied after rendering.
  52784. *
  52785. * @param {Array} effects - An array of post-processing effects.
  52786. */
  52787. this.setEffects = function ( effects ) {
  52788. if ( _outputBufferType === UnsignedByteType ) {
  52789. console.error( 'THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.' );
  52790. return;
  52791. }
  52792. if ( effects ) {
  52793. for ( let i = 0; i < effects.length; i ++ ) {
  52794. if ( effects[ i ].isOutputPass === true ) {
  52795. console.warn( 'THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically.' );
  52796. break;
  52797. }
  52798. }
  52799. }
  52800. output.setEffects( effects || [] );
  52801. };
  52802. /**
  52803. * Returns the current viewport definition.
  52804. *
  52805. * @param {Vector2} target - The method writes the result in this target object.
  52806. * @return {Vector2} The current viewport definition.
  52807. */
  52808. this.getCurrentViewport = function ( target ) {
  52809. return target.copy( _currentViewport );
  52810. };
  52811. /**
  52812. * Returns the viewport definition.
  52813. *
  52814. * @param {Vector4} target - The method writes the result in this target object.
  52815. * @return {Vector4} The viewport definition.
  52816. */
  52817. this.getViewport = function ( target ) {
  52818. return target.copy( _viewport );
  52819. };
  52820. /**
  52821. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52822. *
  52823. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52824. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52825. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52826. * @param {number} width - The width of the viewport in logical pixel unit.
  52827. * @param {number} height - The height of the viewport in logical pixel unit.
  52828. */
  52829. this.setViewport = function ( x, y, width, height ) {
  52830. if ( x.isVector4 ) {
  52831. _viewport.set( x.x, x.y, x.z, x.w );
  52832. } else {
  52833. _viewport.set( x, y, width, height );
  52834. }
  52835. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52836. };
  52837. /**
  52838. * Returns the scissor region.
  52839. *
  52840. * @param {Vector4} target - The method writes the result in this target object.
  52841. * @return {Vector4} The scissor region.
  52842. */
  52843. this.getScissor = function ( target ) {
  52844. return target.copy( _scissor );
  52845. };
  52846. /**
  52847. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52848. *
  52849. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52850. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52851. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52852. * @param {number} width - The width of the scissor region in logical pixel unit.
  52853. * @param {number} height - The height of the scissor region in logical pixel unit.
  52854. */
  52855. this.setScissor = function ( x, y, width, height ) {
  52856. if ( x.isVector4 ) {
  52857. _scissor.set( x.x, x.y, x.z, x.w );
  52858. } else {
  52859. _scissor.set( x, y, width, height );
  52860. }
  52861. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52862. };
  52863. /**
  52864. * Returns `true` if the scissor test is enabled.
  52865. *
  52866. * @return {boolean} Whether the scissor test is enabled or not.
  52867. */
  52868. this.getScissorTest = function () {
  52869. return _scissorTest;
  52870. };
  52871. /**
  52872. * Enable or disable the scissor test. When this is enabled, only the pixels
  52873. * within the defined scissor area will be affected by further renderer
  52874. * actions.
  52875. *
  52876. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  52877. */
  52878. this.setScissorTest = function ( boolean ) {
  52879. state.setScissorTest( _scissorTest = boolean );
  52880. };
  52881. /**
  52882. * Sets a custom opaque sort function for the render lists. Pass `null`
  52883. * to use the default `painterSortStable` function.
  52884. *
  52885. * @param {?Function} method - The opaque sort function.
  52886. */
  52887. this.setOpaqueSort = function ( method ) {
  52888. _opaqueSort = method;
  52889. };
  52890. /**
  52891. * Sets a custom transparent sort function for the render lists. Pass `null`
  52892. * to use the default `reversePainterSortStable` function.
  52893. *
  52894. * @param {?Function} method - The opaque sort function.
  52895. */
  52896. this.setTransparentSort = function ( method ) {
  52897. _transparentSort = method;
  52898. };
  52899. // Clearing
  52900. /**
  52901. * Returns the clear color.
  52902. *
  52903. * @param {Color} target - The method writes the result in this target object.
  52904. * @return {Color} The clear color.
  52905. */
  52906. this.getClearColor = function ( target ) {
  52907. return target.copy( background.getClearColor() );
  52908. };
  52909. /**
  52910. * Sets the clear color and alpha.
  52911. *
  52912. * @param {Color} color - The clear color.
  52913. * @param {number} [alpha=1] - The clear alpha.
  52914. */
  52915. this.setClearColor = function () {
  52916. background.setClearColor( ...arguments );
  52917. };
  52918. /**
  52919. * Returns the clear alpha. Ranges within `[0,1]`.
  52920. *
  52921. * @return {number} The clear alpha.
  52922. */
  52923. this.getClearAlpha = function () {
  52924. return background.getClearAlpha();
  52925. };
  52926. /**
  52927. * Sets the clear alpha.
  52928. *
  52929. * @param {number} alpha - The clear alpha.
  52930. */
  52931. this.setClearAlpha = function () {
  52932. background.setClearAlpha( ...arguments );
  52933. };
  52934. /**
  52935. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  52936. * This method initializes the buffers to the current clear color values.
  52937. *
  52938. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  52939. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  52940. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  52941. */
  52942. this.clear = function ( color = true, depth = true, stencil = true ) {
  52943. let bits = 0;
  52944. if ( color ) {
  52945. // check if we're trying to clear an integer target
  52946. let isIntegerFormat = false;
  52947. if ( _currentRenderTarget !== null ) {
  52948. const targetFormat = _currentRenderTarget.texture.format;
  52949. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  52950. }
  52951. // use the appropriate clear functions to clear the target if it's a signed
  52952. // or unsigned integer target
  52953. if ( isIntegerFormat ) {
  52954. const targetType = _currentRenderTarget.texture.type;
  52955. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  52956. const clearColor = background.getClearColor();
  52957. const a = background.getClearAlpha();
  52958. const r = clearColor.r;
  52959. const g = clearColor.g;
  52960. const b = clearColor.b;
  52961. if ( isUnsignedType ) {
  52962. uintClearColor[ 0 ] = r;
  52963. uintClearColor[ 1 ] = g;
  52964. uintClearColor[ 2 ] = b;
  52965. uintClearColor[ 3 ] = a;
  52966. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  52967. } else {
  52968. intClearColor[ 0 ] = r;
  52969. intClearColor[ 1 ] = g;
  52970. intClearColor[ 2 ] = b;
  52971. intClearColor[ 3 ] = a;
  52972. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  52973. }
  52974. } else {
  52975. bits |= _gl.COLOR_BUFFER_BIT;
  52976. }
  52977. }
  52978. if ( depth ) {
  52979. bits |= _gl.DEPTH_BUFFER_BIT;
  52980. }
  52981. if ( stencil ) {
  52982. bits |= _gl.STENCIL_BUFFER_BIT;
  52983. this.state.buffers.stencil.setMask( 0xffffffff );
  52984. }
  52985. _gl.clear( bits );
  52986. };
  52987. /**
  52988. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  52989. */
  52990. this.clearColor = function () {
  52991. this.clear( true, false, false );
  52992. };
  52993. /**
  52994. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  52995. */
  52996. this.clearDepth = function () {
  52997. this.clear( false, true, false );
  52998. };
  52999. /**
  53000. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  53001. */
  53002. this.clearStencil = function () {
  53003. this.clear( false, false, true );
  53004. };
  53005. /**
  53006. * Frees the GPU-related resources allocated by this instance. Call this
  53007. * method whenever this instance is no longer used in your app.
  53008. */
  53009. this.dispose = function () {
  53010. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  53011. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  53012. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  53013. background.dispose();
  53014. renderLists.dispose();
  53015. renderStates.dispose();
  53016. properties.dispose();
  53017. cubemaps.dispose();
  53018. cubeuvmaps.dispose();
  53019. objects.dispose();
  53020. bindingStates.dispose();
  53021. uniformsGroups.dispose();
  53022. programCache.dispose();
  53023. xr.dispose();
  53024. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  53025. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  53026. animation.stop();
  53027. };
  53028. // Events
  53029. function onContextLost( event ) {
  53030. event.preventDefault();
  53031. log( 'WebGLRenderer: Context Lost.' );
  53032. _isContextLost = true;
  53033. }
  53034. function onContextRestore( /* event */ ) {
  53035. log( 'WebGLRenderer: Context Restored.' );
  53036. _isContextLost = false;
  53037. const infoAutoReset = info.autoReset;
  53038. const shadowMapEnabled = shadowMap.enabled;
  53039. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  53040. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  53041. const shadowMapType = shadowMap.type;
  53042. initGLContext();
  53043. info.autoReset = infoAutoReset;
  53044. shadowMap.enabled = shadowMapEnabled;
  53045. shadowMap.autoUpdate = shadowMapAutoUpdate;
  53046. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  53047. shadowMap.type = shadowMapType;
  53048. }
  53049. function onContextCreationError( event ) {
  53050. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  53051. }
  53052. function onMaterialDispose( event ) {
  53053. const material = event.target;
  53054. material.removeEventListener( 'dispose', onMaterialDispose );
  53055. deallocateMaterial( material );
  53056. }
  53057. // Buffer deallocation
  53058. function deallocateMaterial( material ) {
  53059. releaseMaterialProgramReferences( material );
  53060. properties.remove( material );
  53061. }
  53062. function releaseMaterialProgramReferences( material ) {
  53063. const programs = properties.get( material ).programs;
  53064. if ( programs !== undefined ) {
  53065. programs.forEach( function ( program ) {
  53066. programCache.releaseProgram( program );
  53067. } );
  53068. if ( material.isShaderMaterial ) {
  53069. programCache.releaseShaderCache( material );
  53070. }
  53071. }
  53072. }
  53073. // Buffer rendering
  53074. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  53075. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  53076. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53077. const program = setProgram( camera, scene, geometry, material, object );
  53078. state.setMaterial( material, frontFaceCW );
  53079. //
  53080. let index = geometry.index;
  53081. let rangeFactor = 1;
  53082. if ( material.wireframe === true ) {
  53083. index = geometries.getWireframeAttribute( geometry );
  53084. if ( index === undefined ) return;
  53085. rangeFactor = 2;
  53086. }
  53087. //
  53088. const drawRange = geometry.drawRange;
  53089. const position = geometry.attributes.position;
  53090. let drawStart = drawRange.start * rangeFactor;
  53091. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  53092. if ( group !== null ) {
  53093. drawStart = Math.max( drawStart, group.start * rangeFactor );
  53094. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  53095. }
  53096. if ( index !== null ) {
  53097. drawStart = Math.max( drawStart, 0 );
  53098. drawEnd = Math.min( drawEnd, index.count );
  53099. } else if ( position !== undefined && position !== null ) {
  53100. drawStart = Math.max( drawStart, 0 );
  53101. drawEnd = Math.min( drawEnd, position.count );
  53102. }
  53103. const drawCount = drawEnd - drawStart;
  53104. if ( drawCount < 0 || drawCount === Infinity ) return;
  53105. //
  53106. bindingStates.setup( object, material, program, geometry, index );
  53107. let attribute;
  53108. let renderer = bufferRenderer;
  53109. if ( index !== null ) {
  53110. attribute = attributes.get( index );
  53111. renderer = indexedBufferRenderer;
  53112. renderer.setIndex( attribute );
  53113. }
  53114. //
  53115. if ( object.isMesh ) {
  53116. if ( material.wireframe === true ) {
  53117. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  53118. renderer.setMode( _gl.LINES );
  53119. } else {
  53120. renderer.setMode( _gl.TRIANGLES );
  53121. }
  53122. } else if ( object.isLine ) {
  53123. let lineWidth = material.linewidth;
  53124. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  53125. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  53126. if ( object.isLineSegments ) {
  53127. renderer.setMode( _gl.LINES );
  53128. } else if ( object.isLineLoop ) {
  53129. renderer.setMode( _gl.LINE_LOOP );
  53130. } else {
  53131. renderer.setMode( _gl.LINE_STRIP );
  53132. }
  53133. } else if ( object.isPoints ) {
  53134. renderer.setMode( _gl.POINTS );
  53135. } else if ( object.isSprite ) {
  53136. renderer.setMode( _gl.TRIANGLES );
  53137. }
  53138. if ( object.isBatchedMesh ) {
  53139. if ( object._multiDrawInstances !== null ) {
  53140. // @deprecated, r174
  53141. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53142. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  53143. } else {
  53144. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  53145. const starts = object._multiDrawStarts;
  53146. const counts = object._multiDrawCounts;
  53147. const drawCount = object._multiDrawCount;
  53148. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  53149. const uniforms = properties.get( material ).currentProgram.getUniforms();
  53150. for ( let i = 0; i < drawCount; i ++ ) {
  53151. uniforms.setValue( _gl, '_gl_DrawID', i );
  53152. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  53153. }
  53154. } else {
  53155. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  53156. }
  53157. }
  53158. } else if ( object.isInstancedMesh ) {
  53159. renderer.renderInstances( drawStart, drawCount, object.count );
  53160. } else if ( geometry.isInstancedBufferGeometry ) {
  53161. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  53162. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  53163. renderer.renderInstances( drawStart, drawCount, instanceCount );
  53164. } else {
  53165. renderer.render( drawStart, drawCount );
  53166. }
  53167. };
  53168. // Compile
  53169. function prepareMaterial( material, scene, object ) {
  53170. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53171. material.side = BackSide;
  53172. material.needsUpdate = true;
  53173. getProgram( material, scene, object );
  53174. material.side = FrontSide;
  53175. material.needsUpdate = true;
  53176. getProgram( material, scene, object );
  53177. material.side = DoubleSide;
  53178. } else {
  53179. getProgram( material, scene, object );
  53180. }
  53181. }
  53182. /**
  53183. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  53184. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  53185. * optional parameter for applying the target scene.
  53186. *
  53187. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  53188. *
  53189. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53190. * @param {Camera} camera - The camera.
  53191. * @param {?Scene} [targetScene=null] - The target scene.
  53192. * @return {Set<Material>} The precompiled materials.
  53193. */
  53194. this.compile = function ( scene, camera, targetScene = null ) {
  53195. if ( targetScene === null ) targetScene = scene;
  53196. currentRenderState = renderStates.get( targetScene );
  53197. currentRenderState.init( camera );
  53198. renderStateStack.push( currentRenderState );
  53199. // gather lights from both the target scene and the new object that will be added to the scene.
  53200. targetScene.traverseVisible( function ( object ) {
  53201. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53202. currentRenderState.pushLight( object );
  53203. if ( object.castShadow ) {
  53204. currentRenderState.pushShadow( object );
  53205. }
  53206. }
  53207. } );
  53208. if ( scene !== targetScene ) {
  53209. scene.traverseVisible( function ( object ) {
  53210. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53211. currentRenderState.pushLight( object );
  53212. if ( object.castShadow ) {
  53213. currentRenderState.pushShadow( object );
  53214. }
  53215. }
  53216. } );
  53217. }
  53218. currentRenderState.setupLights();
  53219. // Only initialize materials in the new scene, not the targetScene.
  53220. const materials = new Set();
  53221. scene.traverse( function ( object ) {
  53222. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  53223. return;
  53224. }
  53225. const material = object.material;
  53226. if ( material ) {
  53227. if ( Array.isArray( material ) ) {
  53228. for ( let i = 0; i < material.length; i ++ ) {
  53229. const material2 = material[ i ];
  53230. prepareMaterial( material2, targetScene, object );
  53231. materials.add( material2 );
  53232. }
  53233. } else {
  53234. prepareMaterial( material, targetScene, object );
  53235. materials.add( material );
  53236. }
  53237. }
  53238. } );
  53239. currentRenderState = renderStateStack.pop();
  53240. return materials;
  53241. };
  53242. // compileAsync
  53243. /**
  53244. * Asynchronous version of {@link WebGLRenderer#compile}.
  53245. *
  53246. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  53247. * it is recommended to use this version of `compile()` whenever possible.
  53248. *
  53249. * @async
  53250. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53251. * @param {Camera} camera - The camera.
  53252. * @param {?Scene} [targetScene=null] - The target scene.
  53253. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  53254. */
  53255. this.compileAsync = function ( scene, camera, targetScene = null ) {
  53256. const materials = this.compile( scene, camera, targetScene );
  53257. // Wait for all the materials in the new object to indicate that they're
  53258. // ready to be used before resolving the promise.
  53259. return new Promise( ( resolve ) => {
  53260. function checkMaterialsReady() {
  53261. materials.forEach( function ( material ) {
  53262. const materialProperties = properties.get( material );
  53263. const program = materialProperties.currentProgram;
  53264. if ( program.isReady() ) {
  53265. // remove any programs that report they're ready to use from the list
  53266. materials.delete( material );
  53267. }
  53268. } );
  53269. // once the list of compiling materials is empty, call the callback
  53270. if ( materials.size === 0 ) {
  53271. resolve( scene );
  53272. return;
  53273. }
  53274. // if some materials are still not ready, wait a bit and check again
  53275. setTimeout( checkMaterialsReady, 10 );
  53276. }
  53277. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  53278. // If we can check the compilation status of the materials without
  53279. // blocking then do so right away.
  53280. checkMaterialsReady();
  53281. } else {
  53282. // Otherwise start by waiting a bit to give the materials we just
  53283. // initialized a chance to finish.
  53284. setTimeout( checkMaterialsReady, 10 );
  53285. }
  53286. } );
  53287. };
  53288. // Animation Loop
  53289. let onAnimationFrameCallback = null;
  53290. function onAnimationFrame( time ) {
  53291. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  53292. }
  53293. function onXRSessionStart() {
  53294. animation.stop();
  53295. }
  53296. function onXRSessionEnd() {
  53297. animation.start();
  53298. }
  53299. const animation = new WebGLAnimation();
  53300. animation.setAnimationLoop( onAnimationFrame );
  53301. if ( typeof self !== 'undefined' ) animation.setContext( self );
  53302. /**
  53303. * Applications are advised to always define the animation loop
  53304. * with this method and not manually with `requestAnimationFrame()`
  53305. * for best compatibility.
  53306. *
  53307. * @param {?onAnimationCallback} callback - The application's animation loop.
  53308. */
  53309. this.setAnimationLoop = function ( callback ) {
  53310. onAnimationFrameCallback = callback;
  53311. xr.setAnimationLoop( callback );
  53312. ( callback === null ) ? animation.stop() : animation.start();
  53313. };
  53314. xr.addEventListener( 'sessionstart', onXRSessionStart );
  53315. xr.addEventListener( 'sessionend', onXRSessionEnd );
  53316. // Rendering
  53317. /**
  53318. * Renders the given scene (or other type of 3D object) using the given camera.
  53319. *
  53320. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  53321. * or to the canvas as usual.
  53322. *
  53323. * By default render buffers are cleared before rendering but you can prevent
  53324. * this by setting the property `autoClear` to `false`. If you want to prevent
  53325. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  53326. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  53327. *
  53328. * @param {Object3D} scene - The scene to render.
  53329. * @param {Camera} camera - The camera.
  53330. */
  53331. this.render = function ( scene, camera ) {
  53332. if ( camera !== undefined && camera.isCamera !== true ) {
  53333. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  53334. return;
  53335. }
  53336. if ( _isContextLost === true ) return;
  53337. // use internal render target for HalfFloatType color buffer (only when tone mapping is enabled)
  53338. const isXRPresenting = xr.enabled === true && xr.isPresenting === true;
  53339. const useOutput = output !== null && ( _currentRenderTarget === null || isXRPresenting ) && output.begin( _this, _currentRenderTarget );
  53340. // update scene graph
  53341. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  53342. // update camera matrices and frustum
  53343. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  53344. if ( xr.enabled === true && xr.isPresenting === true && ( output === null || output.isCompositing() === false ) ) {
  53345. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  53346. camera = xr.getCamera(); // use XR camera for rendering
  53347. }
  53348. //
  53349. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  53350. currentRenderState = renderStates.get( scene, renderStateStack.length );
  53351. currentRenderState.init( camera );
  53352. renderStateStack.push( currentRenderState );
  53353. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  53354. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  53355. _localClippingEnabled = this.localClippingEnabled;
  53356. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  53357. currentRenderList = renderLists.get( scene, renderListStack.length );
  53358. currentRenderList.init();
  53359. renderListStack.push( currentRenderList );
  53360. if ( xr.enabled === true && xr.isPresenting === true ) {
  53361. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  53362. if ( depthSensingMesh !== null ) {
  53363. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  53364. }
  53365. }
  53366. projectObject( scene, camera, 0, _this.sortObjects );
  53367. currentRenderList.finish();
  53368. if ( _this.sortObjects === true ) {
  53369. currentRenderList.sort( _opaqueSort, _transparentSort );
  53370. }
  53371. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  53372. if ( _renderBackground ) {
  53373. background.addToRenderList( currentRenderList, scene );
  53374. }
  53375. //
  53376. this.info.render.frame ++;
  53377. if ( _clippingEnabled === true ) clipping.beginShadows();
  53378. const shadowsArray = currentRenderState.state.shadowsArray;
  53379. shadowMap.render( shadowsArray, scene, camera );
  53380. if ( _clippingEnabled === true ) clipping.endShadows();
  53381. //
  53382. if ( this.info.autoReset === true ) this.info.reset();
  53383. // render scene (skip if first effect is a render pass - it will render the scene itself)
  53384. const skipSceneRender = useOutput && output.hasRenderPass();
  53385. if ( skipSceneRender === false ) {
  53386. const opaqueObjects = currentRenderList.opaque;
  53387. const transmissiveObjects = currentRenderList.transmissive;
  53388. currentRenderState.setupLights();
  53389. if ( camera.isArrayCamera ) {
  53390. const cameras = camera.cameras;
  53391. if ( transmissiveObjects.length > 0 ) {
  53392. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53393. const camera2 = cameras[ i ];
  53394. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  53395. }
  53396. }
  53397. if ( _renderBackground ) background.render( scene );
  53398. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53399. const camera2 = cameras[ i ];
  53400. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  53401. }
  53402. } else {
  53403. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  53404. if ( _renderBackground ) background.render( scene );
  53405. renderScene( currentRenderList, scene, camera );
  53406. }
  53407. }
  53408. //
  53409. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  53410. // resolve multisample renderbuffers to a single-sample texture if necessary
  53411. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  53412. // Generate mipmap if we're using any kind of mipmap filtering
  53413. textures.updateRenderTargetMipmap( _currentRenderTarget );
  53414. }
  53415. // copy from internal render target to canvas using fullscreen quad
  53416. if ( useOutput ) {
  53417. output.end( _this );
  53418. }
  53419. //
  53420. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  53421. // _gl.finish();
  53422. bindingStates.resetDefaultState();
  53423. _currentMaterialId = -1;
  53424. _currentCamera = null;
  53425. renderStateStack.pop();
  53426. if ( renderStateStack.length > 0 ) {
  53427. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  53428. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  53429. } else {
  53430. currentRenderState = null;
  53431. }
  53432. renderListStack.pop();
  53433. if ( renderListStack.length > 0 ) {
  53434. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  53435. } else {
  53436. currentRenderList = null;
  53437. }
  53438. };
  53439. function projectObject( object, camera, groupOrder, sortObjects ) {
  53440. if ( object.visible === false ) return;
  53441. const visible = object.layers.test( camera.layers );
  53442. if ( visible ) {
  53443. if ( object.isGroup ) {
  53444. groupOrder = object.renderOrder;
  53445. } else if ( object.isLOD ) {
  53446. if ( object.autoUpdate === true ) object.update( camera );
  53447. } else if ( object.isLight ) {
  53448. currentRenderState.pushLight( object );
  53449. if ( object.castShadow ) {
  53450. currentRenderState.pushShadow( object );
  53451. }
  53452. } else if ( object.isSprite ) {
  53453. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  53454. if ( sortObjects ) {
  53455. _vector4.setFromMatrixPosition( object.matrixWorld )
  53456. .applyMatrix4( _projScreenMatrix );
  53457. }
  53458. const geometry = objects.update( object );
  53459. const material = object.material;
  53460. if ( material.visible ) {
  53461. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53462. }
  53463. }
  53464. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  53465. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  53466. const geometry = objects.update( object );
  53467. const material = object.material;
  53468. if ( sortObjects ) {
  53469. if ( object.boundingSphere !== undefined ) {
  53470. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  53471. _vector4.copy( object.boundingSphere.center );
  53472. } else {
  53473. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  53474. _vector4.copy( geometry.boundingSphere.center );
  53475. }
  53476. _vector4
  53477. .applyMatrix4( object.matrixWorld )
  53478. .applyMatrix4( _projScreenMatrix );
  53479. }
  53480. if ( Array.isArray( material ) ) {
  53481. const groups = geometry.groups;
  53482. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53483. const group = groups[ i ];
  53484. const groupMaterial = material[ group.materialIndex ];
  53485. if ( groupMaterial && groupMaterial.visible ) {
  53486. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  53487. }
  53488. }
  53489. } else if ( material.visible ) {
  53490. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53491. }
  53492. }
  53493. }
  53494. }
  53495. const children = object.children;
  53496. for ( let i = 0, l = children.length; i < l; i ++ ) {
  53497. projectObject( children[ i ], camera, groupOrder, sortObjects );
  53498. }
  53499. }
  53500. function renderScene( currentRenderList, scene, camera, viewport ) {
  53501. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  53502. currentRenderState.setupLightsView( camera );
  53503. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53504. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  53505. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  53506. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  53507. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  53508. // Ensure depth buffer writing is enabled so it can be cleared on next render
  53509. state.buffers.depth.setTest( true );
  53510. state.buffers.depth.setMask( true );
  53511. state.buffers.color.setMask( true );
  53512. state.setPolygonOffset( false );
  53513. }
  53514. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  53515. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53516. if ( overrideMaterial !== null ) {
  53517. return;
  53518. }
  53519. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  53520. const hasHalfFloatSupport = extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' );
  53521. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  53522. generateMipmaps: true,
  53523. type: hasHalfFloatSupport ? HalfFloatType : UnsignedByteType,
  53524. minFilter: LinearMipmapLinearFilter,
  53525. samples: capabilities.samples,
  53526. stencilBuffer: stencil,
  53527. resolveDepthBuffer: false,
  53528. resolveStencilBuffer: false,
  53529. colorSpace: ColorManagement.workingColorSpace,
  53530. } );
  53531. // debug
  53532. /*
  53533. const geometry = new PlaneGeometry();
  53534. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  53535. const mesh = new Mesh( geometry, material );
  53536. scene.add( mesh );
  53537. */
  53538. }
  53539. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  53540. const activeViewport = camera.viewport || _currentViewport;
  53541. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  53542. //
  53543. const currentRenderTarget = _this.getRenderTarget();
  53544. const currentActiveCubeFace = _this.getActiveCubeFace();
  53545. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  53546. _this.setRenderTarget( transmissionRenderTarget );
  53547. _this.getClearColor( _currentClearColor );
  53548. _currentClearAlpha = _this.getClearAlpha();
  53549. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  53550. _this.clear();
  53551. if ( _renderBackground ) background.render( scene );
  53552. // Turn off the features which can affect the frag color for opaque objects pass.
  53553. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  53554. const currentToneMapping = _this.toneMapping;
  53555. _this.toneMapping = NoToneMapping;
  53556. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  53557. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  53558. const currentCameraViewport = camera.viewport;
  53559. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  53560. currentRenderState.setupLightsView( camera );
  53561. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53562. renderObjects( opaqueObjects, scene, camera );
  53563. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53564. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53565. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  53566. let renderTargetNeedsUpdate = false;
  53567. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  53568. const renderItem = transmissiveObjects[ i ];
  53569. const { object, geometry, material, group } = renderItem;
  53570. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  53571. const currentSide = material.side;
  53572. material.side = BackSide;
  53573. material.needsUpdate = true;
  53574. renderObject( object, scene, camera, geometry, material, group );
  53575. material.side = currentSide;
  53576. material.needsUpdate = true;
  53577. renderTargetNeedsUpdate = true;
  53578. }
  53579. }
  53580. if ( renderTargetNeedsUpdate === true ) {
  53581. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53582. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53583. }
  53584. }
  53585. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  53586. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  53587. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  53588. _this.toneMapping = currentToneMapping;
  53589. }
  53590. function renderObjects( renderList, scene, camera ) {
  53591. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53592. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  53593. const renderItem = renderList[ i ];
  53594. const { object, geometry, group } = renderItem;
  53595. let material = renderItem.material;
  53596. if ( material.allowOverride === true && overrideMaterial !== null ) {
  53597. material = overrideMaterial;
  53598. }
  53599. if ( object.layers.test( camera.layers ) ) {
  53600. renderObject( object, scene, camera, geometry, material, group );
  53601. }
  53602. }
  53603. }
  53604. function renderObject( object, scene, camera, geometry, material, group ) {
  53605. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  53606. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  53607. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  53608. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  53609. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53610. material.side = BackSide;
  53611. material.needsUpdate = true;
  53612. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53613. material.side = FrontSide;
  53614. material.needsUpdate = true;
  53615. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53616. material.side = DoubleSide;
  53617. } else {
  53618. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53619. }
  53620. object.onAfterRender( _this, scene, camera, geometry, material, group );
  53621. }
  53622. function getProgram( material, scene, object ) {
  53623. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53624. const materialProperties = properties.get( material );
  53625. const lights = currentRenderState.state.lights;
  53626. const shadowsArray = currentRenderState.state.shadowsArray;
  53627. const lightsStateVersion = lights.state.version;
  53628. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  53629. const programCacheKey = programCache.getProgramCacheKey( parameters );
  53630. let programs = materialProperties.programs;
  53631. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  53632. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  53633. materialProperties.fog = scene.fog;
  53634. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  53635. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  53636. if ( programs === undefined ) {
  53637. // new material
  53638. material.addEventListener( 'dispose', onMaterialDispose );
  53639. programs = new Map();
  53640. materialProperties.programs = programs;
  53641. }
  53642. let program = programs.get( programCacheKey );
  53643. if ( program !== undefined ) {
  53644. // early out if program and light state is identical
  53645. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  53646. updateCommonMaterialProperties( material, parameters );
  53647. return program;
  53648. }
  53649. } else {
  53650. parameters.uniforms = programCache.getUniforms( material );
  53651. material.onBeforeCompile( parameters, _this );
  53652. program = programCache.acquireProgram( parameters, programCacheKey );
  53653. programs.set( programCacheKey, program );
  53654. materialProperties.uniforms = parameters.uniforms;
  53655. }
  53656. const uniforms = materialProperties.uniforms;
  53657. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  53658. uniforms.clippingPlanes = clipping.uniform;
  53659. }
  53660. updateCommonMaterialProperties( material, parameters );
  53661. // store the light setup it was created for
  53662. materialProperties.needsLights = materialNeedsLights( material );
  53663. materialProperties.lightsStateVersion = lightsStateVersion;
  53664. if ( materialProperties.needsLights ) {
  53665. // wire up the material to this renderer's lighting state
  53666. uniforms.ambientLightColor.value = lights.state.ambient;
  53667. uniforms.lightProbe.value = lights.state.probe;
  53668. uniforms.directionalLights.value = lights.state.directional;
  53669. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  53670. uniforms.spotLights.value = lights.state.spot;
  53671. uniforms.spotLightShadows.value = lights.state.spotShadow;
  53672. uniforms.rectAreaLights.value = lights.state.rectArea;
  53673. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  53674. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  53675. uniforms.pointLights.value = lights.state.point;
  53676. uniforms.pointLightShadows.value = lights.state.pointShadow;
  53677. uniforms.hemisphereLights.value = lights.state.hemi;
  53678. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  53679. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  53680. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  53681. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  53682. uniforms.spotLightMap.value = lights.state.spotLightMap;
  53683. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  53684. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  53685. // TODO (abelnation): add area lights shadow info to uniforms
  53686. }
  53687. materialProperties.currentProgram = program;
  53688. materialProperties.uniformsList = null;
  53689. return program;
  53690. }
  53691. function getUniformList( materialProperties ) {
  53692. if ( materialProperties.uniformsList === null ) {
  53693. const progUniforms = materialProperties.currentProgram.getUniforms();
  53694. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  53695. }
  53696. return materialProperties.uniformsList;
  53697. }
  53698. function updateCommonMaterialProperties( material, parameters ) {
  53699. const materialProperties = properties.get( material );
  53700. materialProperties.outputColorSpace = parameters.outputColorSpace;
  53701. materialProperties.batching = parameters.batching;
  53702. materialProperties.batchingColor = parameters.batchingColor;
  53703. materialProperties.instancing = parameters.instancing;
  53704. materialProperties.instancingColor = parameters.instancingColor;
  53705. materialProperties.instancingMorph = parameters.instancingMorph;
  53706. materialProperties.skinning = parameters.skinning;
  53707. materialProperties.morphTargets = parameters.morphTargets;
  53708. materialProperties.morphNormals = parameters.morphNormals;
  53709. materialProperties.morphColors = parameters.morphColors;
  53710. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  53711. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  53712. materialProperties.numIntersection = parameters.numClipIntersection;
  53713. materialProperties.vertexAlphas = parameters.vertexAlphas;
  53714. materialProperties.vertexTangents = parameters.vertexTangents;
  53715. materialProperties.toneMapping = parameters.toneMapping;
  53716. }
  53717. function setProgram( camera, scene, geometry, material, object ) {
  53718. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53719. textures.resetTextureUnits();
  53720. const fog = scene.fog;
  53721. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  53722. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  53723. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  53724. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  53725. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  53726. const morphTargets = !! geometry.morphAttributes.position;
  53727. const morphNormals = !! geometry.morphAttributes.normal;
  53728. const morphColors = !! geometry.morphAttributes.color;
  53729. let toneMapping = NoToneMapping;
  53730. if ( material.toneMapped ) {
  53731. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  53732. toneMapping = _this.toneMapping;
  53733. }
  53734. }
  53735. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  53736. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  53737. const materialProperties = properties.get( material );
  53738. const lights = currentRenderState.state.lights;
  53739. if ( _clippingEnabled === true ) {
  53740. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  53741. const useCache =
  53742. camera === _currentCamera &&
  53743. material.id === _currentMaterialId;
  53744. // we might want to call this function with some ClippingGroup
  53745. // object instead of the material, once it becomes feasible
  53746. // (#8465, #8379)
  53747. clipping.setState( material, camera, useCache );
  53748. }
  53749. }
  53750. //
  53751. let needsProgramChange = false;
  53752. if ( material.version === materialProperties.__version ) {
  53753. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  53754. needsProgramChange = true;
  53755. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  53756. needsProgramChange = true;
  53757. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53758. needsProgramChange = true;
  53759. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53760. needsProgramChange = true;
  53761. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53762. needsProgramChange = true;
  53763. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53764. needsProgramChange = true;
  53765. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53766. needsProgramChange = true;
  53767. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53768. needsProgramChange = true;
  53769. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53770. needsProgramChange = true;
  53771. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53772. needsProgramChange = true;
  53773. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53774. needsProgramChange = true;
  53775. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53776. needsProgramChange = true;
  53777. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53778. needsProgramChange = true;
  53779. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53780. needsProgramChange = true;
  53781. } else if ( materialProperties.envMap !== envMap ) {
  53782. needsProgramChange = true;
  53783. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53784. needsProgramChange = true;
  53785. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53786. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53787. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53788. needsProgramChange = true;
  53789. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53790. needsProgramChange = true;
  53791. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53792. needsProgramChange = true;
  53793. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53794. needsProgramChange = true;
  53795. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53796. needsProgramChange = true;
  53797. } else if ( materialProperties.morphColors !== morphColors ) {
  53798. needsProgramChange = true;
  53799. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53800. needsProgramChange = true;
  53801. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53802. needsProgramChange = true;
  53803. }
  53804. } else {
  53805. needsProgramChange = true;
  53806. materialProperties.__version = material.version;
  53807. }
  53808. //
  53809. let program = materialProperties.currentProgram;
  53810. if ( needsProgramChange === true ) {
  53811. program = getProgram( material, scene, object );
  53812. }
  53813. let refreshProgram = false;
  53814. let refreshMaterial = false;
  53815. let refreshLights = false;
  53816. const p_uniforms = program.getUniforms(),
  53817. m_uniforms = materialProperties.uniforms;
  53818. if ( state.useProgram( program.program ) ) {
  53819. refreshProgram = true;
  53820. refreshMaterial = true;
  53821. refreshLights = true;
  53822. }
  53823. if ( material.id !== _currentMaterialId ) {
  53824. _currentMaterialId = material.id;
  53825. refreshMaterial = true;
  53826. }
  53827. if ( refreshProgram || _currentCamera !== camera ) {
  53828. // common camera uniforms
  53829. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53830. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53831. camera._reversedDepth = true;
  53832. camera.updateProjectionMatrix();
  53833. }
  53834. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53835. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53836. const uCamPos = p_uniforms.map.cameraPosition;
  53837. if ( uCamPos !== undefined ) {
  53838. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53839. }
  53840. if ( capabilities.logarithmicDepthBuffer ) {
  53841. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53842. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53843. }
  53844. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53845. if ( material.isMeshPhongMaterial ||
  53846. material.isMeshToonMaterial ||
  53847. material.isMeshLambertMaterial ||
  53848. material.isMeshBasicMaterial ||
  53849. material.isMeshStandardMaterial ||
  53850. material.isShaderMaterial ) {
  53851. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53852. }
  53853. if ( _currentCamera !== camera ) {
  53854. _currentCamera = camera;
  53855. // lighting uniforms depend on the camera so enforce an update
  53856. // now, in case this material supports lights - or later, when
  53857. // the next material that does gets activated:
  53858. refreshMaterial = true; // set to true on material change
  53859. refreshLights = true; // remains set until update done
  53860. }
  53861. }
  53862. // Pre-allocate texture units for shadow samplers before setting data textures
  53863. if ( materialProperties.needsLights ) {
  53864. // Set shadow map uniforms first to ensure they get the first texture units
  53865. if ( lights.state.directionalShadowMap.length > 0 ) {
  53866. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  53867. }
  53868. if ( lights.state.spotShadowMap.length > 0 ) {
  53869. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  53870. }
  53871. if ( lights.state.pointShadowMap.length > 0 ) {
  53872. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  53873. }
  53874. }
  53875. // skinning and morph target uniforms must be set even if material didn't change
  53876. // auto-setting of texture unit for bone and morph texture must go before other textures
  53877. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  53878. if ( object.isSkinnedMesh ) {
  53879. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  53880. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  53881. const skeleton = object.skeleton;
  53882. if ( skeleton ) {
  53883. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  53884. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  53885. }
  53886. }
  53887. if ( object.isBatchedMesh ) {
  53888. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  53889. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  53890. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  53891. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  53892. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  53893. if ( object._colorsTexture !== null ) {
  53894. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  53895. }
  53896. }
  53897. const morphAttributes = geometry.morphAttributes;
  53898. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  53899. morphtargets.update( object, geometry, program );
  53900. }
  53901. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  53902. materialProperties.receiveShadow = object.receiveShadow;
  53903. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  53904. }
  53905. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  53906. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  53907. m_uniforms.envMap.value = envMap;
  53908. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  53909. }
  53910. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  53911. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  53912. }
  53913. // Set DFG LUT for physically-based materials
  53914. if ( m_uniforms.dfgLUT !== undefined ) {
  53915. m_uniforms.dfgLUT.value = getDFGLUT();
  53916. }
  53917. if ( refreshMaterial ) {
  53918. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  53919. if ( materialProperties.needsLights ) {
  53920. // the current material requires lighting info
  53921. // note: all lighting uniforms are always set correctly
  53922. // they simply reference the renderer's state for their
  53923. // values
  53924. //
  53925. // use the current material's .needsUpdate flags to set
  53926. // the GL state when required
  53927. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  53928. }
  53929. // refresh uniforms common to several materials
  53930. if ( fog && material.fog === true ) {
  53931. materials.refreshFogUniforms( m_uniforms, fog );
  53932. }
  53933. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  53934. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53935. }
  53936. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  53937. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53938. material.uniformsNeedUpdate = false;
  53939. }
  53940. if ( material.isSpriteMaterial ) {
  53941. p_uniforms.setValue( _gl, 'center', object.center );
  53942. }
  53943. // common matrices
  53944. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  53945. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  53946. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  53947. // UBOs
  53948. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  53949. const groups = material.uniformsGroups;
  53950. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53951. const group = groups[ i ];
  53952. uniformsGroups.update( group, program );
  53953. uniformsGroups.bind( group, program );
  53954. }
  53955. }
  53956. return program;
  53957. }
  53958. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  53959. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  53960. uniforms.ambientLightColor.needsUpdate = value;
  53961. uniforms.lightProbe.needsUpdate = value;
  53962. uniforms.directionalLights.needsUpdate = value;
  53963. uniforms.directionalLightShadows.needsUpdate = value;
  53964. uniforms.pointLights.needsUpdate = value;
  53965. uniforms.pointLightShadows.needsUpdate = value;
  53966. uniforms.spotLights.needsUpdate = value;
  53967. uniforms.spotLightShadows.needsUpdate = value;
  53968. uniforms.rectAreaLights.needsUpdate = value;
  53969. uniforms.hemisphereLights.needsUpdate = value;
  53970. }
  53971. function materialNeedsLights( material ) {
  53972. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  53973. material.isMeshStandardMaterial || material.isShadowMaterial ||
  53974. ( material.isShaderMaterial && material.lights === true );
  53975. }
  53976. /**
  53977. * Returns the active cube face.
  53978. *
  53979. * @return {number} The active cube face.
  53980. */
  53981. this.getActiveCubeFace = function () {
  53982. return _currentActiveCubeFace;
  53983. };
  53984. /**
  53985. * Returns the active mipmap level.
  53986. *
  53987. * @return {number} The active mipmap level.
  53988. */
  53989. this.getActiveMipmapLevel = function () {
  53990. return _currentActiveMipmapLevel;
  53991. };
  53992. /**
  53993. * Returns the active render target.
  53994. *
  53995. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  53996. * is currently set.
  53997. */
  53998. this.getRenderTarget = function () {
  53999. return _currentRenderTarget;
  54000. };
  54001. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  54002. const renderTargetProperties = properties.get( renderTarget );
  54003. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  54004. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  54005. // The multisample_render_to_texture extension doesn't work properly if there
  54006. // are midframe flushes and an external depth buffer. Disable use of the extension.
  54007. renderTargetProperties.__useRenderToTexture = false;
  54008. }
  54009. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  54010. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  54011. renderTargetProperties.__hasExternalTextures = true;
  54012. };
  54013. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  54014. const renderTargetProperties = properties.get( renderTarget );
  54015. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  54016. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  54017. };
  54018. const _scratchFrameBuffer = _gl.createFramebuffer();
  54019. /**
  54020. * Sets the active rendertarget.
  54021. *
  54022. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  54023. * the canvas is set as the active render target instead.
  54024. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  54025. * Indicates the z layer to render in to when using 3D or array render targets.
  54026. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  54027. */
  54028. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  54029. _currentRenderTarget = renderTarget;
  54030. _currentActiveCubeFace = activeCubeFace;
  54031. _currentActiveMipmapLevel = activeMipmapLevel;
  54032. let framebuffer = null;
  54033. let isCube = false;
  54034. let isRenderTarget3D = false;
  54035. if ( renderTarget ) {
  54036. const renderTargetProperties = properties.get( renderTarget );
  54037. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  54038. // Externally-managed framebuffer (e.g. XR)
  54039. // Bind to the stored framebuffer (may be null for default, or a WebGLFramebuffer)
  54040. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  54041. _currentViewport.copy( renderTarget.viewport );
  54042. _currentScissor.copy( renderTarget.scissor );
  54043. _currentScissorTest = renderTarget.scissorTest;
  54044. state.viewport( _currentViewport );
  54045. state.scissor( _currentScissor );
  54046. state.setScissorTest( _currentScissorTest );
  54047. _currentMaterialId = -1;
  54048. return;
  54049. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  54050. textures.setupRenderTarget( renderTarget );
  54051. } else if ( renderTargetProperties.__hasExternalTextures ) {
  54052. // Color and depth texture must be rebound in order for the swapchain to update.
  54053. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  54054. } else if ( renderTarget.depthBuffer ) {
  54055. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  54056. const depthTexture = renderTarget.depthTexture;
  54057. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  54058. // check if the depth texture is compatible
  54059. if (
  54060. depthTexture !== null &&
  54061. properties.has( depthTexture ) &&
  54062. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  54063. ) {
  54064. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  54065. }
  54066. // Swap the depth buffer to the currently attached one
  54067. textures.setupDepthRenderbuffer( renderTarget );
  54068. }
  54069. }
  54070. const texture = renderTarget.texture;
  54071. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54072. isRenderTarget3D = true;
  54073. }
  54074. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54075. if ( renderTarget.isWebGLCubeRenderTarget ) {
  54076. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  54077. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  54078. } else {
  54079. framebuffer = __webglFramebuffer[ activeCubeFace ];
  54080. }
  54081. isCube = true;
  54082. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  54083. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  54084. } else {
  54085. if ( Array.isArray( __webglFramebuffer ) ) {
  54086. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  54087. } else {
  54088. framebuffer = __webglFramebuffer;
  54089. }
  54090. }
  54091. _currentViewport.copy( renderTarget.viewport );
  54092. _currentScissor.copy( renderTarget.scissor );
  54093. _currentScissorTest = renderTarget.scissorTest;
  54094. } else {
  54095. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  54096. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  54097. _currentScissorTest = _scissorTest;
  54098. }
  54099. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  54100. // being bound that are different sizes.
  54101. if ( activeMipmapLevel !== 0 ) {
  54102. framebuffer = _scratchFrameBuffer;
  54103. }
  54104. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54105. if ( framebufferBound ) {
  54106. state.drawBuffers( renderTarget, framebuffer );
  54107. }
  54108. state.viewport( _currentViewport );
  54109. state.scissor( _currentScissor );
  54110. state.setScissorTest( _currentScissorTest );
  54111. if ( isCube ) {
  54112. const textureProperties = properties.get( renderTarget.texture );
  54113. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  54114. } else if ( isRenderTarget3D ) {
  54115. const layer = activeCubeFace;
  54116. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  54117. const textureProperties = properties.get( renderTarget.textures[ i ] );
  54118. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  54119. }
  54120. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  54121. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  54122. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  54123. const textureProperties = properties.get( renderTarget.texture );
  54124. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  54125. }
  54126. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  54127. };
  54128. /**
  54129. * Reads the pixel data from the given render target into the given buffer.
  54130. *
  54131. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54132. * @param {number} x - The `x` coordinate of the copy region's origin.
  54133. * @param {number} y - The `y` coordinate of the copy region's origin.
  54134. * @param {number} width - The width of the copy region.
  54135. * @param {number} height - The height of the copy region.
  54136. * @param {TypedArray} buffer - The result buffer.
  54137. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54138. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54139. */
  54140. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54141. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54142. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54143. return;
  54144. }
  54145. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54146. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54147. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54148. }
  54149. if ( framebuffer ) {
  54150. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54151. try {
  54152. const texture = renderTarget.textures[ textureIndex ];
  54153. const textureFormat = texture.format;
  54154. const textureType = texture.type;
  54155. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54156. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  54157. return;
  54158. }
  54159. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54160. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54161. return;
  54162. }
  54163. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54164. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54165. // when using MRT, select the correct color buffer for the subsequent read command
  54166. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54167. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  54168. }
  54169. } finally {
  54170. // restore framebuffer of current render target if necessary
  54171. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54172. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54173. }
  54174. }
  54175. };
  54176. /**
  54177. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  54178. *
  54179. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  54180. *
  54181. * @async
  54182. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  54183. * @param {number} x - The `x` coordinate of the copy region's origin.
  54184. * @param {number} y - The `y` coordinate of the copy region's origin.
  54185. * @param {number} width - The width of the copy region.
  54186. * @param {number} height - The height of the copy region.
  54187. * @param {TypedArray} buffer - The result buffer.
  54188. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54189. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54190. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  54191. */
  54192. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54193. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54194. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54195. }
  54196. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54197. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54198. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54199. }
  54200. if ( framebuffer ) {
  54201. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54202. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54203. // set the active frame buffer to the one we want to read
  54204. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54205. const texture = renderTarget.textures[ textureIndex ];
  54206. const textureFormat = texture.format;
  54207. const textureType = texture.type;
  54208. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54209. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  54210. }
  54211. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54212. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54213. }
  54214. const glBuffer = _gl.createBuffer();
  54215. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54216. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  54217. // when using MRT, select the correct color buffer for the subsequent read command
  54218. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54219. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  54220. // reset the frame buffer to the currently set buffer before waiting
  54221. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54222. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  54223. // check if the commands have finished every 8 ms
  54224. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  54225. _gl.flush();
  54226. await probeAsync( _gl, sync, 4 );
  54227. // read the data and delete the buffer
  54228. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54229. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  54230. _gl.deleteBuffer( glBuffer );
  54231. _gl.deleteSync( sync );
  54232. return buffer;
  54233. } else {
  54234. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  54235. }
  54236. }
  54237. };
  54238. /**
  54239. * Copies pixels from the current bound framebuffer into the given texture.
  54240. *
  54241. * @param {FramebufferTexture} texture - The texture.
  54242. * @param {?Vector2} [position=null] - The start position of the copy operation.
  54243. * @param {number} [level=0] - The mip level. The default represents the base mip.
  54244. */
  54245. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  54246. const levelScale = Math.pow( 2, - level );
  54247. const width = Math.floor( texture.image.width * levelScale );
  54248. const height = Math.floor( texture.image.height * levelScale );
  54249. const x = position !== null ? position.x : 0;
  54250. const y = position !== null ? position.y : 0;
  54251. textures.setTexture2D( texture, 0 );
  54252. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  54253. state.unbindTexture();
  54254. };
  54255. const _srcFramebuffer = _gl.createFramebuffer();
  54256. const _dstFramebuffer = _gl.createFramebuffer();
  54257. /**
  54258. * Copies data of the given source texture into a destination texture.
  54259. *
  54260. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  54261. * {@link WebGLRenderer#initRenderTarget}.
  54262. *
  54263. * @param {Texture} srcTexture - The source texture.
  54264. * @param {Texture} dstTexture - The destination texture.
  54265. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  54266. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  54267. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  54268. * @param {?number} [dstLevel=null] - The destination mipmap level.
  54269. */
  54270. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  54271. // support the previous signature with just a single dst mipmap level
  54272. if ( dstLevel === null ) {
  54273. if ( srcLevel !== 0 ) {
  54274. // @deprecated, r171
  54275. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  54276. dstLevel = srcLevel;
  54277. srcLevel = 0;
  54278. } else {
  54279. dstLevel = 0;
  54280. }
  54281. }
  54282. // gather the necessary dimensions to copy
  54283. let width, height, depth, minX, minY, minZ;
  54284. let dstX, dstY, dstZ;
  54285. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  54286. if ( srcRegion !== null ) {
  54287. width = srcRegion.max.x - srcRegion.min.x;
  54288. height = srcRegion.max.y - srcRegion.min.y;
  54289. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  54290. minX = srcRegion.min.x;
  54291. minY = srcRegion.min.y;
  54292. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  54293. } else {
  54294. const levelScale = Math.pow( 2, - srcLevel );
  54295. width = Math.floor( image.width * levelScale );
  54296. height = Math.floor( image.height * levelScale );
  54297. if ( srcTexture.isDataArrayTexture ) {
  54298. depth = image.depth;
  54299. } else if ( srcTexture.isData3DTexture ) {
  54300. depth = Math.floor( image.depth * levelScale );
  54301. } else {
  54302. depth = 1;
  54303. }
  54304. minX = 0;
  54305. minY = 0;
  54306. minZ = 0;
  54307. }
  54308. if ( dstPosition !== null ) {
  54309. dstX = dstPosition.x;
  54310. dstY = dstPosition.y;
  54311. dstZ = dstPosition.z;
  54312. } else {
  54313. dstX = 0;
  54314. dstY = 0;
  54315. dstZ = 0;
  54316. }
  54317. // Set up the destination target
  54318. const glFormat = utils.convert( dstTexture.format );
  54319. const glType = utils.convert( dstTexture.type );
  54320. let glTarget;
  54321. if ( dstTexture.isData3DTexture ) {
  54322. textures.setTexture3D( dstTexture, 0 );
  54323. glTarget = _gl.TEXTURE_3D;
  54324. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  54325. textures.setTexture2DArray( dstTexture, 0 );
  54326. glTarget = _gl.TEXTURE_2D_ARRAY;
  54327. } else {
  54328. textures.setTexture2D( dstTexture, 0 );
  54329. glTarget = _gl.TEXTURE_2D;
  54330. }
  54331. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  54332. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  54333. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  54334. // used for copying data from cpu
  54335. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  54336. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  54337. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  54338. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  54339. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  54340. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  54341. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  54342. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  54343. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  54344. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  54345. // set up the src texture
  54346. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  54347. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  54348. if ( srcTexture.isDepthTexture ) {
  54349. const srcTextureProperties = properties.get( srcTexture );
  54350. const dstTextureProperties = properties.get( dstTexture );
  54351. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  54352. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  54353. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  54354. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  54355. for ( let i = 0; i < depth; i ++ ) {
  54356. // if the source or destination are a 3d target then a layer needs to be bound
  54357. if ( isSrc3D ) {
  54358. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  54359. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  54360. }
  54361. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  54362. }
  54363. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54364. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54365. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  54366. // get the appropriate frame buffers
  54367. const srcTextureProperties = properties.get( srcTexture );
  54368. const dstTextureProperties = properties.get( dstTexture );
  54369. // bind the frame buffer targets
  54370. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  54371. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  54372. for ( let i = 0; i < depth; i ++ ) {
  54373. // assign the correct layers and mip maps to the frame buffers
  54374. if ( isSrc3D ) {
  54375. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  54376. } else {
  54377. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  54378. }
  54379. if ( isDst3D ) {
  54380. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  54381. } else {
  54382. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  54383. }
  54384. // copy the data using the fastest function that can achieve the copy
  54385. if ( srcLevel !== 0 ) {
  54386. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  54387. } else if ( isDst3D ) {
  54388. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  54389. } else {
  54390. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  54391. }
  54392. }
  54393. // unbind read, draw buffers
  54394. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54395. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54396. } else {
  54397. if ( isDst3D ) {
  54398. // copy data into the 3d texture
  54399. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  54400. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  54401. } else if ( dstTexture.isCompressedArrayTexture ) {
  54402. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  54403. } else {
  54404. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  54405. }
  54406. } else {
  54407. // copy data into the 2d texture
  54408. if ( srcTexture.isDataTexture ) {
  54409. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  54410. } else if ( srcTexture.isCompressedTexture ) {
  54411. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  54412. } else {
  54413. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  54414. }
  54415. }
  54416. }
  54417. // reset values
  54418. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  54419. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  54420. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  54421. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  54422. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  54423. // Generate mipmaps only when copying level 0
  54424. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54425. _gl.generateMipmap( glTarget );
  54426. }
  54427. state.unbindTexture();
  54428. };
  54429. /**
  54430. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  54431. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  54432. * rendered to.
  54433. *
  54434. * @param {WebGLRenderTarget} target - The render target.
  54435. */
  54436. this.initRenderTarget = function ( target ) {
  54437. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  54438. textures.setupRenderTarget( target );
  54439. }
  54440. };
  54441. /**
  54442. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  54443. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  54444. *
  54445. * @param {Texture} texture - The texture.
  54446. */
  54447. this.initTexture = function ( texture ) {
  54448. if ( texture.isCubeTexture ) {
  54449. textures.setTextureCube( texture, 0 );
  54450. } else if ( texture.isData3DTexture ) {
  54451. textures.setTexture3D( texture, 0 );
  54452. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54453. textures.setTexture2DArray( texture, 0 );
  54454. } else {
  54455. textures.setTexture2D( texture, 0 );
  54456. }
  54457. state.unbindTexture();
  54458. };
  54459. /**
  54460. * Can be used to reset the internal WebGL state. This method is mostly
  54461. * relevant for applications which share a single WebGL context across
  54462. * multiple WebGL libraries.
  54463. */
  54464. this.resetState = function () {
  54465. _currentActiveCubeFace = 0;
  54466. _currentActiveMipmapLevel = 0;
  54467. _currentRenderTarget = null;
  54468. state.reset();
  54469. bindingStates.reset();
  54470. };
  54471. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54472. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54473. }
  54474. }
  54475. /**
  54476. * Defines the coordinate system of the renderer.
  54477. *
  54478. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  54479. *
  54480. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  54481. * @default WebGLCoordinateSystem
  54482. * @readonly
  54483. */
  54484. get coordinateSystem() {
  54485. return WebGLCoordinateSystem;
  54486. }
  54487. /**
  54488. * Defines the output color space of the renderer.
  54489. *
  54490. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  54491. * @default SRGBColorSpace
  54492. */
  54493. get outputColorSpace() {
  54494. return this._outputColorSpace;
  54495. }
  54496. set outputColorSpace( colorSpace ) {
  54497. this._outputColorSpace = colorSpace;
  54498. const gl = this.getContext();
  54499. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  54500. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  54501. }
  54502. }
  54503. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  54504. exports.AddEquation = AddEquation;
  54505. exports.AddOperation = AddOperation;
  54506. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  54507. exports.AdditiveBlending = AdditiveBlending;
  54508. exports.AgXToneMapping = AgXToneMapping;
  54509. exports.AlphaFormat = AlphaFormat;
  54510. exports.AlwaysCompare = AlwaysCompare;
  54511. exports.AlwaysDepth = AlwaysDepth;
  54512. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  54513. exports.AmbientLight = AmbientLight;
  54514. exports.AnimationAction = AnimationAction;
  54515. exports.AnimationClip = AnimationClip;
  54516. exports.AnimationLoader = AnimationLoader;
  54517. exports.AnimationMixer = AnimationMixer;
  54518. exports.AnimationObjectGroup = AnimationObjectGroup;
  54519. exports.AnimationUtils = AnimationUtils;
  54520. exports.ArcCurve = ArcCurve;
  54521. exports.ArrayCamera = ArrayCamera;
  54522. exports.ArrowHelper = ArrowHelper;
  54523. exports.AttachedBindMode = AttachedBindMode;
  54524. exports.Audio = Audio;
  54525. exports.AudioAnalyser = AudioAnalyser;
  54526. exports.AudioContext = AudioContext;
  54527. exports.AudioListener = AudioListener;
  54528. exports.AudioLoader = AudioLoader;
  54529. exports.AxesHelper = AxesHelper;
  54530. exports.BackSide = BackSide;
  54531. exports.BasicDepthPacking = BasicDepthPacking;
  54532. exports.BasicShadowMap = BasicShadowMap;
  54533. exports.BatchedMesh = BatchedMesh;
  54534. exports.Bone = Bone;
  54535. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  54536. exports.Box2 = Box2;
  54537. exports.Box3 = Box3;
  54538. exports.Box3Helper = Box3Helper;
  54539. exports.BoxGeometry = BoxGeometry;
  54540. exports.BoxHelper = BoxHelper;
  54541. exports.BufferAttribute = BufferAttribute;
  54542. exports.BufferGeometry = BufferGeometry;
  54543. exports.BufferGeometryLoader = BufferGeometryLoader;
  54544. exports.ByteType = ByteType;
  54545. exports.Cache = Cache;
  54546. exports.Camera = Camera;
  54547. exports.CameraHelper = CameraHelper;
  54548. exports.CanvasTexture = CanvasTexture;
  54549. exports.CapsuleGeometry = CapsuleGeometry;
  54550. exports.CatmullRomCurve3 = CatmullRomCurve3;
  54551. exports.CineonToneMapping = CineonToneMapping;
  54552. exports.CircleGeometry = CircleGeometry;
  54553. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  54554. exports.Clock = Clock;
  54555. exports.Color = Color;
  54556. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  54557. exports.ColorManagement = ColorManagement;
  54558. exports.CompressedArrayTexture = CompressedArrayTexture;
  54559. exports.CompressedCubeTexture = CompressedCubeTexture;
  54560. exports.CompressedTexture = CompressedTexture;
  54561. exports.CompressedTextureLoader = CompressedTextureLoader;
  54562. exports.ConeGeometry = ConeGeometry;
  54563. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  54564. exports.ConstantColorFactor = ConstantColorFactor;
  54565. exports.Controls = Controls;
  54566. exports.CubeCamera = CubeCamera;
  54567. exports.CubeDepthTexture = CubeDepthTexture;
  54568. exports.CubeReflectionMapping = CubeReflectionMapping;
  54569. exports.CubeRefractionMapping = CubeRefractionMapping;
  54570. exports.CubeTexture = CubeTexture;
  54571. exports.CubeTextureLoader = CubeTextureLoader;
  54572. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  54573. exports.CubicBezierCurve = CubicBezierCurve;
  54574. exports.CubicBezierCurve3 = CubicBezierCurve3;
  54575. exports.CubicInterpolant = CubicInterpolant;
  54576. exports.CullFaceBack = CullFaceBack;
  54577. exports.CullFaceFront = CullFaceFront;
  54578. exports.CullFaceFrontBack = CullFaceFrontBack;
  54579. exports.CullFaceNone = CullFaceNone;
  54580. exports.Curve = Curve;
  54581. exports.CurvePath = CurvePath;
  54582. exports.CustomBlending = CustomBlending;
  54583. exports.CustomToneMapping = CustomToneMapping;
  54584. exports.CylinderGeometry = CylinderGeometry;
  54585. exports.Cylindrical = Cylindrical;
  54586. exports.Data3DTexture = Data3DTexture;
  54587. exports.DataArrayTexture = DataArrayTexture;
  54588. exports.DataTexture = DataTexture;
  54589. exports.DataTextureLoader = DataTextureLoader;
  54590. exports.DataUtils = DataUtils;
  54591. exports.DecrementStencilOp = DecrementStencilOp;
  54592. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  54593. exports.DefaultLoadingManager = DefaultLoadingManager;
  54594. exports.DepthFormat = DepthFormat;
  54595. exports.DepthStencilFormat = DepthStencilFormat;
  54596. exports.DepthTexture = DepthTexture;
  54597. exports.DetachedBindMode = DetachedBindMode;
  54598. exports.DirectionalLight = DirectionalLight;
  54599. exports.DirectionalLightHelper = DirectionalLightHelper;
  54600. exports.DiscreteInterpolant = DiscreteInterpolant;
  54601. exports.DodecahedronGeometry = DodecahedronGeometry;
  54602. exports.DoubleSide = DoubleSide;
  54603. exports.DstAlphaFactor = DstAlphaFactor;
  54604. exports.DstColorFactor = DstColorFactor;
  54605. exports.DynamicCopyUsage = DynamicCopyUsage;
  54606. exports.DynamicDrawUsage = DynamicDrawUsage;
  54607. exports.DynamicReadUsage = DynamicReadUsage;
  54608. exports.EdgesGeometry = EdgesGeometry;
  54609. exports.EllipseCurve = EllipseCurve;
  54610. exports.EqualCompare = EqualCompare;
  54611. exports.EqualDepth = EqualDepth;
  54612. exports.EqualStencilFunc = EqualStencilFunc;
  54613. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  54614. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  54615. exports.Euler = Euler;
  54616. exports.EventDispatcher = EventDispatcher;
  54617. exports.ExternalTexture = ExternalTexture;
  54618. exports.ExtrudeGeometry = ExtrudeGeometry;
  54619. exports.FileLoader = FileLoader;
  54620. exports.Float16BufferAttribute = Float16BufferAttribute;
  54621. exports.Float32BufferAttribute = Float32BufferAttribute;
  54622. exports.FloatType = FloatType;
  54623. exports.Fog = Fog;
  54624. exports.FogExp2 = FogExp2;
  54625. exports.FramebufferTexture = FramebufferTexture;
  54626. exports.FrontSide = FrontSide;
  54627. exports.Frustum = Frustum;
  54628. exports.FrustumArray = FrustumArray;
  54629. exports.GLBufferAttribute = GLBufferAttribute;
  54630. exports.GLSL1 = GLSL1;
  54631. exports.GLSL3 = GLSL3;
  54632. exports.GreaterCompare = GreaterCompare;
  54633. exports.GreaterDepth = GreaterDepth;
  54634. exports.GreaterEqualCompare = GreaterEqualCompare;
  54635. exports.GreaterEqualDepth = GreaterEqualDepth;
  54636. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  54637. exports.GreaterStencilFunc = GreaterStencilFunc;
  54638. exports.GridHelper = GridHelper;
  54639. exports.Group = Group;
  54640. exports.HalfFloatType = HalfFloatType;
  54641. exports.HemisphereLight = HemisphereLight;
  54642. exports.HemisphereLightHelper = HemisphereLightHelper;
  54643. exports.IcosahedronGeometry = IcosahedronGeometry;
  54644. exports.ImageBitmapLoader = ImageBitmapLoader;
  54645. exports.ImageLoader = ImageLoader;
  54646. exports.ImageUtils = ImageUtils;
  54647. exports.IncrementStencilOp = IncrementStencilOp;
  54648. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  54649. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  54650. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  54651. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  54652. exports.InstancedMesh = InstancedMesh;
  54653. exports.Int16BufferAttribute = Int16BufferAttribute;
  54654. exports.Int32BufferAttribute = Int32BufferAttribute;
  54655. exports.Int8BufferAttribute = Int8BufferAttribute;
  54656. exports.IntType = IntType;
  54657. exports.InterleavedBuffer = InterleavedBuffer;
  54658. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  54659. exports.Interpolant = Interpolant;
  54660. exports.InterpolateDiscrete = InterpolateDiscrete;
  54661. exports.InterpolateLinear = InterpolateLinear;
  54662. exports.InterpolateSmooth = InterpolateSmooth;
  54663. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  54664. exports.InterpolationSamplingType = InterpolationSamplingType;
  54665. exports.InvertStencilOp = InvertStencilOp;
  54666. exports.KeepStencilOp = KeepStencilOp;
  54667. exports.KeyframeTrack = KeyframeTrack;
  54668. exports.LOD = LOD;
  54669. exports.LatheGeometry = LatheGeometry;
  54670. exports.Layers = Layers;
  54671. exports.LessCompare = LessCompare;
  54672. exports.LessDepth = LessDepth;
  54673. exports.LessEqualCompare = LessEqualCompare;
  54674. exports.LessEqualDepth = LessEqualDepth;
  54675. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  54676. exports.LessStencilFunc = LessStencilFunc;
  54677. exports.Light = Light;
  54678. exports.LightProbe = LightProbe;
  54679. exports.Line = Line;
  54680. exports.Line3 = Line3;
  54681. exports.LineBasicMaterial = LineBasicMaterial;
  54682. exports.LineCurve = LineCurve;
  54683. exports.LineCurve3 = LineCurve3;
  54684. exports.LineDashedMaterial = LineDashedMaterial;
  54685. exports.LineLoop = LineLoop;
  54686. exports.LineSegments = LineSegments;
  54687. exports.LinearFilter = LinearFilter;
  54688. exports.LinearInterpolant = LinearInterpolant;
  54689. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  54690. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  54691. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  54692. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  54693. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  54694. exports.LinearToneMapping = LinearToneMapping;
  54695. exports.LinearTransfer = LinearTransfer;
  54696. exports.Loader = Loader;
  54697. exports.LoaderUtils = LoaderUtils;
  54698. exports.LoadingManager = LoadingManager;
  54699. exports.LoopOnce = LoopOnce;
  54700. exports.LoopPingPong = LoopPingPong;
  54701. exports.LoopRepeat = LoopRepeat;
  54702. exports.MOUSE = MOUSE;
  54703. exports.Material = Material;
  54704. exports.MaterialLoader = MaterialLoader;
  54705. exports.MathUtils = MathUtils;
  54706. exports.Matrix2 = Matrix2;
  54707. exports.Matrix3 = Matrix3;
  54708. exports.Matrix4 = Matrix4;
  54709. exports.MaxEquation = MaxEquation;
  54710. exports.Mesh = Mesh;
  54711. exports.MeshBasicMaterial = MeshBasicMaterial;
  54712. exports.MeshDepthMaterial = MeshDepthMaterial;
  54713. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  54714. exports.MeshLambertMaterial = MeshLambertMaterial;
  54715. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  54716. exports.MeshNormalMaterial = MeshNormalMaterial;
  54717. exports.MeshPhongMaterial = MeshPhongMaterial;
  54718. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  54719. exports.MeshStandardMaterial = MeshStandardMaterial;
  54720. exports.MeshToonMaterial = MeshToonMaterial;
  54721. exports.MinEquation = MinEquation;
  54722. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  54723. exports.MixOperation = MixOperation;
  54724. exports.MultiplyBlending = MultiplyBlending;
  54725. exports.MultiplyOperation = MultiplyOperation;
  54726. exports.NearestFilter = NearestFilter;
  54727. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  54728. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  54729. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  54730. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  54731. exports.NeutralToneMapping = NeutralToneMapping;
  54732. exports.NeverCompare = NeverCompare;
  54733. exports.NeverDepth = NeverDepth;
  54734. exports.NeverStencilFunc = NeverStencilFunc;
  54735. exports.NoBlending = NoBlending;
  54736. exports.NoColorSpace = NoColorSpace;
  54737. exports.NoNormalPacking = NoNormalPacking;
  54738. exports.NoToneMapping = NoToneMapping;
  54739. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  54740. exports.NormalBlending = NormalBlending;
  54741. exports.NormalGAPacking = NormalGAPacking;
  54742. exports.NormalRGPacking = NormalRGPacking;
  54743. exports.NotEqualCompare = NotEqualCompare;
  54744. exports.NotEqualDepth = NotEqualDepth;
  54745. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  54746. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  54747. exports.Object3D = Object3D;
  54748. exports.ObjectLoader = ObjectLoader;
  54749. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  54750. exports.OctahedronGeometry = OctahedronGeometry;
  54751. exports.OneFactor = OneFactor;
  54752. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  54753. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  54754. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  54755. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  54756. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  54757. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  54758. exports.OrthographicCamera = OrthographicCamera;
  54759. exports.PCFShadowMap = PCFShadowMap;
  54760. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  54761. exports.PMREMGenerator = PMREMGenerator;
  54762. exports.Path = Path;
  54763. exports.PerspectiveCamera = PerspectiveCamera;
  54764. exports.Plane = Plane;
  54765. exports.PlaneGeometry = PlaneGeometry;
  54766. exports.PlaneHelper = PlaneHelper;
  54767. exports.PointLight = PointLight;
  54768. exports.PointLightHelper = PointLightHelper;
  54769. exports.Points = Points;
  54770. exports.PointsMaterial = PointsMaterial;
  54771. exports.PolarGridHelper = PolarGridHelper;
  54772. exports.PolyhedronGeometry = PolyhedronGeometry;
  54773. exports.PositionalAudio = PositionalAudio;
  54774. exports.PropertyBinding = PropertyBinding;
  54775. exports.PropertyMixer = PropertyMixer;
  54776. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  54777. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  54778. exports.Quaternion = Quaternion;
  54779. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  54780. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  54781. exports.R11_EAC_Format = R11_EAC_Format;
  54782. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  54783. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  54784. exports.REVISION = REVISION;
  54785. exports.RG11_EAC_Format = RG11_EAC_Format;
  54786. exports.RGBADepthPacking = RGBADepthPacking;
  54787. exports.RGBAFormat = RGBAFormat;
  54788. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54789. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54790. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54791. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54792. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54793. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54794. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54795. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54796. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54797. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54798. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54799. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54800. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54801. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54802. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54803. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54804. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54805. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54806. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54807. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54808. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54809. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54810. exports.RGBDepthPacking = RGBDepthPacking;
  54811. exports.RGBFormat = RGBFormat;
  54812. exports.RGBIntegerFormat = RGBIntegerFormat;
  54813. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54814. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54815. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54816. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54817. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54818. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54819. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54820. exports.RGDepthPacking = RGDepthPacking;
  54821. exports.RGFormat = RGFormat;
  54822. exports.RGIntegerFormat = RGIntegerFormat;
  54823. exports.RawShaderMaterial = RawShaderMaterial;
  54824. exports.Ray = Ray;
  54825. exports.Raycaster = Raycaster;
  54826. exports.RectAreaLight = RectAreaLight;
  54827. exports.RedFormat = RedFormat;
  54828. exports.RedIntegerFormat = RedIntegerFormat;
  54829. exports.ReinhardToneMapping = ReinhardToneMapping;
  54830. exports.RenderTarget = RenderTarget;
  54831. exports.RenderTarget3D = RenderTarget3D;
  54832. exports.RepeatWrapping = RepeatWrapping;
  54833. exports.ReplaceStencilOp = ReplaceStencilOp;
  54834. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54835. exports.RingGeometry = RingGeometry;
  54836. exports.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format;
  54837. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54838. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54839. exports.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format;
  54840. exports.SRGBColorSpace = SRGBColorSpace;
  54841. exports.SRGBTransfer = SRGBTransfer;
  54842. exports.Scene = Scene;
  54843. exports.ShaderChunk = ShaderChunk;
  54844. exports.ShaderLib = ShaderLib;
  54845. exports.ShaderMaterial = ShaderMaterial;
  54846. exports.ShadowMaterial = ShadowMaterial;
  54847. exports.Shape = Shape;
  54848. exports.ShapeGeometry = ShapeGeometry;
  54849. exports.ShapePath = ShapePath;
  54850. exports.ShapeUtils = ShapeUtils;
  54851. exports.ShortType = ShortType;
  54852. exports.Skeleton = Skeleton;
  54853. exports.SkeletonHelper = SkeletonHelper;
  54854. exports.SkinnedMesh = SkinnedMesh;
  54855. exports.Source = Source;
  54856. exports.Sphere = Sphere;
  54857. exports.SphereGeometry = SphereGeometry;
  54858. exports.Spherical = Spherical;
  54859. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54860. exports.SplineCurve = SplineCurve;
  54861. exports.SpotLight = SpotLight;
  54862. exports.SpotLightHelper = SpotLightHelper;
  54863. exports.Sprite = Sprite;
  54864. exports.SpriteMaterial = SpriteMaterial;
  54865. exports.SrcAlphaFactor = SrcAlphaFactor;
  54866. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54867. exports.SrcColorFactor = SrcColorFactor;
  54868. exports.StaticCopyUsage = StaticCopyUsage;
  54869. exports.StaticDrawUsage = StaticDrawUsage;
  54870. exports.StaticReadUsage = StaticReadUsage;
  54871. exports.StereoCamera = StereoCamera;
  54872. exports.StreamCopyUsage = StreamCopyUsage;
  54873. exports.StreamDrawUsage = StreamDrawUsage;
  54874. exports.StreamReadUsage = StreamReadUsage;
  54875. exports.StringKeyframeTrack = StringKeyframeTrack;
  54876. exports.SubtractEquation = SubtractEquation;
  54877. exports.SubtractiveBlending = SubtractiveBlending;
  54878. exports.TOUCH = TOUCH;
  54879. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54880. exports.TetrahedronGeometry = TetrahedronGeometry;
  54881. exports.Texture = Texture;
  54882. exports.TextureLoader = TextureLoader;
  54883. exports.TextureUtils = TextureUtils;
  54884. exports.Timer = Timer;
  54885. exports.TimestampQuery = TimestampQuery;
  54886. exports.TorusGeometry = TorusGeometry;
  54887. exports.TorusKnotGeometry = TorusKnotGeometry;
  54888. exports.Triangle = Triangle;
  54889. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  54890. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  54891. exports.TrianglesDrawMode = TrianglesDrawMode;
  54892. exports.TubeGeometry = TubeGeometry;
  54893. exports.UVMapping = UVMapping;
  54894. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  54895. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  54896. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  54897. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  54898. exports.Uniform = Uniform;
  54899. exports.UniformsGroup = UniformsGroup;
  54900. exports.UniformsLib = UniformsLib;
  54901. exports.UniformsUtils = UniformsUtils;
  54902. exports.UnsignedByteType = UnsignedByteType;
  54903. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  54904. exports.UnsignedInt248Type = UnsignedInt248Type;
  54905. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  54906. exports.UnsignedIntType = UnsignedIntType;
  54907. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  54908. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  54909. exports.UnsignedShortType = UnsignedShortType;
  54910. exports.VSMShadowMap = VSMShadowMap;
  54911. exports.Vector2 = Vector2;
  54912. exports.Vector3 = Vector3;
  54913. exports.Vector4 = Vector4;
  54914. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  54915. exports.VideoFrameTexture = VideoFrameTexture;
  54916. exports.VideoTexture = VideoTexture;
  54917. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  54918. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  54919. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  54920. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  54921. exports.WebGLRenderTarget = WebGLRenderTarget;
  54922. exports.WebGLRenderer = WebGLRenderer;
  54923. exports.WebGLUtils = WebGLUtils;
  54924. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  54925. exports.WebXRController = WebXRController;
  54926. exports.WireframeGeometry = WireframeGeometry;
  54927. exports.WrapAroundEnding = WrapAroundEnding;
  54928. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  54929. exports.ZeroFactor = ZeroFactor;
  54930. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  54931. exports.ZeroStencilOp = ZeroStencilOp;
  54932. exports.createCanvasElement = createCanvasElement;
  54933. exports.error = error;
  54934. exports.getConsoleFunction = getConsoleFunction;
  54935. exports.log = log;
  54936. exports.setConsoleFunction = setConsoleFunction;
  54937. exports.warn = warn;
  54938. exports.warnOnce = warnOnce;
粤ICP备19079148号