three.cjs 1.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242
  1. /**
  2. * @license
  3. * Copyright 2010-2025 Three.js Authors
  4. * SPDX-License-Identifier: MIT
  5. */
  6. 'use strict';
  7. const REVISION = '182dev';
  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. * The depth value is not packed.
  1111. *
  1112. * @type {number}
  1113. * @constant
  1114. */
  1115. const IdentityDepthPacking = 3204;
  1116. /**
  1117. * Normal information is relative to the underlying surface.
  1118. *
  1119. * @type {number}
  1120. * @constant
  1121. */
  1122. const TangentSpaceNormalMap = 0;
  1123. /**
  1124. * Normal information is relative to the object orientation.
  1125. *
  1126. * @type {number}
  1127. * @constant
  1128. */
  1129. const ObjectSpaceNormalMap = 1;
  1130. // Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
  1131. /**
  1132. * No color space.
  1133. *
  1134. * @type {string}
  1135. * @constant
  1136. */
  1137. const NoColorSpace = '';
  1138. /**
  1139. * sRGB color space.
  1140. *
  1141. * @type {string}
  1142. * @constant
  1143. */
  1144. const SRGBColorSpace = 'srgb';
  1145. /**
  1146. * sRGB-linear color space.
  1147. *
  1148. * @type {string}
  1149. * @constant
  1150. */
  1151. const LinearSRGBColorSpace = 'srgb-linear';
  1152. /**
  1153. * Linear transfer function.
  1154. *
  1155. * @type {string}
  1156. * @constant
  1157. */
  1158. const LinearTransfer = 'linear';
  1159. /**
  1160. * sRGB transfer function.
  1161. *
  1162. * @type {string}
  1163. * @constant
  1164. */
  1165. const SRGBTransfer = 'srgb';
  1166. /**
  1167. * No normal map packing.
  1168. *
  1169. * @type {string}
  1170. * @constant
  1171. */
  1172. const NoNormalPacking = '';
  1173. /**
  1174. * Normal RG packing.
  1175. *
  1176. * @type {string}
  1177. * @constant
  1178. */
  1179. const NormalRGPacking = 'rg';
  1180. /**
  1181. * Normal GA packing.
  1182. *
  1183. * @type {string}
  1184. * @constant
  1185. */
  1186. const NormalGAPacking = 'ga';
  1187. /**
  1188. * Sets the stencil buffer value to `0`.
  1189. *
  1190. * @type {number}
  1191. * @constant
  1192. */
  1193. const ZeroStencilOp = 0;
  1194. /**
  1195. * Keeps the current value.
  1196. *
  1197. * @type {number}
  1198. * @constant
  1199. */
  1200. const KeepStencilOp = 7680;
  1201. /**
  1202. * Sets the stencil buffer value to the specified reference value.
  1203. *
  1204. * @type {number}
  1205. * @constant
  1206. */
  1207. const ReplaceStencilOp = 7681;
  1208. /**
  1209. * Increments the current stencil buffer value. Clamps to the maximum representable unsigned value.
  1210. *
  1211. * @type {number}
  1212. * @constant
  1213. */
  1214. const IncrementStencilOp = 7682;
  1215. /**
  1216. * Decrements the current stencil buffer value. Clamps to `0`.
  1217. *
  1218. * @type {number}
  1219. * @constant
  1220. */
  1221. const DecrementStencilOp = 7683;
  1222. /**
  1223. * Increments the current stencil buffer value. Wraps stencil buffer value to zero when incrementing
  1224. * the maximum representable unsigned value.
  1225. *
  1226. * @type {number}
  1227. * @constant
  1228. */
  1229. const IncrementWrapStencilOp = 34055;
  1230. /**
  1231. * Decrements the current stencil buffer value. Wraps stencil buffer value to the maximum representable
  1232. * unsigned value when decrementing a stencil buffer value of `0`.
  1233. *
  1234. * @type {number}
  1235. * @constant
  1236. */
  1237. const DecrementWrapStencilOp = 34056;
  1238. /**
  1239. * Inverts the current stencil buffer value bitwise.
  1240. *
  1241. * @type {number}
  1242. * @constant
  1243. */
  1244. const InvertStencilOp = 5386;
  1245. /**
  1246. * Will never return true.
  1247. *
  1248. * @type {number}
  1249. * @constant
  1250. */
  1251. const NeverStencilFunc = 512;
  1252. /**
  1253. * Will return true if the stencil reference value is less than the current stencil value.
  1254. *
  1255. * @type {number}
  1256. * @constant
  1257. */
  1258. const LessStencilFunc = 513;
  1259. /**
  1260. * Will return true if the stencil reference value is equal to the current stencil value.
  1261. *
  1262. * @type {number}
  1263. * @constant
  1264. */
  1265. const EqualStencilFunc = 514;
  1266. /**
  1267. * Will return true if the stencil reference value is less than or equal to the current stencil value.
  1268. *
  1269. * @type {number}
  1270. * @constant
  1271. */
  1272. const LessEqualStencilFunc = 515;
  1273. /**
  1274. * Will return true if the stencil reference value is greater than the current stencil value.
  1275. *
  1276. * @type {number}
  1277. * @constant
  1278. */
  1279. const GreaterStencilFunc = 516;
  1280. /**
  1281. * Will return true if the stencil reference value is not equal to the current stencil value.
  1282. *
  1283. * @type {number}
  1284. * @constant
  1285. */
  1286. const NotEqualStencilFunc = 517;
  1287. /**
  1288. * Will return true if the stencil reference value is greater than or equal to the current stencil value.
  1289. *
  1290. * @type {number}
  1291. * @constant
  1292. */
  1293. const GreaterEqualStencilFunc = 518;
  1294. /**
  1295. * Will always return true.
  1296. *
  1297. * @type {number}
  1298. * @constant
  1299. */
  1300. const AlwaysStencilFunc = 519;
  1301. /**
  1302. * Never pass.
  1303. *
  1304. * @type {number}
  1305. * @constant
  1306. */
  1307. const NeverCompare = 512;
  1308. /**
  1309. * Pass if the incoming value is less than the texture value.
  1310. *
  1311. * @type {number}
  1312. * @constant
  1313. */
  1314. const LessCompare = 513;
  1315. /**
  1316. * Pass if the incoming value equals the texture value.
  1317. *
  1318. * @type {number}
  1319. * @constant
  1320. */
  1321. const EqualCompare = 514;
  1322. /**
  1323. * Pass if the incoming value is less than or equal to the texture value.
  1324. *
  1325. * @type {number}
  1326. * @constant
  1327. */
  1328. const LessEqualCompare = 515;
  1329. /**
  1330. * Pass if the incoming value is greater than the texture value.
  1331. *
  1332. * @type {number}
  1333. * @constant
  1334. */
  1335. const GreaterCompare = 516;
  1336. /**
  1337. * Pass if the incoming value is not equal to the texture value.
  1338. *
  1339. * @type {number}
  1340. * @constant
  1341. */
  1342. const NotEqualCompare = 517;
  1343. /**
  1344. * Pass if the incoming value is greater than or equal to the texture value.
  1345. *
  1346. * @type {number}
  1347. * @constant
  1348. */
  1349. const GreaterEqualCompare = 518;
  1350. /**
  1351. * Always pass.
  1352. *
  1353. * @type {number}
  1354. * @constant
  1355. */
  1356. const AlwaysCompare = 519;
  1357. /**
  1358. * The contents are intended to be specified once by the application, and used many
  1359. * times as the source for drawing and image specification commands.
  1360. *
  1361. * @type {number}
  1362. * @constant
  1363. */
  1364. const StaticDrawUsage = 35044;
  1365. /**
  1366. * The contents are intended to be respecified repeatedly by the application, and
  1367. * used many times as the source for drawing and image specification commands.
  1368. *
  1369. * @type {number}
  1370. * @constant
  1371. */
  1372. const DynamicDrawUsage = 35048;
  1373. /**
  1374. * The contents are intended to be specified once by the application, and used at most
  1375. * a few times as the source for drawing and image specification commands.
  1376. *
  1377. * @type {number}
  1378. * @constant
  1379. */
  1380. const StreamDrawUsage = 35040;
  1381. /**
  1382. * The contents are intended to be specified once by reading data from the 3D API, and queried
  1383. * many times by the application.
  1384. *
  1385. * @type {number}
  1386. * @constant
  1387. */
  1388. const StaticReadUsage = 35045;
  1389. /**
  1390. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and queried
  1391. * many times by the application.
  1392. *
  1393. * @type {number}
  1394. * @constant
  1395. */
  1396. const DynamicReadUsage = 35049;
  1397. /**
  1398. * The contents are intended to be specified once by reading data from the 3D API, and queried at most
  1399. * a few times by the application
  1400. *
  1401. * @type {number}
  1402. * @constant
  1403. */
  1404. const StreamReadUsage = 35041;
  1405. /**
  1406. * The contents are intended to be specified once by reading data from the 3D API, and used many times as
  1407. * the source for WebGL drawing and image specification commands.
  1408. *
  1409. * @type {number}
  1410. * @constant
  1411. */
  1412. const StaticCopyUsage = 35046;
  1413. /**
  1414. * The contents are intended to be respecified repeatedly by reading data from the 3D API, and used many times
  1415. * as the source for WebGL drawing and image specification commands.
  1416. *
  1417. * @type {number}
  1418. * @constant
  1419. */
  1420. const DynamicCopyUsage = 35050;
  1421. /**
  1422. * The contents are intended to be specified once by reading data from the 3D API, and used at most a few times
  1423. * as the source for WebGL drawing and image specification commands.
  1424. *
  1425. * @type {number}
  1426. * @constant
  1427. */
  1428. const StreamCopyUsage = 35042;
  1429. /**
  1430. * GLSL 1 shader code.
  1431. *
  1432. * @type {string}
  1433. * @constant
  1434. */
  1435. const GLSL1 = '100';
  1436. /**
  1437. * GLSL 3 shader code.
  1438. *
  1439. * @type {string}
  1440. * @constant
  1441. */
  1442. const GLSL3 = '300 es';
  1443. /**
  1444. * WebGL coordinate system.
  1445. *
  1446. * @type {number}
  1447. * @constant
  1448. */
  1449. const WebGLCoordinateSystem = 2000;
  1450. /**
  1451. * WebGPU coordinate system.
  1452. *
  1453. * @type {number}
  1454. * @constant
  1455. */
  1456. const WebGPUCoordinateSystem = 2001;
  1457. /**
  1458. * Represents the different timestamp query types.
  1459. *
  1460. * @type {ConstantsTimestampQuery}
  1461. * @constant
  1462. */
  1463. const TimestampQuery = {
  1464. COMPUTE: 'compute',
  1465. RENDER: 'render'
  1466. };
  1467. /**
  1468. * Represents mouse buttons and interaction types in context of controls.
  1469. *
  1470. * @type {ConstantsInterpolationSamplingType}
  1471. * @constant
  1472. */
  1473. const InterpolationSamplingType = {
  1474. PERSPECTIVE: 'perspective',
  1475. LINEAR: 'linear',
  1476. FLAT: 'flat'
  1477. };
  1478. /**
  1479. * Represents the different interpolation sampling modes.
  1480. *
  1481. * @type {ConstantsInterpolationSamplingMode}
  1482. * @constant
  1483. */
  1484. const InterpolationSamplingMode = {
  1485. NORMAL: 'normal',
  1486. CENTROID: 'centroid',
  1487. SAMPLE: 'sample',
  1488. FIRST: 'first',
  1489. EITHER: 'either'
  1490. };
  1491. /**
  1492. * This type represents mouse buttons and interaction types in context of controls.
  1493. *
  1494. * @typedef {Object} ConstantsMouse
  1495. * @property {number} MIDDLE - The left mouse button.
  1496. * @property {number} LEFT - The middle mouse button.
  1497. * @property {number} RIGHT - The right mouse button.
  1498. * @property {number} ROTATE - A rotate interaction.
  1499. * @property {number} DOLLY - A dolly interaction.
  1500. * @property {number} PAN - A pan interaction.
  1501. **/
  1502. /**
  1503. * This type represents touch interaction types in context of controls.
  1504. *
  1505. * @typedef {Object} ConstantsTouch
  1506. * @property {number} ROTATE - A rotate interaction.
  1507. * @property {number} PAN - A pan interaction.
  1508. * @property {number} DOLLY_PAN - The dolly-pan interaction.
  1509. * @property {number} DOLLY_ROTATE - A dolly-rotate interaction.
  1510. **/
  1511. /**
  1512. * This type represents the different timestamp query types.
  1513. *
  1514. * @typedef {Object} ConstantsTimestampQuery
  1515. * @property {string} COMPUTE - A `compute` timestamp query.
  1516. * @property {string} RENDER - A `render` timestamp query.
  1517. **/
  1518. /**
  1519. * Represents the different interpolation sampling types.
  1520. *
  1521. * @typedef {Object} ConstantsInterpolationSamplingType
  1522. * @property {string} PERSPECTIVE - Perspective-correct interpolation.
  1523. * @property {string} LINEAR - Linear interpolation.
  1524. * @property {string} FLAT - Flat interpolation.
  1525. */
  1526. /**
  1527. * Represents the different interpolation sampling modes.
  1528. *
  1529. * @typedef {Object} ConstantsInterpolationSamplingMode
  1530. * @property {string} NORMAL - Normal sampling mode.
  1531. * @property {string} CENTROID - Centroid sampling mode.
  1532. * @property {string} SAMPLE - Sample-specific sampling mode.
  1533. * @property {string} FIRST - Flat interpolation using the first vertex.
  1534. * @property {string} EITHER - Flat interpolation using either vertex.
  1535. */
  1536. function arrayNeedsUint32( array ) {
  1537. // assumes larger values usually on last
  1538. for ( let i = array.length - 1; i >= 0; -- i ) {
  1539. if ( array[ i ] >= 65535 ) return true; // account for PRIMITIVE_RESTART_FIXED_INDEX, #24565
  1540. }
  1541. return false;
  1542. }
  1543. const TYPED_ARRAYS = {
  1544. Int8Array: Int8Array,
  1545. Uint8Array: Uint8Array,
  1546. Uint8ClampedArray: Uint8ClampedArray,
  1547. Int16Array: Int16Array,
  1548. Uint16Array: Uint16Array,
  1549. Int32Array: Int32Array,
  1550. Uint32Array: Uint32Array,
  1551. Float32Array: Float32Array,
  1552. Float64Array: Float64Array
  1553. };
  1554. function getTypedArray( type, buffer ) {
  1555. return new TYPED_ARRAYS[ type ]( buffer );
  1556. }
  1557. /**
  1558. * Returns `true` if the given object is a typed array.
  1559. *
  1560. * @param {any} array - The object to check.
  1561. * @return {boolean} Whether the given object is a typed array.
  1562. */
  1563. function isTypedArray( array ) {
  1564. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  1565. }
  1566. function createElementNS( name ) {
  1567. return document.createElementNS( 'http://www.w3.org/1999/xhtml', name );
  1568. }
  1569. function createCanvasElement() {
  1570. const canvas = createElementNS( 'canvas' );
  1571. canvas.style.display = 'block';
  1572. return canvas;
  1573. }
  1574. const _cache = {};
  1575. let _setConsoleFunction = null;
  1576. function setConsoleFunction( fn ) {
  1577. _setConsoleFunction = fn;
  1578. }
  1579. function getConsoleFunction() {
  1580. return _setConsoleFunction;
  1581. }
  1582. function log( ...params ) {
  1583. const message = 'THREE.' + params.shift();
  1584. if ( _setConsoleFunction ) {
  1585. _setConsoleFunction( 'log', message, ...params );
  1586. } else {
  1587. console.log( message, ...params );
  1588. }
  1589. }
  1590. function warn( ...params ) {
  1591. const message = 'THREE.' + params.shift();
  1592. if ( _setConsoleFunction ) {
  1593. _setConsoleFunction( 'warn', message, ...params );
  1594. } else {
  1595. console.warn( message, ...params );
  1596. }
  1597. }
  1598. function error( ...params ) {
  1599. const message = 'THREE.' + params.shift();
  1600. if ( _setConsoleFunction ) {
  1601. _setConsoleFunction( 'error', message, ...params );
  1602. } else {
  1603. console.error( message, ...params );
  1604. }
  1605. }
  1606. function warnOnce( ...params ) {
  1607. const message = params.join( ' ' );
  1608. if ( message in _cache ) return;
  1609. _cache[ message ] = true;
  1610. warn( ...params );
  1611. }
  1612. function probeAsync( gl, sync, interval ) {
  1613. return new Promise( function ( resolve, reject ) {
  1614. function probe() {
  1615. switch ( gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 ) ) {
  1616. case gl.WAIT_FAILED:
  1617. reject();
  1618. break;
  1619. case gl.TIMEOUT_EXPIRED:
  1620. setTimeout( probe, interval );
  1621. break;
  1622. default:
  1623. resolve();
  1624. }
  1625. }
  1626. setTimeout( probe, interval );
  1627. } );
  1628. }
  1629. /**
  1630. * This modules allows to dispatch event objects on custom JavaScript objects.
  1631. *
  1632. * Main repository: [eventdispatcher.js](https://github.com/mrdoob/eventdispatcher.js/)
  1633. *
  1634. * Code Example:
  1635. * ```js
  1636. * class Car extends EventDispatcher {
  1637. * start() {
  1638. * this.dispatchEvent( { type: 'start', message: 'vroom vroom!' } );
  1639. * }
  1640. *};
  1641. *
  1642. * // Using events with the custom object
  1643. * const car = new Car();
  1644. * car.addEventListener( 'start', function ( event ) {
  1645. * alert( event.message );
  1646. * } );
  1647. *
  1648. * car.start();
  1649. * ```
  1650. */
  1651. class EventDispatcher {
  1652. /**
  1653. * Adds the given event listener to the given event type.
  1654. *
  1655. * @param {string} type - The type of event to listen to.
  1656. * @param {Function} listener - The function that gets called when the event is fired.
  1657. */
  1658. addEventListener( type, listener ) {
  1659. if ( this._listeners === undefined ) this._listeners = {};
  1660. const listeners = this._listeners;
  1661. if ( listeners[ type ] === undefined ) {
  1662. listeners[ type ] = [];
  1663. }
  1664. if ( listeners[ type ].indexOf( listener ) === -1 ) {
  1665. listeners[ type ].push( listener );
  1666. }
  1667. }
  1668. /**
  1669. * Returns `true` if the given event listener has been added to the given event type.
  1670. *
  1671. * @param {string} type - The type of event.
  1672. * @param {Function} listener - The listener to check.
  1673. * @return {boolean} Whether the given event listener has been added to the given event type.
  1674. */
  1675. hasEventListener( type, listener ) {
  1676. const listeners = this._listeners;
  1677. if ( listeners === undefined ) return false;
  1678. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== -1;
  1679. }
  1680. /**
  1681. * Removes the given event listener from the given event type.
  1682. *
  1683. * @param {string} type - The type of event.
  1684. * @param {Function} listener - The listener to remove.
  1685. */
  1686. removeEventListener( type, listener ) {
  1687. const listeners = this._listeners;
  1688. if ( listeners === undefined ) return;
  1689. const listenerArray = listeners[ type ];
  1690. if ( listenerArray !== undefined ) {
  1691. const index = listenerArray.indexOf( listener );
  1692. if ( index !== -1 ) {
  1693. listenerArray.splice( index, 1 );
  1694. }
  1695. }
  1696. }
  1697. /**
  1698. * Dispatches an event object.
  1699. *
  1700. * @param {Object} event - The event that gets fired.
  1701. */
  1702. dispatchEvent( event ) {
  1703. const listeners = this._listeners;
  1704. if ( listeners === undefined ) return;
  1705. const listenerArray = listeners[ event.type ];
  1706. if ( listenerArray !== undefined ) {
  1707. event.target = this;
  1708. // Make a copy, in case listeners are removed while iterating.
  1709. const array = listenerArray.slice( 0 );
  1710. for ( let i = 0, l = array.length; i < l; i ++ ) {
  1711. array[ i ].call( this, event );
  1712. }
  1713. event.target = null;
  1714. }
  1715. }
  1716. }
  1717. 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' ];
  1718. let _seed = 1234567;
  1719. const DEG2RAD = Math.PI / 180;
  1720. const RAD2DEG = 180 / Math.PI;
  1721. /**
  1722. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  1723. * (universally unique identifier).
  1724. *
  1725. * @return {string} The UUID.
  1726. */
  1727. function generateUUID() {
  1728. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  1729. const d0 = Math.random() * 0xffffffff | 0;
  1730. const d1 = Math.random() * 0xffffffff | 0;
  1731. const d2 = Math.random() * 0xffffffff | 0;
  1732. const d3 = Math.random() * 0xffffffff | 0;
  1733. const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
  1734. _lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
  1735. _lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
  1736. _lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
  1737. // .toLowerCase() here flattens concatenated strings to save heap memory space.
  1738. return uuid.toLowerCase();
  1739. }
  1740. /**
  1741. * Clamps the given value between min and max.
  1742. *
  1743. * @param {number} value - The value to clamp.
  1744. * @param {number} min - The min value.
  1745. * @param {number} max - The max value.
  1746. * @return {number} The clamped value.
  1747. */
  1748. function clamp( value, min, max ) {
  1749. return Math.max( min, Math.min( max, value ) );
  1750. }
  1751. /**
  1752. * Computes the Euclidean modulo of the given parameters that
  1753. * is `( ( n % m ) + m ) % m`.
  1754. *
  1755. * @param {number} n - The first parameter.
  1756. * @param {number} m - The second parameter.
  1757. * @return {number} The Euclidean modulo.
  1758. */
  1759. function euclideanModulo( n, m ) {
  1760. // https://en.wikipedia.org/wiki/Modulo_operation
  1761. return ( ( n % m ) + m ) % m;
  1762. }
  1763. /**
  1764. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  1765. * for the given value.
  1766. *
  1767. * @param {number} x - The value to be mapped.
  1768. * @param {number} a1 - Minimum value for range A.
  1769. * @param {number} a2 - Maximum value for range A.
  1770. * @param {number} b1 - Minimum value for range B.
  1771. * @param {number} b2 - Maximum value for range B.
  1772. * @return {number} The mapped value.
  1773. */
  1774. function mapLinear( x, a1, a2, b1, b2 ) {
  1775. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  1776. }
  1777. /**
  1778. * Returns the percentage in the closed interval `[0, 1]` of the given value
  1779. * between the start and end point.
  1780. *
  1781. * @param {number} x - The start point
  1782. * @param {number} y - The end point.
  1783. * @param {number} value - A value between start and end.
  1784. * @return {number} The interpolation factor.
  1785. */
  1786. function inverseLerp( x, y, value ) {
  1787. // https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
  1788. if ( x !== y ) {
  1789. return ( value - x ) / ( y - x );
  1790. } else {
  1791. return 0;
  1792. }
  1793. }
  1794. /**
  1795. * Returns a value linearly interpolated from two known points based on the given interval -
  1796. * `t = 0` will return `x` and `t = 1` will return `y`.
  1797. *
  1798. * @param {number} x - The start point
  1799. * @param {number} y - The end point.
  1800. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  1801. * @return {number} The interpolated value.
  1802. */
  1803. function lerp( x, y, t ) {
  1804. return ( 1 - t ) * x + t * y;
  1805. }
  1806. /**
  1807. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  1808. * time to maintain frame rate independent movement. For details, see
  1809. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  1810. *
  1811. * @param {number} x - The current point.
  1812. * @param {number} y - The target point.
  1813. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  1814. * and a lower value will make the movement more gradual.
  1815. * @param {number} dt - Delta time in seconds.
  1816. * @return {number} The interpolated value.
  1817. */
  1818. function damp( x, y, lambda, dt ) {
  1819. return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
  1820. }
  1821. /**
  1822. * Returns a value that alternates between `0` and the given `length` parameter.
  1823. *
  1824. * @param {number} x - The value to pingpong.
  1825. * @param {number} [length=1] - The positive value the function will pingpong to.
  1826. * @return {number} The alternated value.
  1827. */
  1828. function pingpong( x, length = 1 ) {
  1829. // https://www.desmos.com/calculator/vcsjnyz7x4
  1830. return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
  1831. }
  1832. /**
  1833. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  1834. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  1835. * the `min` and `max`.
  1836. *
  1837. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  1838. *
  1839. * @param {number} x - The value to evaluate based on its position between min and max.
  1840. * @param {number} min - The min value. Any x value below min will be `0`.
  1841. * @param {number} max - The max value. Any x value above max will be `1`.
  1842. * @return {number} The alternated value.
  1843. */
  1844. function smoothstep( x, min, max ) {
  1845. if ( x <= min ) return 0;
  1846. if ( x >= max ) return 1;
  1847. x = ( x - min ) / ( max - min );
  1848. return x * x * ( 3 - 2 * x );
  1849. }
  1850. /**
  1851. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  1852. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  1853. *
  1854. * @param {number} x - The value to evaluate based on its position between min and max.
  1855. * @param {number} min - The min value. Any x value below min will be `0`.
  1856. * @param {number} max - The max value. Any x value above max will be `1`.
  1857. * @return {number} The alternated value.
  1858. */
  1859. function smootherstep( x, min, max ) {
  1860. if ( x <= min ) return 0;
  1861. if ( x >= max ) return 1;
  1862. x = ( x - min ) / ( max - min );
  1863. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  1864. }
  1865. /**
  1866. * Returns a random integer from `<low, high>` interval.
  1867. *
  1868. * @param {number} low - The lower value boundary.
  1869. * @param {number} high - The upper value boundary
  1870. * @return {number} A random integer.
  1871. */
  1872. function randInt( low, high ) {
  1873. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  1874. }
  1875. /**
  1876. * Returns a random float from `<low, high>` interval.
  1877. *
  1878. * @param {number} low - The lower value boundary.
  1879. * @param {number} high - The upper value boundary
  1880. * @return {number} A random float.
  1881. */
  1882. function randFloat( low, high ) {
  1883. return low + Math.random() * ( high - low );
  1884. }
  1885. /**
  1886. * Returns a random integer from `<-range/2, range/2>` interval.
  1887. *
  1888. * @param {number} range - Defines the value range.
  1889. * @return {number} A random float.
  1890. */
  1891. function randFloatSpread( range ) {
  1892. return range * ( 0.5 - Math.random() );
  1893. }
  1894. /**
  1895. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  1896. *
  1897. * @param {number} [s] - The integer seed.
  1898. * @return {number} A random float.
  1899. */
  1900. function seededRandom( s ) {
  1901. if ( s !== undefined ) _seed = s;
  1902. // Mulberry32 generator
  1903. let t = _seed += 0x6D2B79F5;
  1904. t = Math.imul( t ^ t >>> 15, t | 1 );
  1905. t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
  1906. return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
  1907. }
  1908. /**
  1909. * Converts degrees to radians.
  1910. *
  1911. * @param {number} degrees - A value in degrees.
  1912. * @return {number} The converted value in radians.
  1913. */
  1914. function degToRad( degrees ) {
  1915. return degrees * DEG2RAD;
  1916. }
  1917. /**
  1918. * Converts radians to degrees.
  1919. *
  1920. * @param {number} radians - A value in radians.
  1921. * @return {number} The converted value in degrees.
  1922. */
  1923. function radToDeg( radians ) {
  1924. return radians * RAD2DEG;
  1925. }
  1926. /**
  1927. * Returns `true` if the given number is a power of two.
  1928. *
  1929. * @param {number} value - The value to check.
  1930. * @return {boolean} Whether the given number is a power of two or not.
  1931. */
  1932. function isPowerOfTwo( value ) {
  1933. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  1934. }
  1935. /**
  1936. * Returns the smallest power of two that is greater than or equal to the given number.
  1937. *
  1938. * @param {number} value - The value to find a POT for.
  1939. * @return {number} The smallest power of two that is greater than or equal to the given number.
  1940. */
  1941. function ceilPowerOfTwo( value ) {
  1942. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  1943. }
  1944. /**
  1945. * Returns the largest power of two that is less than or equal to the given number.
  1946. *
  1947. * @param {number} value - The value to find a POT for.
  1948. * @return {number} The largest power of two that is less than or equal to the given number.
  1949. */
  1950. function floorPowerOfTwo( value ) {
  1951. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  1952. }
  1953. /**
  1954. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  1955. * defined by the given angles and order.
  1956. *
  1957. * Rotations are applied to the axes in the order specified by order:
  1958. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  1959. *
  1960. * @param {Quaternion} q - The quaternion to set.
  1961. * @param {number} a - The rotation applied to the first axis, in radians.
  1962. * @param {number} b - The rotation applied to the second axis, in radians.
  1963. * @param {number} c - The rotation applied to the third axis, in radians.
  1964. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  1965. */
  1966. function setQuaternionFromProperEuler( q, a, b, c, order ) {
  1967. const cos = Math.cos;
  1968. const sin = Math.sin;
  1969. const c2 = cos( b / 2 );
  1970. const s2 = sin( b / 2 );
  1971. const c13 = cos( ( a + c ) / 2 );
  1972. const s13 = sin( ( a + c ) / 2 );
  1973. const c1_3 = cos( ( a - c ) / 2 );
  1974. const s1_3 = sin( ( a - c ) / 2 );
  1975. const c3_1 = cos( ( c - a ) / 2 );
  1976. const s3_1 = sin( ( c - a ) / 2 );
  1977. switch ( order ) {
  1978. case 'XYX':
  1979. q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
  1980. break;
  1981. case 'YZY':
  1982. q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
  1983. break;
  1984. case 'ZXZ':
  1985. q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
  1986. break;
  1987. case 'XZX':
  1988. q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
  1989. break;
  1990. case 'YXY':
  1991. q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
  1992. break;
  1993. case 'ZYZ':
  1994. q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
  1995. break;
  1996. default:
  1997. warn( 'MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
  1998. }
  1999. }
  2000. /**
  2001. * Denormalizes the given value according to the given typed array.
  2002. *
  2003. * @param {number} value - The value to denormalize.
  2004. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2005. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2006. */
  2007. function denormalize( value, array ) {
  2008. switch ( array.constructor ) {
  2009. case Float32Array:
  2010. return value;
  2011. case Uint32Array:
  2012. return value / 4294967295.0;
  2013. case Uint16Array:
  2014. return value / 65535.0;
  2015. case Uint8Array:
  2016. return value / 255.0;
  2017. case Int32Array:
  2018. return Math.max( value / 2147483647.0, -1 );
  2019. case Int16Array:
  2020. return Math.max( value / 32767.0, -1 );
  2021. case Int8Array:
  2022. return Math.max( value / 127.0, -1 );
  2023. default:
  2024. throw new Error( 'Invalid component type.' );
  2025. }
  2026. }
  2027. /**
  2028. * Normalizes the given value according to the given typed array.
  2029. *
  2030. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2031. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2032. * @return {number} The normalize value.
  2033. */
  2034. function normalize( value, array ) {
  2035. switch ( array.constructor ) {
  2036. case Float32Array:
  2037. return value;
  2038. case Uint32Array:
  2039. return Math.round( value * 4294967295.0 );
  2040. case Uint16Array:
  2041. return Math.round( value * 65535.0 );
  2042. case Uint8Array:
  2043. return Math.round( value * 255.0 );
  2044. case Int32Array:
  2045. return Math.round( value * 2147483647.0 );
  2046. case Int16Array:
  2047. return Math.round( value * 32767.0 );
  2048. case Int8Array:
  2049. return Math.round( value * 127.0 );
  2050. default:
  2051. throw new Error( 'Invalid component type.' );
  2052. }
  2053. }
  2054. /**
  2055. * @class
  2056. * @classdesc A collection of math utility functions.
  2057. * @hideconstructor
  2058. */
  2059. const MathUtils = {
  2060. DEG2RAD: DEG2RAD,
  2061. RAD2DEG: RAD2DEG,
  2062. /**
  2063. * Generate a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier)
  2064. * (universally unique identifier).
  2065. *
  2066. * @static
  2067. * @method
  2068. * @return {string} The UUID.
  2069. */
  2070. generateUUID: generateUUID,
  2071. /**
  2072. * Clamps the given value between min and max.
  2073. *
  2074. * @static
  2075. * @method
  2076. * @param {number} value - The value to clamp.
  2077. * @param {number} min - The min value.
  2078. * @param {number} max - The max value.
  2079. * @return {number} The clamped value.
  2080. */
  2081. clamp: clamp,
  2082. /**
  2083. * Computes the Euclidean modulo of the given parameters that
  2084. * is `( ( n % m ) + m ) % m`.
  2085. *
  2086. * @static
  2087. * @method
  2088. * @param {number} n - The first parameter.
  2089. * @param {number} m - The second parameter.
  2090. * @return {number} The Euclidean modulo.
  2091. */
  2092. euclideanModulo: euclideanModulo,
  2093. /**
  2094. * Performs a linear mapping from range `<a1, a2>` to range `<b1, b2>`
  2095. * for the given value.
  2096. *
  2097. * @static
  2098. * @method
  2099. * @param {number} x - The value to be mapped.
  2100. * @param {number} a1 - Minimum value for range A.
  2101. * @param {number} a2 - Maximum value for range A.
  2102. * @param {number} b1 - Minimum value for range B.
  2103. * @param {number} b2 - Maximum value for range B.
  2104. * @return {number} The mapped value.
  2105. */
  2106. mapLinear: mapLinear,
  2107. /**
  2108. * Returns the percentage in the closed interval `[0, 1]` of the given value
  2109. * between the start and end point.
  2110. *
  2111. * @static
  2112. * @method
  2113. * @param {number} x - The start point
  2114. * @param {number} y - The end point.
  2115. * @param {number} value - A value between start and end.
  2116. * @return {number} The interpolation factor.
  2117. */
  2118. inverseLerp: inverseLerp,
  2119. /**
  2120. * Returns a value linearly interpolated from two known points based on the given interval -
  2121. * `t = 0` will return `x` and `t = 1` will return `y`.
  2122. *
  2123. * @static
  2124. * @method
  2125. * @param {number} x - The start point
  2126. * @param {number} y - The end point.
  2127. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  2128. * @return {number} The interpolated value.
  2129. */
  2130. lerp: lerp,
  2131. /**
  2132. * Smoothly interpolate a number from `x` to `y` in a spring-like manner using a delta
  2133. * time to maintain frame rate independent movement. For details, see
  2134. * [Frame rate independent damping using lerp](http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/).
  2135. *
  2136. * @static
  2137. * @method
  2138. * @param {number} x - The current point.
  2139. * @param {number} y - The target point.
  2140. * @param {number} lambda - A higher lambda value will make the movement more sudden,
  2141. * and a lower value will make the movement more gradual.
  2142. * @param {number} dt - Delta time in seconds.
  2143. * @return {number} The interpolated value.
  2144. */
  2145. damp: damp,
  2146. /**
  2147. * Returns a value that alternates between `0` and the given `length` parameter.
  2148. *
  2149. * @static
  2150. * @method
  2151. * @param {number} x - The value to pingpong.
  2152. * @param {number} [length=1] - The positive value the function will pingpong to.
  2153. * @return {number} The alternated value.
  2154. */
  2155. pingpong: pingpong,
  2156. /**
  2157. * Returns a value in the range `[0,1]` that represents the percentage that `x` has
  2158. * moved between `min` and `max`, but smoothed or slowed down the closer `x` is to
  2159. * the `min` and `max`.
  2160. *
  2161. * See [Smoothstep](http://en.wikipedia.org/wiki/Smoothstep) for more details.
  2162. *
  2163. * @static
  2164. * @method
  2165. * @param {number} x - The value to evaluate based on its position between min and max.
  2166. * @param {number} min - The min value. Any x value below min will be `0`.
  2167. * @param {number} max - The max value. Any x value above max will be `1`.
  2168. * @return {number} The alternated value.
  2169. */
  2170. smoothstep: smoothstep,
  2171. /**
  2172. * A [variation on smoothstep](https://en.wikipedia.org/wiki/Smoothstep#Variations)
  2173. * that has zero 1st and 2nd order derivatives at x=0 and x=1.
  2174. *
  2175. * @static
  2176. * @method
  2177. * @param {number} x - The value to evaluate based on its position between min and max.
  2178. * @param {number} min - The min value. Any x value below min will be `0`.
  2179. * @param {number} max - The max value. Any x value above max will be `1`.
  2180. * @return {number} The alternated value.
  2181. */
  2182. smootherstep: smootherstep,
  2183. /**
  2184. * Returns a random integer from `<low, high>` interval.
  2185. *
  2186. * @static
  2187. * @method
  2188. * @param {number} low - The lower value boundary.
  2189. * @param {number} high - The upper value boundary
  2190. * @return {number} A random integer.
  2191. */
  2192. randInt: randInt,
  2193. /**
  2194. * Returns a random float from `<low, high>` interval.
  2195. *
  2196. * @static
  2197. * @method
  2198. * @param {number} low - The lower value boundary.
  2199. * @param {number} high - The upper value boundary
  2200. * @return {number} A random float.
  2201. */
  2202. randFloat: randFloat,
  2203. /**
  2204. * Returns a random integer from `<-range/2, range/2>` interval.
  2205. *
  2206. * @static
  2207. * @method
  2208. * @param {number} range - Defines the value range.
  2209. * @return {number} A random float.
  2210. */
  2211. randFloatSpread: randFloatSpread,
  2212. /**
  2213. * Returns a deterministic pseudo-random float in the interval `[0, 1]`.
  2214. *
  2215. * @static
  2216. * @method
  2217. * @param {number} [s] - The integer seed.
  2218. * @return {number} A random float.
  2219. */
  2220. seededRandom: seededRandom,
  2221. /**
  2222. * Converts degrees to radians.
  2223. *
  2224. * @static
  2225. * @method
  2226. * @param {number} degrees - A value in degrees.
  2227. * @return {number} The converted value in radians.
  2228. */
  2229. degToRad: degToRad,
  2230. /**
  2231. * Converts radians to degrees.
  2232. *
  2233. * @static
  2234. * @method
  2235. * @param {number} radians - A value in radians.
  2236. * @return {number} The converted value in degrees.
  2237. */
  2238. radToDeg: radToDeg,
  2239. /**
  2240. * Returns `true` if the given number is a power of two.
  2241. *
  2242. * @static
  2243. * @method
  2244. * @param {number} value - The value to check.
  2245. * @return {boolean} Whether the given number is a power of two or not.
  2246. */
  2247. isPowerOfTwo: isPowerOfTwo,
  2248. /**
  2249. * Returns the smallest power of two that is greater than or equal to the given number.
  2250. *
  2251. * @static
  2252. * @method
  2253. * @param {number} value - The value to find a POT for.
  2254. * @return {number} The smallest power of two that is greater than or equal to the given number.
  2255. */
  2256. ceilPowerOfTwo: ceilPowerOfTwo,
  2257. /**
  2258. * Returns the largest power of two that is less than or equal to the given number.
  2259. *
  2260. * @static
  2261. * @method
  2262. * @param {number} value - The value to find a POT for.
  2263. * @return {number} The largest power of two that is less than or equal to the given number.
  2264. */
  2265. floorPowerOfTwo: floorPowerOfTwo,
  2266. /**
  2267. * Sets the given quaternion from the [Intrinsic Proper Euler Angles](https://en.wikipedia.org/wiki/Euler_angles)
  2268. * defined by the given angles and order.
  2269. *
  2270. * Rotations are applied to the axes in the order specified by order:
  2271. * rotation by angle `a` is applied first, then by angle `b`, then by angle `c`.
  2272. *
  2273. * @static
  2274. * @method
  2275. * @param {Quaternion} q - The quaternion to set.
  2276. * @param {number} a - The rotation applied to the first axis, in radians.
  2277. * @param {number} b - The rotation applied to the second axis, in radians.
  2278. * @param {number} c - The rotation applied to the third axis, in radians.
  2279. * @param {('XYX'|'XZX'|'YXY'|'YZY'|'ZXZ'|'ZYZ')} order - A string specifying the axes order.
  2280. */
  2281. setQuaternionFromProperEuler: setQuaternionFromProperEuler,
  2282. /**
  2283. * Normalizes the given value according to the given typed array.
  2284. *
  2285. * @static
  2286. * @method
  2287. * @param {number} value - The float value in the range `[0,1]` to normalize.
  2288. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2289. * @return {number} The normalize value.
  2290. */
  2291. normalize: normalize,
  2292. /**
  2293. * Denormalizes the given value according to the given typed array.
  2294. *
  2295. * @static
  2296. * @method
  2297. * @param {number} value - The value to denormalize.
  2298. * @param {TypedArray} array - The typed array that defines the data type of the value.
  2299. * @return {number} The denormalize (float) value in the range `[0,1]`.
  2300. */
  2301. denormalize: denormalize
  2302. };
  2303. /**
  2304. * Class representing a 2D vector. A 2D vector is an ordered pair of numbers
  2305. * (labeled x and y), which can be used to represent a number of things, such as:
  2306. *
  2307. * - A point in 2D space (i.e. a position on a plane).
  2308. * - A direction and length across a plane. In three.js the length will
  2309. * always be the Euclidean distance(straight-line distance) from `(0, 0)` to `(x, y)`
  2310. * and the direction is also measured from `(0, 0)` towards `(x, y)`.
  2311. * - Any arbitrary ordered pair of numbers.
  2312. *
  2313. * There are other things a 2D vector can be used to represent, such as
  2314. * momentum vectors, complex numbers and so on, however these are the most
  2315. * common uses in three.js.
  2316. *
  2317. * Iterating through a vector instance will yield its components `(x, y)` in
  2318. * the corresponding order.
  2319. * ```js
  2320. * const a = new THREE.Vector2( 0, 1 );
  2321. *
  2322. * //no arguments; will be initialised to (0, 0)
  2323. * const b = new THREE.Vector2( );
  2324. *
  2325. * const d = a.distanceTo( b );
  2326. * ```
  2327. */
  2328. class Vector2 {
  2329. /**
  2330. * Constructs a new 2D vector.
  2331. *
  2332. * @param {number} [x=0] - The x value of this vector.
  2333. * @param {number} [y=0] - The y value of this vector.
  2334. */
  2335. constructor( x = 0, y = 0 ) {
  2336. /**
  2337. * This flag can be used for type testing.
  2338. *
  2339. * @type {boolean}
  2340. * @readonly
  2341. * @default true
  2342. */
  2343. Vector2.prototype.isVector2 = true;
  2344. /**
  2345. * The x value of this vector.
  2346. *
  2347. * @type {number}
  2348. */
  2349. this.x = x;
  2350. /**
  2351. * The y value of this vector.
  2352. *
  2353. * @type {number}
  2354. */
  2355. this.y = y;
  2356. }
  2357. /**
  2358. * Alias for {@link Vector2#x}.
  2359. *
  2360. * @type {number}
  2361. */
  2362. get width() {
  2363. return this.x;
  2364. }
  2365. set width( value ) {
  2366. this.x = value;
  2367. }
  2368. /**
  2369. * Alias for {@link Vector2#y}.
  2370. *
  2371. * @type {number}
  2372. */
  2373. get height() {
  2374. return this.y;
  2375. }
  2376. set height( value ) {
  2377. this.y = value;
  2378. }
  2379. /**
  2380. * Sets the vector components.
  2381. *
  2382. * @param {number} x - The value of the x component.
  2383. * @param {number} y - The value of the y component.
  2384. * @return {Vector2} A reference to this vector.
  2385. */
  2386. set( x, y ) {
  2387. this.x = x;
  2388. this.y = y;
  2389. return this;
  2390. }
  2391. /**
  2392. * Sets the vector components to the same value.
  2393. *
  2394. * @param {number} scalar - The value to set for all vector components.
  2395. * @return {Vector2} A reference to this vector.
  2396. */
  2397. setScalar( scalar ) {
  2398. this.x = scalar;
  2399. this.y = scalar;
  2400. return this;
  2401. }
  2402. /**
  2403. * Sets the vector's x component to the given value
  2404. *
  2405. * @param {number} x - The value to set.
  2406. * @return {Vector2} A reference to this vector.
  2407. */
  2408. setX( x ) {
  2409. this.x = x;
  2410. return this;
  2411. }
  2412. /**
  2413. * Sets the vector's y component to the given value
  2414. *
  2415. * @param {number} y - The value to set.
  2416. * @return {Vector2} A reference to this vector.
  2417. */
  2418. setY( y ) {
  2419. this.y = y;
  2420. return this;
  2421. }
  2422. /**
  2423. * Allows to set a vector component with an index.
  2424. *
  2425. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2426. * @param {number} value - The value to set.
  2427. * @return {Vector2} A reference to this vector.
  2428. */
  2429. setComponent( index, value ) {
  2430. switch ( index ) {
  2431. case 0: this.x = value; break;
  2432. case 1: this.y = value; break;
  2433. default: throw new Error( 'index is out of range: ' + index );
  2434. }
  2435. return this;
  2436. }
  2437. /**
  2438. * Returns the value of the vector component which matches the given index.
  2439. *
  2440. * @param {number} index - The component index. `0` equals to x, `1` equals to y.
  2441. * @return {number} A vector component value.
  2442. */
  2443. getComponent( index ) {
  2444. switch ( index ) {
  2445. case 0: return this.x;
  2446. case 1: return this.y;
  2447. default: throw new Error( 'index is out of range: ' + index );
  2448. }
  2449. }
  2450. /**
  2451. * Returns a new vector with copied values from this instance.
  2452. *
  2453. * @return {Vector2} A clone of this instance.
  2454. */
  2455. clone() {
  2456. return new this.constructor( this.x, this.y );
  2457. }
  2458. /**
  2459. * Copies the values of the given vector to this instance.
  2460. *
  2461. * @param {Vector2} v - The vector to copy.
  2462. * @return {Vector2} A reference to this vector.
  2463. */
  2464. copy( v ) {
  2465. this.x = v.x;
  2466. this.y = v.y;
  2467. return this;
  2468. }
  2469. /**
  2470. * Adds the given vector to this instance.
  2471. *
  2472. * @param {Vector2} v - The vector to add.
  2473. * @return {Vector2} A reference to this vector.
  2474. */
  2475. add( v ) {
  2476. this.x += v.x;
  2477. this.y += v.y;
  2478. return this;
  2479. }
  2480. /**
  2481. * Adds the given scalar value to all components of this instance.
  2482. *
  2483. * @param {number} s - The scalar to add.
  2484. * @return {Vector2} A reference to this vector.
  2485. */
  2486. addScalar( s ) {
  2487. this.x += s;
  2488. this.y += s;
  2489. return this;
  2490. }
  2491. /**
  2492. * Adds the given vectors and stores the result in this instance.
  2493. *
  2494. * @param {Vector2} a - The first vector.
  2495. * @param {Vector2} b - The second vector.
  2496. * @return {Vector2} A reference to this vector.
  2497. */
  2498. addVectors( a, b ) {
  2499. this.x = a.x + b.x;
  2500. this.y = a.y + b.y;
  2501. return this;
  2502. }
  2503. /**
  2504. * Adds the given vector scaled by the given factor to this instance.
  2505. *
  2506. * @param {Vector2} v - The vector.
  2507. * @param {number} s - The factor that scales `v`.
  2508. * @return {Vector2} A reference to this vector.
  2509. */
  2510. addScaledVector( v, s ) {
  2511. this.x += v.x * s;
  2512. this.y += v.y * s;
  2513. return this;
  2514. }
  2515. /**
  2516. * Subtracts the given vector from this instance.
  2517. *
  2518. * @param {Vector2} v - The vector to subtract.
  2519. * @return {Vector2} A reference to this vector.
  2520. */
  2521. sub( v ) {
  2522. this.x -= v.x;
  2523. this.y -= v.y;
  2524. return this;
  2525. }
  2526. /**
  2527. * Subtracts the given scalar value from all components of this instance.
  2528. *
  2529. * @param {number} s - The scalar to subtract.
  2530. * @return {Vector2} A reference to this vector.
  2531. */
  2532. subScalar( s ) {
  2533. this.x -= s;
  2534. this.y -= s;
  2535. return this;
  2536. }
  2537. /**
  2538. * Subtracts the given vectors and stores the result in this instance.
  2539. *
  2540. * @param {Vector2} a - The first vector.
  2541. * @param {Vector2} b - The second vector.
  2542. * @return {Vector2} A reference to this vector.
  2543. */
  2544. subVectors( a, b ) {
  2545. this.x = a.x - b.x;
  2546. this.y = a.y - b.y;
  2547. return this;
  2548. }
  2549. /**
  2550. * Multiplies the given vector with this instance.
  2551. *
  2552. * @param {Vector2} v - The vector to multiply.
  2553. * @return {Vector2} A reference to this vector.
  2554. */
  2555. multiply( v ) {
  2556. this.x *= v.x;
  2557. this.y *= v.y;
  2558. return this;
  2559. }
  2560. /**
  2561. * Multiplies the given scalar value with all components of this instance.
  2562. *
  2563. * @param {number} scalar - The scalar to multiply.
  2564. * @return {Vector2} A reference to this vector.
  2565. */
  2566. multiplyScalar( scalar ) {
  2567. this.x *= scalar;
  2568. this.y *= scalar;
  2569. return this;
  2570. }
  2571. /**
  2572. * Divides this instance by the given vector.
  2573. *
  2574. * @param {Vector2} v - The vector to divide.
  2575. * @return {Vector2} A reference to this vector.
  2576. */
  2577. divide( v ) {
  2578. this.x /= v.x;
  2579. this.y /= v.y;
  2580. return this;
  2581. }
  2582. /**
  2583. * Divides this vector by the given scalar.
  2584. *
  2585. * @param {number} scalar - The scalar to divide.
  2586. * @return {Vector2} A reference to this vector.
  2587. */
  2588. divideScalar( scalar ) {
  2589. return this.multiplyScalar( 1 / scalar );
  2590. }
  2591. /**
  2592. * Multiplies this vector (with an implicit 1 as the 3rd component) by
  2593. * the given 3x3 matrix.
  2594. *
  2595. * @param {Matrix3} m - The matrix to apply.
  2596. * @return {Vector2} A reference to this vector.
  2597. */
  2598. applyMatrix3( m ) {
  2599. const x = this.x, y = this.y;
  2600. const e = m.elements;
  2601. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  2602. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  2603. return this;
  2604. }
  2605. /**
  2606. * If this vector's x or y value is greater than the given vector's x or y
  2607. * value, replace that value with the corresponding min value.
  2608. *
  2609. * @param {Vector2} v - The vector.
  2610. * @return {Vector2} A reference to this vector.
  2611. */
  2612. min( v ) {
  2613. this.x = Math.min( this.x, v.x );
  2614. this.y = Math.min( this.y, v.y );
  2615. return this;
  2616. }
  2617. /**
  2618. * If this vector's x or y value is less than the given vector's x or y
  2619. * value, replace that value with the corresponding max value.
  2620. *
  2621. * @param {Vector2} v - The vector.
  2622. * @return {Vector2} A reference to this vector.
  2623. */
  2624. max( v ) {
  2625. this.x = Math.max( this.x, v.x );
  2626. this.y = Math.max( this.y, v.y );
  2627. return this;
  2628. }
  2629. /**
  2630. * If this vector's x or y value is greater than the max vector's x or y
  2631. * value, it is replaced by the corresponding value.
  2632. * If this vector's x or y value is less than the min vector's x or y value,
  2633. * it is replaced by the corresponding value.
  2634. *
  2635. * @param {Vector2} min - The minimum x and y values.
  2636. * @param {Vector2} max - The maximum x and y values in the desired range.
  2637. * @return {Vector2} A reference to this vector.
  2638. */
  2639. clamp( min, max ) {
  2640. // assumes min < max, componentwise
  2641. this.x = clamp( this.x, min.x, max.x );
  2642. this.y = clamp( this.y, min.y, max.y );
  2643. return this;
  2644. }
  2645. /**
  2646. * If this vector's x or y values are greater than the max value, they are
  2647. * replaced by the max value.
  2648. * If this vector's x or y values are less than the min value, they are
  2649. * replaced by the min value.
  2650. *
  2651. * @param {number} minVal - The minimum value the components will be clamped to.
  2652. * @param {number} maxVal - The maximum value the components will be clamped to.
  2653. * @return {Vector2} A reference to this vector.
  2654. */
  2655. clampScalar( minVal, maxVal ) {
  2656. this.x = clamp( this.x, minVal, maxVal );
  2657. this.y = clamp( this.y, minVal, maxVal );
  2658. return this;
  2659. }
  2660. /**
  2661. * If this vector's length is greater than the max value, it is replaced by
  2662. * the max value.
  2663. * If this vector's length is less than the min value, it is replaced by the
  2664. * min value.
  2665. *
  2666. * @param {number} min - The minimum value the vector length will be clamped to.
  2667. * @param {number} max - The maximum value the vector length will be clamped to.
  2668. * @return {Vector2} A reference to this vector.
  2669. */
  2670. clampLength( min, max ) {
  2671. const length = this.length();
  2672. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  2673. }
  2674. /**
  2675. * The components of this vector are rounded down to the nearest integer value.
  2676. *
  2677. * @return {Vector2} A reference to this vector.
  2678. */
  2679. floor() {
  2680. this.x = Math.floor( this.x );
  2681. this.y = Math.floor( this.y );
  2682. return this;
  2683. }
  2684. /**
  2685. * The components of this vector are rounded up to the nearest integer value.
  2686. *
  2687. * @return {Vector2} A reference to this vector.
  2688. */
  2689. ceil() {
  2690. this.x = Math.ceil( this.x );
  2691. this.y = Math.ceil( this.y );
  2692. return this;
  2693. }
  2694. /**
  2695. * The components of this vector are rounded to the nearest integer value
  2696. *
  2697. * @return {Vector2} A reference to this vector.
  2698. */
  2699. round() {
  2700. this.x = Math.round( this.x );
  2701. this.y = Math.round( this.y );
  2702. return this;
  2703. }
  2704. /**
  2705. * The components of this vector are rounded towards zero (up if negative,
  2706. * down if positive) to an integer value.
  2707. *
  2708. * @return {Vector2} A reference to this vector.
  2709. */
  2710. roundToZero() {
  2711. this.x = Math.trunc( this.x );
  2712. this.y = Math.trunc( this.y );
  2713. return this;
  2714. }
  2715. /**
  2716. * Inverts this vector - i.e. sets x = -x and y = -y.
  2717. *
  2718. * @return {Vector2} A reference to this vector.
  2719. */
  2720. negate() {
  2721. this.x = - this.x;
  2722. this.y = - this.y;
  2723. return this;
  2724. }
  2725. /**
  2726. * Calculates the dot product of the given vector with this instance.
  2727. *
  2728. * @param {Vector2} v - The vector to compute the dot product with.
  2729. * @return {number} The result of the dot product.
  2730. */
  2731. dot( v ) {
  2732. return this.x * v.x + this.y * v.y;
  2733. }
  2734. /**
  2735. * Calculates the cross product of the given vector with this instance.
  2736. *
  2737. * @param {Vector2} v - The vector to compute the cross product with.
  2738. * @return {number} The result of the cross product.
  2739. */
  2740. cross( v ) {
  2741. return this.x * v.y - this.y * v.x;
  2742. }
  2743. /**
  2744. * Computes the square of the Euclidean length (straight-line length) from
  2745. * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should
  2746. * compare the length squared instead as it is slightly more efficient to calculate.
  2747. *
  2748. * @return {number} The square length of this vector.
  2749. */
  2750. lengthSq() {
  2751. return this.x * this.x + this.y * this.y;
  2752. }
  2753. /**
  2754. * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y).
  2755. *
  2756. * @return {number} The length of this vector.
  2757. */
  2758. length() {
  2759. return Math.sqrt( this.x * this.x + this.y * this.y );
  2760. }
  2761. /**
  2762. * Computes the Manhattan length of this vector.
  2763. *
  2764. * @return {number} The length of this vector.
  2765. */
  2766. manhattanLength() {
  2767. return Math.abs( this.x ) + Math.abs( this.y );
  2768. }
  2769. /**
  2770. * Converts this vector to a unit vector - that is, sets it equal to a vector
  2771. * with the same direction as this one, but with a vector length of `1`.
  2772. *
  2773. * @return {Vector2} A reference to this vector.
  2774. */
  2775. normalize() {
  2776. return this.divideScalar( this.length() || 1 );
  2777. }
  2778. /**
  2779. * Computes the angle in radians of this vector with respect to the positive x-axis.
  2780. *
  2781. * @return {number} The angle in radians.
  2782. */
  2783. angle() {
  2784. const angle = Math.atan2( - this.y, - this.x ) + Math.PI;
  2785. return angle;
  2786. }
  2787. /**
  2788. * Returns the angle between the given vector and this instance in radians.
  2789. *
  2790. * @param {Vector2} v - The vector to compute the angle with.
  2791. * @return {number} The angle in radians.
  2792. */
  2793. angleTo( v ) {
  2794. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  2795. if ( denominator === 0 ) return Math.PI / 2;
  2796. const theta = this.dot( v ) / denominator;
  2797. // clamp, to handle numerical problems
  2798. return Math.acos( clamp( theta, -1, 1 ) );
  2799. }
  2800. /**
  2801. * Computes the distance from the given vector to this instance.
  2802. *
  2803. * @param {Vector2} v - The vector to compute the distance to.
  2804. * @return {number} The distance.
  2805. */
  2806. distanceTo( v ) {
  2807. return Math.sqrt( this.distanceToSquared( v ) );
  2808. }
  2809. /**
  2810. * Computes the squared distance from the given vector to this instance.
  2811. * If you are just comparing the distance with another distance, you should compare
  2812. * the distance squared instead as it is slightly more efficient to calculate.
  2813. *
  2814. * @param {Vector2} v - The vector to compute the squared distance to.
  2815. * @return {number} The squared distance.
  2816. */
  2817. distanceToSquared( v ) {
  2818. const dx = this.x - v.x, dy = this.y - v.y;
  2819. return dx * dx + dy * dy;
  2820. }
  2821. /**
  2822. * Computes the Manhattan distance from the given vector to this instance.
  2823. *
  2824. * @param {Vector2} v - The vector to compute the Manhattan distance to.
  2825. * @return {number} The Manhattan distance.
  2826. */
  2827. manhattanDistanceTo( v ) {
  2828. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  2829. }
  2830. /**
  2831. * Sets this vector to a vector with the same direction as this one, but
  2832. * with the specified length.
  2833. *
  2834. * @param {number} length - The new length of this vector.
  2835. * @return {Vector2} A reference to this vector.
  2836. */
  2837. setLength( length ) {
  2838. return this.normalize().multiplyScalar( length );
  2839. }
  2840. /**
  2841. * Linearly interpolates between the given vector and this instance, where
  2842. * alpha is the percent distance along the line - alpha = 0 will be this
  2843. * vector, and alpha = 1 will be the given one.
  2844. *
  2845. * @param {Vector2} v - The vector to interpolate towards.
  2846. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2847. * @return {Vector2} A reference to this vector.
  2848. */
  2849. lerp( v, alpha ) {
  2850. this.x += ( v.x - this.x ) * alpha;
  2851. this.y += ( v.y - this.y ) * alpha;
  2852. return this;
  2853. }
  2854. /**
  2855. * Linearly interpolates between the given vectors, where alpha is the percent
  2856. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  2857. * be the second one. The result is stored in this instance.
  2858. *
  2859. * @param {Vector2} v1 - The first vector.
  2860. * @param {Vector2} v2 - The second vector.
  2861. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  2862. * @return {Vector2} A reference to this vector.
  2863. */
  2864. lerpVectors( v1, v2, alpha ) {
  2865. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  2866. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  2867. return this;
  2868. }
  2869. /**
  2870. * Returns `true` if this vector is equal with the given one.
  2871. *
  2872. * @param {Vector2} v - The vector to test for equality.
  2873. * @return {boolean} Whether this vector is equal with the given one.
  2874. */
  2875. equals( v ) {
  2876. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  2877. }
  2878. /**
  2879. * Sets this vector's x value to be `array[ offset ]` and y
  2880. * value to be `array[ offset + 1 ]`.
  2881. *
  2882. * @param {Array<number>} array - An array holding the vector component values.
  2883. * @param {number} [offset=0] - The offset into the array.
  2884. * @return {Vector2} A reference to this vector.
  2885. */
  2886. fromArray( array, offset = 0 ) {
  2887. this.x = array[ offset ];
  2888. this.y = array[ offset + 1 ];
  2889. return this;
  2890. }
  2891. /**
  2892. * Writes the components of this vector to the given array. If no array is provided,
  2893. * the method returns a new instance.
  2894. *
  2895. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  2896. * @param {number} [offset=0] - Index of the first element in the array.
  2897. * @return {Array<number>} The vector components.
  2898. */
  2899. toArray( array = [], offset = 0 ) {
  2900. array[ offset ] = this.x;
  2901. array[ offset + 1 ] = this.y;
  2902. return array;
  2903. }
  2904. /**
  2905. * Sets the components of this vector from the given buffer attribute.
  2906. *
  2907. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  2908. * @param {number} index - The index into the attribute.
  2909. * @return {Vector2} A reference to this vector.
  2910. */
  2911. fromBufferAttribute( attribute, index ) {
  2912. this.x = attribute.getX( index );
  2913. this.y = attribute.getY( index );
  2914. return this;
  2915. }
  2916. /**
  2917. * Rotates this vector around the given center by the given angle.
  2918. *
  2919. * @param {Vector2} center - The point around which to rotate.
  2920. * @param {number} angle - The angle to rotate, in radians.
  2921. * @return {Vector2} A reference to this vector.
  2922. */
  2923. rotateAround( center, angle ) {
  2924. const c = Math.cos( angle ), s = Math.sin( angle );
  2925. const x = this.x - center.x;
  2926. const y = this.y - center.y;
  2927. this.x = x * c - y * s + center.x;
  2928. this.y = x * s + y * c + center.y;
  2929. return this;
  2930. }
  2931. /**
  2932. * Sets each component of this vector to a pseudo-random value between `0` and
  2933. * `1`, excluding `1`.
  2934. *
  2935. * @return {Vector2} A reference to this vector.
  2936. */
  2937. random() {
  2938. this.x = Math.random();
  2939. this.y = Math.random();
  2940. return this;
  2941. }
  2942. *[ Symbol.iterator ]() {
  2943. yield this.x;
  2944. yield this.y;
  2945. }
  2946. }
  2947. /**
  2948. * Class for representing a Quaternion. Quaternions are used in three.js to represent rotations.
  2949. *
  2950. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  2951. * the corresponding order.
  2952. *
  2953. * Note that three.js expects Quaternions to be normalized.
  2954. * ```js
  2955. * const quaternion = new THREE.Quaternion();
  2956. * quaternion.setFromAxisAngle( new THREE.Vector3( 0, 1, 0 ), Math.PI / 2 );
  2957. *
  2958. * const vector = new THREE.Vector3( 1, 0, 0 );
  2959. * vector.applyQuaternion( quaternion );
  2960. * ```
  2961. */
  2962. class Quaternion {
  2963. /**
  2964. * Constructs a new quaternion.
  2965. *
  2966. * @param {number} [x=0] - The x value of this quaternion.
  2967. * @param {number} [y=0] - The y value of this quaternion.
  2968. * @param {number} [z=0] - The z value of this quaternion.
  2969. * @param {number} [w=1] - The w value of this quaternion.
  2970. */
  2971. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  2972. /**
  2973. * This flag can be used for type testing.
  2974. *
  2975. * @type {boolean}
  2976. * @readonly
  2977. * @default true
  2978. */
  2979. this.isQuaternion = true;
  2980. this._x = x;
  2981. this._y = y;
  2982. this._z = z;
  2983. this._w = w;
  2984. }
  2985. /**
  2986. * Interpolates between two quaternions via SLERP. This implementation assumes the
  2987. * quaternion data are managed in flat arrays.
  2988. *
  2989. * @param {Array<number>} dst - The destination array.
  2990. * @param {number} dstOffset - An offset into the destination array.
  2991. * @param {Array<number>} src0 - The source array of the first quaternion.
  2992. * @param {number} srcOffset0 - An offset into the first source array.
  2993. * @param {Array<number>} src1 - The source array of the second quaternion.
  2994. * @param {number} srcOffset1 - An offset into the second source array.
  2995. * @param {number} t - The interpolation factor in the range `[0,1]`.
  2996. * @see {@link Quaternion#slerp}
  2997. */
  2998. static slerpFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  2999. let x0 = src0[ srcOffset0 + 0 ],
  3000. y0 = src0[ srcOffset0 + 1 ],
  3001. z0 = src0[ srcOffset0 + 2 ],
  3002. w0 = src0[ srcOffset0 + 3 ];
  3003. let x1 = src1[ srcOffset1 + 0 ],
  3004. y1 = src1[ srcOffset1 + 1 ],
  3005. z1 = src1[ srcOffset1 + 2 ],
  3006. w1 = src1[ srcOffset1 + 3 ];
  3007. if ( t <= 0 ) {
  3008. dst[ dstOffset + 0 ] = x0;
  3009. dst[ dstOffset + 1 ] = y0;
  3010. dst[ dstOffset + 2 ] = z0;
  3011. dst[ dstOffset + 3 ] = w0;
  3012. return;
  3013. }
  3014. if ( t >= 1 ) {
  3015. dst[ dstOffset + 0 ] = x1;
  3016. dst[ dstOffset + 1 ] = y1;
  3017. dst[ dstOffset + 2 ] = z1;
  3018. dst[ dstOffset + 3 ] = w1;
  3019. return;
  3020. }
  3021. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  3022. let dot = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1;
  3023. if ( dot < 0 ) {
  3024. x1 = - x1;
  3025. y1 = - y1;
  3026. z1 = - z1;
  3027. w1 = - w1;
  3028. dot = - dot;
  3029. }
  3030. let s = 1 - t;
  3031. if ( dot < 0.9995 ) {
  3032. // slerp
  3033. const theta = Math.acos( dot );
  3034. const sin = Math.sin( theta );
  3035. s = Math.sin( s * theta ) / sin;
  3036. t = Math.sin( t * theta ) / sin;
  3037. x0 = x0 * s + x1 * t;
  3038. y0 = y0 * s + y1 * t;
  3039. z0 = z0 * s + z1 * t;
  3040. w0 = w0 * s + w1 * t;
  3041. } else {
  3042. // for small angles, lerp then normalize
  3043. x0 = x0 * s + x1 * t;
  3044. y0 = y0 * s + y1 * t;
  3045. z0 = z0 * s + z1 * t;
  3046. w0 = w0 * s + w1 * t;
  3047. const f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  3048. x0 *= f;
  3049. y0 *= f;
  3050. z0 *= f;
  3051. w0 *= f;
  3052. }
  3053. }
  3054. dst[ dstOffset ] = x0;
  3055. dst[ dstOffset + 1 ] = y0;
  3056. dst[ dstOffset + 2 ] = z0;
  3057. dst[ dstOffset + 3 ] = w0;
  3058. }
  3059. /**
  3060. * Multiplies two quaternions. This implementation assumes the quaternion data are managed
  3061. * in flat arrays.
  3062. *
  3063. * @param {Array<number>} dst - The destination array.
  3064. * @param {number} dstOffset - An offset into the destination array.
  3065. * @param {Array<number>} src0 - The source array of the first quaternion.
  3066. * @param {number} srcOffset0 - An offset into the first source array.
  3067. * @param {Array<number>} src1 - The source array of the second quaternion.
  3068. * @param {number} srcOffset1 - An offset into the second source array.
  3069. * @return {Array<number>} The destination array.
  3070. * @see {@link Quaternion#multiplyQuaternions}.
  3071. */
  3072. static multiplyQuaternionsFlat( dst, dstOffset, src0, srcOffset0, src1, srcOffset1 ) {
  3073. const x0 = src0[ srcOffset0 ];
  3074. const y0 = src0[ srcOffset0 + 1 ];
  3075. const z0 = src0[ srcOffset0 + 2 ];
  3076. const w0 = src0[ srcOffset0 + 3 ];
  3077. const x1 = src1[ srcOffset1 ];
  3078. const y1 = src1[ srcOffset1 + 1 ];
  3079. const z1 = src1[ srcOffset1 + 2 ];
  3080. const w1 = src1[ srcOffset1 + 3 ];
  3081. dst[ dstOffset ] = x0 * w1 + w0 * x1 + y0 * z1 - z0 * y1;
  3082. dst[ dstOffset + 1 ] = y0 * w1 + w0 * y1 + z0 * x1 - x0 * z1;
  3083. dst[ dstOffset + 2 ] = z0 * w1 + w0 * z1 + x0 * y1 - y0 * x1;
  3084. dst[ dstOffset + 3 ] = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1;
  3085. return dst;
  3086. }
  3087. /**
  3088. * The x value of this quaternion.
  3089. *
  3090. * @type {number}
  3091. * @default 0
  3092. */
  3093. get x() {
  3094. return this._x;
  3095. }
  3096. set x( value ) {
  3097. this._x = value;
  3098. this._onChangeCallback();
  3099. }
  3100. /**
  3101. * The y value of this quaternion.
  3102. *
  3103. * @type {number}
  3104. * @default 0
  3105. */
  3106. get y() {
  3107. return this._y;
  3108. }
  3109. set y( value ) {
  3110. this._y = value;
  3111. this._onChangeCallback();
  3112. }
  3113. /**
  3114. * The z value of this quaternion.
  3115. *
  3116. * @type {number}
  3117. * @default 0
  3118. */
  3119. get z() {
  3120. return this._z;
  3121. }
  3122. set z( value ) {
  3123. this._z = value;
  3124. this._onChangeCallback();
  3125. }
  3126. /**
  3127. * The w value of this quaternion.
  3128. *
  3129. * @type {number}
  3130. * @default 1
  3131. */
  3132. get w() {
  3133. return this._w;
  3134. }
  3135. set w( value ) {
  3136. this._w = value;
  3137. this._onChangeCallback();
  3138. }
  3139. /**
  3140. * Sets the quaternion components.
  3141. *
  3142. * @param {number} x - The x value of this quaternion.
  3143. * @param {number} y - The y value of this quaternion.
  3144. * @param {number} z - The z value of this quaternion.
  3145. * @param {number} w - The w value of this quaternion.
  3146. * @return {Quaternion} A reference to this quaternion.
  3147. */
  3148. set( x, y, z, w ) {
  3149. this._x = x;
  3150. this._y = y;
  3151. this._z = z;
  3152. this._w = w;
  3153. this._onChangeCallback();
  3154. return this;
  3155. }
  3156. /**
  3157. * Returns a new quaternion with copied values from this instance.
  3158. *
  3159. * @return {Quaternion} A clone of this instance.
  3160. */
  3161. clone() {
  3162. return new this.constructor( this._x, this._y, this._z, this._w );
  3163. }
  3164. /**
  3165. * Copies the values of the given quaternion to this instance.
  3166. *
  3167. * @param {Quaternion} quaternion - The quaternion to copy.
  3168. * @return {Quaternion} A reference to this quaternion.
  3169. */
  3170. copy( quaternion ) {
  3171. this._x = quaternion.x;
  3172. this._y = quaternion.y;
  3173. this._z = quaternion.z;
  3174. this._w = quaternion.w;
  3175. this._onChangeCallback();
  3176. return this;
  3177. }
  3178. /**
  3179. * Sets this quaternion from the rotation specified by the given
  3180. * Euler angles.
  3181. *
  3182. * @param {Euler} euler - The Euler angles.
  3183. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  3184. * @return {Quaternion} A reference to this quaternion.
  3185. */
  3186. setFromEuler( euler, update = true ) {
  3187. const x = euler._x, y = euler._y, z = euler._z, order = euler._order;
  3188. // http://www.mathworks.com/matlabcentral/fileexchange/
  3189. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3190. // content/SpinCalc.m
  3191. const cos = Math.cos;
  3192. const sin = Math.sin;
  3193. const c1 = cos( x / 2 );
  3194. const c2 = cos( y / 2 );
  3195. const c3 = cos( z / 2 );
  3196. const s1 = sin( x / 2 );
  3197. const s2 = sin( y / 2 );
  3198. const s3 = sin( z / 2 );
  3199. switch ( order ) {
  3200. case 'XYZ':
  3201. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3202. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3203. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3204. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3205. break;
  3206. case 'YXZ':
  3207. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3208. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3209. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3210. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3211. break;
  3212. case 'ZXY':
  3213. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3214. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3215. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3216. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3217. break;
  3218. case 'ZYX':
  3219. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3220. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3221. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3222. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3223. break;
  3224. case 'YZX':
  3225. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  3226. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  3227. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  3228. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  3229. break;
  3230. case 'XZY':
  3231. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  3232. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  3233. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  3234. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  3235. break;
  3236. default:
  3237. warn( 'Quaternion: .setFromEuler() encountered an unknown order: ' + order );
  3238. }
  3239. if ( update === true ) this._onChangeCallback();
  3240. return this;
  3241. }
  3242. /**
  3243. * Sets this quaternion from the given axis and angle.
  3244. *
  3245. * @param {Vector3} axis - The normalized axis.
  3246. * @param {number} angle - The angle in radians.
  3247. * @return {Quaternion} A reference to this quaternion.
  3248. */
  3249. setFromAxisAngle( axis, angle ) {
  3250. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3251. const halfAngle = angle / 2, s = Math.sin( halfAngle );
  3252. this._x = axis.x * s;
  3253. this._y = axis.y * s;
  3254. this._z = axis.z * s;
  3255. this._w = Math.cos( halfAngle );
  3256. this._onChangeCallback();
  3257. return this;
  3258. }
  3259. /**
  3260. * Sets this quaternion from the given rotation matrix.
  3261. *
  3262. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  3263. * @return {Quaternion} A reference to this quaternion.
  3264. */
  3265. setFromRotationMatrix( m ) {
  3266. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3267. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3268. const te = m.elements,
  3269. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  3270. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  3271. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  3272. trace = m11 + m22 + m33;
  3273. if ( trace > 0 ) {
  3274. const s = 0.5 / Math.sqrt( trace + 1.0 );
  3275. this._w = 0.25 / s;
  3276. this._x = ( m32 - m23 ) * s;
  3277. this._y = ( m13 - m31 ) * s;
  3278. this._z = ( m21 - m12 ) * s;
  3279. } else if ( m11 > m22 && m11 > m33 ) {
  3280. const s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3281. this._w = ( m32 - m23 ) / s;
  3282. this._x = 0.25 * s;
  3283. this._y = ( m12 + m21 ) / s;
  3284. this._z = ( m13 + m31 ) / s;
  3285. } else if ( m22 > m33 ) {
  3286. const s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3287. this._w = ( m13 - m31 ) / s;
  3288. this._x = ( m12 + m21 ) / s;
  3289. this._y = 0.25 * s;
  3290. this._z = ( m23 + m32 ) / s;
  3291. } else {
  3292. const s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3293. this._w = ( m21 - m12 ) / s;
  3294. this._x = ( m13 + m31 ) / s;
  3295. this._y = ( m23 + m32 ) / s;
  3296. this._z = 0.25 * s;
  3297. }
  3298. this._onChangeCallback();
  3299. return this;
  3300. }
  3301. /**
  3302. * Sets this quaternion to the rotation required to rotate the direction vector
  3303. * `vFrom` to the direction vector `vTo`.
  3304. *
  3305. * @param {Vector3} vFrom - The first (normalized) direction vector.
  3306. * @param {Vector3} vTo - The second (normalized) direction vector.
  3307. * @return {Quaternion} A reference to this quaternion.
  3308. */
  3309. setFromUnitVectors( vFrom, vTo ) {
  3310. // assumes direction vectors vFrom and vTo are normalized
  3311. let r = vFrom.dot( vTo ) + 1;
  3312. if ( r < 1e-8 ) { // the epsilon value has been discussed in #31286
  3313. // vFrom and vTo point in opposite directions
  3314. r = 0;
  3315. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  3316. this._x = - vFrom.y;
  3317. this._y = vFrom.x;
  3318. this._z = 0;
  3319. this._w = r;
  3320. } else {
  3321. this._x = 0;
  3322. this._y = - vFrom.z;
  3323. this._z = vFrom.y;
  3324. this._w = r;
  3325. }
  3326. } else {
  3327. // crossVectors( vFrom, vTo ); // inlined to avoid cyclic dependency on Vector3
  3328. this._x = vFrom.y * vTo.z - vFrom.z * vTo.y;
  3329. this._y = vFrom.z * vTo.x - vFrom.x * vTo.z;
  3330. this._z = vFrom.x * vTo.y - vFrom.y * vTo.x;
  3331. this._w = r;
  3332. }
  3333. return this.normalize();
  3334. }
  3335. /**
  3336. * Returns the angle between this quaternion and the given one in radians.
  3337. *
  3338. * @param {Quaternion} q - The quaternion to compute the angle with.
  3339. * @return {number} The angle in radians.
  3340. */
  3341. angleTo( q ) {
  3342. return 2 * Math.acos( Math.abs( clamp( this.dot( q ), -1, 1 ) ) );
  3343. }
  3344. /**
  3345. * Rotates this quaternion by a given angular step to the given quaternion.
  3346. * The method ensures that the final quaternion will not overshoot `q`.
  3347. *
  3348. * @param {Quaternion} q - The target quaternion.
  3349. * @param {number} step - The angular step in radians.
  3350. * @return {Quaternion} A reference to this quaternion.
  3351. */
  3352. rotateTowards( q, step ) {
  3353. const angle = this.angleTo( q );
  3354. if ( angle === 0 ) return this;
  3355. const t = Math.min( 1, step / angle );
  3356. this.slerp( q, t );
  3357. return this;
  3358. }
  3359. /**
  3360. * Sets this quaternion to the identity quaternion; that is, to the
  3361. * quaternion that represents "no rotation".
  3362. *
  3363. * @return {Quaternion} A reference to this quaternion.
  3364. */
  3365. identity() {
  3366. return this.set( 0, 0, 0, 1 );
  3367. }
  3368. /**
  3369. * Inverts this quaternion via {@link Quaternion#conjugate}. The
  3370. * quaternion is assumed to have unit length.
  3371. *
  3372. * @return {Quaternion} A reference to this quaternion.
  3373. */
  3374. invert() {
  3375. return this.conjugate();
  3376. }
  3377. /**
  3378. * Returns the rotational conjugate of this quaternion. The conjugate of a
  3379. * quaternion represents the same rotation in the opposite direction about
  3380. * the rotational axis.
  3381. *
  3382. * @return {Quaternion} A reference to this quaternion.
  3383. */
  3384. conjugate() {
  3385. this._x *= -1;
  3386. this._y *= -1;
  3387. this._z *= -1;
  3388. this._onChangeCallback();
  3389. return this;
  3390. }
  3391. /**
  3392. * Calculates the dot product of this quaternion and the given one.
  3393. *
  3394. * @param {Quaternion} v - The quaternion to compute the dot product with.
  3395. * @return {number} The result of the dot product.
  3396. */
  3397. dot( v ) {
  3398. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  3399. }
  3400. /**
  3401. * Computes the squared Euclidean length (straight-line length) of this quaternion,
  3402. * considered as a 4 dimensional vector. This can be useful if you are comparing the
  3403. * lengths of two quaternions, as this is a slightly more efficient calculation than
  3404. * {@link Quaternion#length}.
  3405. *
  3406. * @return {number} The squared Euclidean length.
  3407. */
  3408. lengthSq() {
  3409. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  3410. }
  3411. /**
  3412. * Computes the Euclidean length (straight-line length) of this quaternion,
  3413. * considered as a 4 dimensional vector.
  3414. *
  3415. * @return {number} The Euclidean length.
  3416. */
  3417. length() {
  3418. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  3419. }
  3420. /**
  3421. * Normalizes this quaternion - that is, calculated the quaternion that performs
  3422. * the same rotation as this one, but has a length equal to `1`.
  3423. *
  3424. * @return {Quaternion} A reference to this quaternion.
  3425. */
  3426. normalize() {
  3427. let l = this.length();
  3428. if ( l === 0 ) {
  3429. this._x = 0;
  3430. this._y = 0;
  3431. this._z = 0;
  3432. this._w = 1;
  3433. } else {
  3434. l = 1 / l;
  3435. this._x = this._x * l;
  3436. this._y = this._y * l;
  3437. this._z = this._z * l;
  3438. this._w = this._w * l;
  3439. }
  3440. this._onChangeCallback();
  3441. return this;
  3442. }
  3443. /**
  3444. * Multiplies this quaternion by the given one.
  3445. *
  3446. * @param {Quaternion} q - The quaternion.
  3447. * @return {Quaternion} A reference to this quaternion.
  3448. */
  3449. multiply( q ) {
  3450. return this.multiplyQuaternions( this, q );
  3451. }
  3452. /**
  3453. * Pre-multiplies this quaternion by the given one.
  3454. *
  3455. * @param {Quaternion} q - The quaternion.
  3456. * @return {Quaternion} A reference to this quaternion.
  3457. */
  3458. premultiply( q ) {
  3459. return this.multiplyQuaternions( q, this );
  3460. }
  3461. /**
  3462. * Multiplies the given quaternions and stores the result in this instance.
  3463. *
  3464. * @param {Quaternion} a - The first quaternion.
  3465. * @param {Quaternion} b - The second quaternion.
  3466. * @return {Quaternion} A reference to this quaternion.
  3467. */
  3468. multiplyQuaternions( a, b ) {
  3469. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3470. const qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  3471. const qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  3472. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3473. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3474. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3475. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3476. this._onChangeCallback();
  3477. return this;
  3478. }
  3479. /**
  3480. * Performs a spherical linear interpolation between quaternions.
  3481. *
  3482. * @param {Quaternion} qb - The target quaternion.
  3483. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3484. * @return {Quaternion} A reference to this quaternion.
  3485. */
  3486. slerp( qb, t ) {
  3487. if ( t <= 0 ) return this;
  3488. if ( t >= 1 ) return this.copy( qb ); // copy calls _onChangeCallback()
  3489. let x = qb._x, y = qb._y, z = qb._z, w = qb._w;
  3490. let dot = this.dot( qb );
  3491. if ( dot < 0 ) {
  3492. x = - x;
  3493. y = - y;
  3494. z = - z;
  3495. w = - w;
  3496. dot = - dot;
  3497. }
  3498. let s = 1 - t;
  3499. if ( dot < 0.9995 ) {
  3500. // slerp
  3501. const theta = Math.acos( dot );
  3502. const sin = Math.sin( theta );
  3503. s = Math.sin( s * theta ) / sin;
  3504. t = Math.sin( t * theta ) / sin;
  3505. this._x = this._x * s + x * t;
  3506. this._y = this._y * s + y * t;
  3507. this._z = this._z * s + z * t;
  3508. this._w = this._w * s + w * t;
  3509. this._onChangeCallback();
  3510. } else {
  3511. // for small angles, lerp then normalize
  3512. this._x = this._x * s + x * t;
  3513. this._y = this._y * s + y * t;
  3514. this._z = this._z * s + z * t;
  3515. this._w = this._w * s + w * t;
  3516. this.normalize(); // normalize calls _onChangeCallback()
  3517. }
  3518. return this;
  3519. }
  3520. /**
  3521. * Performs a spherical linear interpolation between the given quaternions
  3522. * and stores the result in this quaternion.
  3523. *
  3524. * @param {Quaternion} qa - The source quaternion.
  3525. * @param {Quaternion} qb - The target quaternion.
  3526. * @param {number} t - The interpolation factor in the closed interval `[0, 1]`.
  3527. * @return {Quaternion} A reference to this quaternion.
  3528. */
  3529. slerpQuaternions( qa, qb, t ) {
  3530. return this.copy( qa ).slerp( qb, t );
  3531. }
  3532. /**
  3533. * Sets this quaternion to a uniformly random, normalized quaternion.
  3534. *
  3535. * @return {Quaternion} A reference to this quaternion.
  3536. */
  3537. random() {
  3538. // Ken Shoemake
  3539. // Uniform random rotations
  3540. // D. Kirk, editor, Graphics Gems III, pages 124-132. Academic Press, New York, 1992.
  3541. const theta1 = 2 * Math.PI * Math.random();
  3542. const theta2 = 2 * Math.PI * Math.random();
  3543. const x0 = Math.random();
  3544. const r1 = Math.sqrt( 1 - x0 );
  3545. const r2 = Math.sqrt( x0 );
  3546. return this.set(
  3547. r1 * Math.sin( theta1 ),
  3548. r1 * Math.cos( theta1 ),
  3549. r2 * Math.sin( theta2 ),
  3550. r2 * Math.cos( theta2 ),
  3551. );
  3552. }
  3553. /**
  3554. * Returns `true` if this quaternion is equal with the given one.
  3555. *
  3556. * @param {Quaternion} quaternion - The quaternion to test for equality.
  3557. * @return {boolean} Whether this quaternion is equal with the given one.
  3558. */
  3559. equals( quaternion ) {
  3560. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  3561. }
  3562. /**
  3563. * Sets this quaternion's components from the given array.
  3564. *
  3565. * @param {Array<number>} array - An array holding the quaternion component values.
  3566. * @param {number} [offset=0] - The offset into the array.
  3567. * @return {Quaternion} A reference to this quaternion.
  3568. */
  3569. fromArray( array, offset = 0 ) {
  3570. this._x = array[ offset ];
  3571. this._y = array[ offset + 1 ];
  3572. this._z = array[ offset + 2 ];
  3573. this._w = array[ offset + 3 ];
  3574. this._onChangeCallback();
  3575. return this;
  3576. }
  3577. /**
  3578. * Writes the components of this quaternion to the given array. If no array is provided,
  3579. * the method returns a new instance.
  3580. *
  3581. * @param {Array<number>} [array=[]] - The target array holding the quaternion components.
  3582. * @param {number} [offset=0] - Index of the first element in the array.
  3583. * @return {Array<number>} The quaternion components.
  3584. */
  3585. toArray( array = [], offset = 0 ) {
  3586. array[ offset ] = this._x;
  3587. array[ offset + 1 ] = this._y;
  3588. array[ offset + 2 ] = this._z;
  3589. array[ offset + 3 ] = this._w;
  3590. return array;
  3591. }
  3592. /**
  3593. * Sets the components of this quaternion from the given buffer attribute.
  3594. *
  3595. * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data.
  3596. * @param {number} index - The index into the attribute.
  3597. * @return {Quaternion} A reference to this quaternion.
  3598. */
  3599. fromBufferAttribute( attribute, index ) {
  3600. this._x = attribute.getX( index );
  3601. this._y = attribute.getY( index );
  3602. this._z = attribute.getZ( index );
  3603. this._w = attribute.getW( index );
  3604. this._onChangeCallback();
  3605. return this;
  3606. }
  3607. /**
  3608. * This methods defines the serialization result of this class. Returns the
  3609. * numerical elements of this quaternion in an array of format `[x, y, z, w]`.
  3610. *
  3611. * @return {Array<number>} The serialized quaternion.
  3612. */
  3613. toJSON() {
  3614. return this.toArray();
  3615. }
  3616. _onChange( callback ) {
  3617. this._onChangeCallback = callback;
  3618. return this;
  3619. }
  3620. _onChangeCallback() {}
  3621. *[ Symbol.iterator ]() {
  3622. yield this._x;
  3623. yield this._y;
  3624. yield this._z;
  3625. yield this._w;
  3626. }
  3627. }
  3628. /**
  3629. * Class representing a 3D vector. A 3D vector is an ordered triplet of numbers
  3630. * (labeled x, y and z), which can be used to represent a number of things, such as:
  3631. *
  3632. * - A point in 3D space.
  3633. * - A direction and length in 3D space. In three.js the length will
  3634. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0)` to `(x, y, z)`
  3635. * and the direction is also measured from `(0, 0, 0)` towards `(x, y, z)`.
  3636. * - Any arbitrary ordered triplet of numbers.
  3637. *
  3638. * There are other things a 3D vector can be used to represent, such as
  3639. * momentum vectors and so on, however these are the most
  3640. * common uses in three.js.
  3641. *
  3642. * Iterating through a vector instance will yield its components `(x, y, z)` in
  3643. * the corresponding order.
  3644. * ```js
  3645. * const a = new THREE.Vector3( 0, 1, 0 );
  3646. *
  3647. * //no arguments; will be initialised to (0, 0, 0)
  3648. * const b = new THREE.Vector3( );
  3649. *
  3650. * const d = a.distanceTo( b );
  3651. * ```
  3652. */
  3653. class Vector3 {
  3654. /**
  3655. * Constructs a new 3D vector.
  3656. *
  3657. * @param {number} [x=0] - The x value of this vector.
  3658. * @param {number} [y=0] - The y value of this vector.
  3659. * @param {number} [z=0] - The z value of this vector.
  3660. */
  3661. constructor( x = 0, y = 0, z = 0 ) {
  3662. /**
  3663. * This flag can be used for type testing.
  3664. *
  3665. * @type {boolean}
  3666. * @readonly
  3667. * @default true
  3668. */
  3669. Vector3.prototype.isVector3 = true;
  3670. /**
  3671. * The x value of this vector.
  3672. *
  3673. * @type {number}
  3674. */
  3675. this.x = x;
  3676. /**
  3677. * The y value of this vector.
  3678. *
  3679. * @type {number}
  3680. */
  3681. this.y = y;
  3682. /**
  3683. * The z value of this vector.
  3684. *
  3685. * @type {number}
  3686. */
  3687. this.z = z;
  3688. }
  3689. /**
  3690. * Sets the vector components.
  3691. *
  3692. * @param {number} x - The value of the x component.
  3693. * @param {number} y - The value of the y component.
  3694. * @param {number} z - The value of the z component.
  3695. * @return {Vector3} A reference to this vector.
  3696. */
  3697. set( x, y, z ) {
  3698. if ( z === undefined ) z = this.z; // sprite.scale.set(x,y)
  3699. this.x = x;
  3700. this.y = y;
  3701. this.z = z;
  3702. return this;
  3703. }
  3704. /**
  3705. * Sets the vector components to the same value.
  3706. *
  3707. * @param {number} scalar - The value to set for all vector components.
  3708. * @return {Vector3} A reference to this vector.
  3709. */
  3710. setScalar( scalar ) {
  3711. this.x = scalar;
  3712. this.y = scalar;
  3713. this.z = scalar;
  3714. return this;
  3715. }
  3716. /**
  3717. * Sets the vector's x component to the given value
  3718. *
  3719. * @param {number} x - The value to set.
  3720. * @return {Vector3} A reference to this vector.
  3721. */
  3722. setX( x ) {
  3723. this.x = x;
  3724. return this;
  3725. }
  3726. /**
  3727. * Sets the vector's y component to the given value
  3728. *
  3729. * @param {number} y - The value to set.
  3730. * @return {Vector3} A reference to this vector.
  3731. */
  3732. setY( y ) {
  3733. this.y = y;
  3734. return this;
  3735. }
  3736. /**
  3737. * Sets the vector's z component to the given value
  3738. *
  3739. * @param {number} z - The value to set.
  3740. * @return {Vector3} A reference to this vector.
  3741. */
  3742. setZ( z ) {
  3743. this.z = z;
  3744. return this;
  3745. }
  3746. /**
  3747. * Allows to set a vector component with an index.
  3748. *
  3749. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3750. * @param {number} value - The value to set.
  3751. * @return {Vector3} A reference to this vector.
  3752. */
  3753. setComponent( index, value ) {
  3754. switch ( index ) {
  3755. case 0: this.x = value; break;
  3756. case 1: this.y = value; break;
  3757. case 2: this.z = value; break;
  3758. default: throw new Error( 'index is out of range: ' + index );
  3759. }
  3760. return this;
  3761. }
  3762. /**
  3763. * Returns the value of the vector component which matches the given index.
  3764. *
  3765. * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z.
  3766. * @return {number} A vector component value.
  3767. */
  3768. getComponent( index ) {
  3769. switch ( index ) {
  3770. case 0: return this.x;
  3771. case 1: return this.y;
  3772. case 2: return this.z;
  3773. default: throw new Error( 'index is out of range: ' + index );
  3774. }
  3775. }
  3776. /**
  3777. * Returns a new vector with copied values from this instance.
  3778. *
  3779. * @return {Vector3} A clone of this instance.
  3780. */
  3781. clone() {
  3782. return new this.constructor( this.x, this.y, this.z );
  3783. }
  3784. /**
  3785. * Copies the values of the given vector to this instance.
  3786. *
  3787. * @param {Vector3} v - The vector to copy.
  3788. * @return {Vector3} A reference to this vector.
  3789. */
  3790. copy( v ) {
  3791. this.x = v.x;
  3792. this.y = v.y;
  3793. this.z = v.z;
  3794. return this;
  3795. }
  3796. /**
  3797. * Adds the given vector to this instance.
  3798. *
  3799. * @param {Vector3} v - The vector to add.
  3800. * @return {Vector3} A reference to this vector.
  3801. */
  3802. add( v ) {
  3803. this.x += v.x;
  3804. this.y += v.y;
  3805. this.z += v.z;
  3806. return this;
  3807. }
  3808. /**
  3809. * Adds the given scalar value to all components of this instance.
  3810. *
  3811. * @param {number} s - The scalar to add.
  3812. * @return {Vector3} A reference to this vector.
  3813. */
  3814. addScalar( s ) {
  3815. this.x += s;
  3816. this.y += s;
  3817. this.z += s;
  3818. return this;
  3819. }
  3820. /**
  3821. * Adds the given vectors and stores the result in this instance.
  3822. *
  3823. * @param {Vector3} a - The first vector.
  3824. * @param {Vector3} b - The second vector.
  3825. * @return {Vector3} A reference to this vector.
  3826. */
  3827. addVectors( a, b ) {
  3828. this.x = a.x + b.x;
  3829. this.y = a.y + b.y;
  3830. this.z = a.z + b.z;
  3831. return this;
  3832. }
  3833. /**
  3834. * Adds the given vector scaled by the given factor to this instance.
  3835. *
  3836. * @param {Vector3|Vector4} v - The vector.
  3837. * @param {number} s - The factor that scales `v`.
  3838. * @return {Vector3} A reference to this vector.
  3839. */
  3840. addScaledVector( v, s ) {
  3841. this.x += v.x * s;
  3842. this.y += v.y * s;
  3843. this.z += v.z * s;
  3844. return this;
  3845. }
  3846. /**
  3847. * Subtracts the given vector from this instance.
  3848. *
  3849. * @param {Vector3} v - The vector to subtract.
  3850. * @return {Vector3} A reference to this vector.
  3851. */
  3852. sub( v ) {
  3853. this.x -= v.x;
  3854. this.y -= v.y;
  3855. this.z -= v.z;
  3856. return this;
  3857. }
  3858. /**
  3859. * Subtracts the given scalar value from all components of this instance.
  3860. *
  3861. * @param {number} s - The scalar to subtract.
  3862. * @return {Vector3} A reference to this vector.
  3863. */
  3864. subScalar( s ) {
  3865. this.x -= s;
  3866. this.y -= s;
  3867. this.z -= s;
  3868. return this;
  3869. }
  3870. /**
  3871. * Subtracts the given vectors and stores the result in this instance.
  3872. *
  3873. * @param {Vector3} a - The first vector.
  3874. * @param {Vector3} b - The second vector.
  3875. * @return {Vector3} A reference to this vector.
  3876. */
  3877. subVectors( a, b ) {
  3878. this.x = a.x - b.x;
  3879. this.y = a.y - b.y;
  3880. this.z = a.z - b.z;
  3881. return this;
  3882. }
  3883. /**
  3884. * Multiplies the given vector with this instance.
  3885. *
  3886. * @param {Vector3} v - The vector to multiply.
  3887. * @return {Vector3} A reference to this vector.
  3888. */
  3889. multiply( v ) {
  3890. this.x *= v.x;
  3891. this.y *= v.y;
  3892. this.z *= v.z;
  3893. return this;
  3894. }
  3895. /**
  3896. * Multiplies the given scalar value with all components of this instance.
  3897. *
  3898. * @param {number} scalar - The scalar to multiply.
  3899. * @return {Vector3} A reference to this vector.
  3900. */
  3901. multiplyScalar( scalar ) {
  3902. this.x *= scalar;
  3903. this.y *= scalar;
  3904. this.z *= scalar;
  3905. return this;
  3906. }
  3907. /**
  3908. * Multiplies the given vectors and stores the result in this instance.
  3909. *
  3910. * @param {Vector3} a - The first vector.
  3911. * @param {Vector3} b - The second vector.
  3912. * @return {Vector3} A reference to this vector.
  3913. */
  3914. multiplyVectors( a, b ) {
  3915. this.x = a.x * b.x;
  3916. this.y = a.y * b.y;
  3917. this.z = a.z * b.z;
  3918. return this;
  3919. }
  3920. /**
  3921. * Applies the given Euler rotation to this vector.
  3922. *
  3923. * @param {Euler} euler - The Euler angles.
  3924. * @return {Vector3} A reference to this vector.
  3925. */
  3926. applyEuler( euler ) {
  3927. return this.applyQuaternion( _quaternion$4.setFromEuler( euler ) );
  3928. }
  3929. /**
  3930. * Applies a rotation specified by an axis and an angle to this vector.
  3931. *
  3932. * @param {Vector3} axis - A normalized vector representing the rotation axis.
  3933. * @param {number} angle - The angle in radians.
  3934. * @return {Vector3} A reference to this vector.
  3935. */
  3936. applyAxisAngle( axis, angle ) {
  3937. return this.applyQuaternion( _quaternion$4.setFromAxisAngle( axis, angle ) );
  3938. }
  3939. /**
  3940. * Multiplies this vector with the given 3x3 matrix.
  3941. *
  3942. * @param {Matrix3} m - The 3x3 matrix.
  3943. * @return {Vector3} A reference to this vector.
  3944. */
  3945. applyMatrix3( m ) {
  3946. const x = this.x, y = this.y, z = this.z;
  3947. const e = m.elements;
  3948. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  3949. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  3950. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  3951. return this;
  3952. }
  3953. /**
  3954. * Multiplies this vector by the given normal matrix and normalizes
  3955. * the result.
  3956. *
  3957. * @param {Matrix3} m - The normal matrix.
  3958. * @return {Vector3} A reference to this vector.
  3959. */
  3960. applyNormalMatrix( m ) {
  3961. return this.applyMatrix3( m ).normalize();
  3962. }
  3963. /**
  3964. * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and
  3965. * divides by perspective.
  3966. *
  3967. * @param {Matrix4} m - The matrix to apply.
  3968. * @return {Vector3} A reference to this vector.
  3969. */
  3970. applyMatrix4( m ) {
  3971. const x = this.x, y = this.y, z = this.z;
  3972. const e = m.elements;
  3973. const w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  3974. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  3975. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  3976. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  3977. return this;
  3978. }
  3979. /**
  3980. * Applies the given Quaternion to this vector.
  3981. *
  3982. * @param {Quaternion} q - The Quaternion.
  3983. * @return {Vector3} A reference to this vector.
  3984. */
  3985. applyQuaternion( q ) {
  3986. // quaternion q is assumed to have unit length
  3987. const vx = this.x, vy = this.y, vz = this.z;
  3988. const qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  3989. // t = 2 * cross( q.xyz, v );
  3990. const tx = 2 * ( qy * vz - qz * vy );
  3991. const ty = 2 * ( qz * vx - qx * vz );
  3992. const tz = 2 * ( qx * vy - qy * vx );
  3993. // v + q.w * t + cross( q.xyz, t );
  3994. this.x = vx + qw * tx + qy * tz - qz * ty;
  3995. this.y = vy + qw * ty + qz * tx - qx * tz;
  3996. this.z = vz + qw * tz + qx * ty - qy * tx;
  3997. return this;
  3998. }
  3999. /**
  4000. * Projects this vector from world space into the camera's normalized
  4001. * device coordinate (NDC) space.
  4002. *
  4003. * @param {Camera} camera - The camera.
  4004. * @return {Vector3} A reference to this vector.
  4005. */
  4006. project( camera ) {
  4007. return this.applyMatrix4( camera.matrixWorldInverse ).applyMatrix4( camera.projectionMatrix );
  4008. }
  4009. /**
  4010. * Unprojects this vector from the camera's normalized device coordinate (NDC)
  4011. * space into world space.
  4012. *
  4013. * @param {Camera} camera - The camera.
  4014. * @return {Vector3} A reference to this vector.
  4015. */
  4016. unproject( camera ) {
  4017. return this.applyMatrix4( camera.projectionMatrixInverse ).applyMatrix4( camera.matrixWorld );
  4018. }
  4019. /**
  4020. * Transforms the direction of this vector by a matrix (the upper left 3 x 3
  4021. * subset of the given 4x4 matrix and then normalizes the result.
  4022. *
  4023. * @param {Matrix4} m - The matrix.
  4024. * @return {Vector3} A reference to this vector.
  4025. */
  4026. transformDirection( m ) {
  4027. // input: THREE.Matrix4 affine matrix
  4028. // vector interpreted as a direction
  4029. const x = this.x, y = this.y, z = this.z;
  4030. const e = m.elements;
  4031. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  4032. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  4033. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  4034. return this.normalize();
  4035. }
  4036. /**
  4037. * Divides this instance by the given vector.
  4038. *
  4039. * @param {Vector3} v - The vector to divide.
  4040. * @return {Vector3} A reference to this vector.
  4041. */
  4042. divide( v ) {
  4043. this.x /= v.x;
  4044. this.y /= v.y;
  4045. this.z /= v.z;
  4046. return this;
  4047. }
  4048. /**
  4049. * Divides this vector by the given scalar.
  4050. *
  4051. * @param {number} scalar - The scalar to divide.
  4052. * @return {Vector3} A reference to this vector.
  4053. */
  4054. divideScalar( scalar ) {
  4055. return this.multiplyScalar( 1 / scalar );
  4056. }
  4057. /**
  4058. * If this vector's x, y or z value is greater than the given vector's x, y or z
  4059. * value, replace that value with the corresponding min value.
  4060. *
  4061. * @param {Vector3} v - The vector.
  4062. * @return {Vector3} A reference to this vector.
  4063. */
  4064. min( v ) {
  4065. this.x = Math.min( this.x, v.x );
  4066. this.y = Math.min( this.y, v.y );
  4067. this.z = Math.min( this.z, v.z );
  4068. return this;
  4069. }
  4070. /**
  4071. * If this vector's x, y or z value is less than the given vector's x, y or z
  4072. * value, replace that value with the corresponding max value.
  4073. *
  4074. * @param {Vector3} v - The vector.
  4075. * @return {Vector3} A reference to this vector.
  4076. */
  4077. max( v ) {
  4078. this.x = Math.max( this.x, v.x );
  4079. this.y = Math.max( this.y, v.y );
  4080. this.z = Math.max( this.z, v.z );
  4081. return this;
  4082. }
  4083. /**
  4084. * If this vector's x, y or z value is greater than the max vector's x, y or z
  4085. * value, it is replaced by the corresponding value.
  4086. * If this vector's x, y or z value is less than the min vector's x, y or z value,
  4087. * it is replaced by the corresponding value.
  4088. *
  4089. * @param {Vector3} min - The minimum x, y and z values.
  4090. * @param {Vector3} max - The maximum x, y and z values in the desired range.
  4091. * @return {Vector3} A reference to this vector.
  4092. */
  4093. clamp( min, max ) {
  4094. // assumes min < max, componentwise
  4095. this.x = clamp( this.x, min.x, max.x );
  4096. this.y = clamp( this.y, min.y, max.y );
  4097. this.z = clamp( this.z, min.z, max.z );
  4098. return this;
  4099. }
  4100. /**
  4101. * If this vector's x, y or z values are greater than the max value, they are
  4102. * replaced by the max value.
  4103. * If this vector's x, y or z values are less than the min value, they are
  4104. * replaced by the min value.
  4105. *
  4106. * @param {number} minVal - The minimum value the components will be clamped to.
  4107. * @param {number} maxVal - The maximum value the components will be clamped to.
  4108. * @return {Vector3} A reference to this vector.
  4109. */
  4110. clampScalar( minVal, maxVal ) {
  4111. this.x = clamp( this.x, minVal, maxVal );
  4112. this.y = clamp( this.y, minVal, maxVal );
  4113. this.z = clamp( this.z, minVal, maxVal );
  4114. return this;
  4115. }
  4116. /**
  4117. * If this vector's length is greater than the max value, it is replaced by
  4118. * the max value.
  4119. * If this vector's length is less than the min value, it is replaced by the
  4120. * min value.
  4121. *
  4122. * @param {number} min - The minimum value the vector length will be clamped to.
  4123. * @param {number} max - The maximum value the vector length will be clamped to.
  4124. * @return {Vector3} A reference to this vector.
  4125. */
  4126. clampLength( min, max ) {
  4127. const length = this.length();
  4128. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  4129. }
  4130. /**
  4131. * The components of this vector are rounded down to the nearest integer value.
  4132. *
  4133. * @return {Vector3} A reference to this vector.
  4134. */
  4135. floor() {
  4136. this.x = Math.floor( this.x );
  4137. this.y = Math.floor( this.y );
  4138. this.z = Math.floor( this.z );
  4139. return this;
  4140. }
  4141. /**
  4142. * The components of this vector are rounded up to the nearest integer value.
  4143. *
  4144. * @return {Vector3} A reference to this vector.
  4145. */
  4146. ceil() {
  4147. this.x = Math.ceil( this.x );
  4148. this.y = Math.ceil( this.y );
  4149. this.z = Math.ceil( this.z );
  4150. return this;
  4151. }
  4152. /**
  4153. * The components of this vector are rounded to the nearest integer value
  4154. *
  4155. * @return {Vector3} A reference to this vector.
  4156. */
  4157. round() {
  4158. this.x = Math.round( this.x );
  4159. this.y = Math.round( this.y );
  4160. this.z = Math.round( this.z );
  4161. return this;
  4162. }
  4163. /**
  4164. * The components of this vector are rounded towards zero (up if negative,
  4165. * down if positive) to an integer value.
  4166. *
  4167. * @return {Vector3} A reference to this vector.
  4168. */
  4169. roundToZero() {
  4170. this.x = Math.trunc( this.x );
  4171. this.y = Math.trunc( this.y );
  4172. this.z = Math.trunc( this.z );
  4173. return this;
  4174. }
  4175. /**
  4176. * Inverts this vector - i.e. sets x = -x, y = -y and z = -z.
  4177. *
  4178. * @return {Vector3} A reference to this vector.
  4179. */
  4180. negate() {
  4181. this.x = - this.x;
  4182. this.y = - this.y;
  4183. this.z = - this.z;
  4184. return this;
  4185. }
  4186. /**
  4187. * Calculates the dot product of the given vector with this instance.
  4188. *
  4189. * @param {Vector3} v - The vector to compute the dot product with.
  4190. * @return {number} The result of the dot product.
  4191. */
  4192. dot( v ) {
  4193. return this.x * v.x + this.y * v.y + this.z * v.z;
  4194. }
  4195. // TODO lengthSquared?
  4196. /**
  4197. * Computes the square of the Euclidean length (straight-line length) from
  4198. * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should
  4199. * compare the length squared instead as it is slightly more efficient to calculate.
  4200. *
  4201. * @return {number} The square length of this vector.
  4202. */
  4203. lengthSq() {
  4204. return this.x * this.x + this.y * this.y + this.z * this.z;
  4205. }
  4206. /**
  4207. * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z).
  4208. *
  4209. * @return {number} The length of this vector.
  4210. */
  4211. length() {
  4212. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  4213. }
  4214. /**
  4215. * Computes the Manhattan length of this vector.
  4216. *
  4217. * @return {number} The length of this vector.
  4218. */
  4219. manhattanLength() {
  4220. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  4221. }
  4222. /**
  4223. * Converts this vector to a unit vector - that is, sets it equal to a vector
  4224. * with the same direction as this one, but with a vector length of `1`.
  4225. *
  4226. * @return {Vector3} A reference to this vector.
  4227. */
  4228. normalize() {
  4229. return this.divideScalar( this.length() || 1 );
  4230. }
  4231. /**
  4232. * Sets this vector to a vector with the same direction as this one, but
  4233. * with the specified length.
  4234. *
  4235. * @param {number} length - The new length of this vector.
  4236. * @return {Vector3} A reference to this vector.
  4237. */
  4238. setLength( length ) {
  4239. return this.normalize().multiplyScalar( length );
  4240. }
  4241. /**
  4242. * Linearly interpolates between the given vector and this instance, where
  4243. * alpha is the percent distance along the line - alpha = 0 will be this
  4244. * vector, and alpha = 1 will be the given one.
  4245. *
  4246. * @param {Vector3} v - The vector to interpolate towards.
  4247. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4248. * @return {Vector3} A reference to this vector.
  4249. */
  4250. lerp( v, alpha ) {
  4251. this.x += ( v.x - this.x ) * alpha;
  4252. this.y += ( v.y - this.y ) * alpha;
  4253. this.z += ( v.z - this.z ) * alpha;
  4254. return this;
  4255. }
  4256. /**
  4257. * Linearly interpolates between the given vectors, where alpha is the percent
  4258. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  4259. * be the second one. The result is stored in this instance.
  4260. *
  4261. * @param {Vector3} v1 - The first vector.
  4262. * @param {Vector3} v2 - The second vector.
  4263. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  4264. * @return {Vector3} A reference to this vector.
  4265. */
  4266. lerpVectors( v1, v2, alpha ) {
  4267. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  4268. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  4269. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  4270. return this;
  4271. }
  4272. /**
  4273. * Calculates the cross product of the given vector with this instance.
  4274. *
  4275. * @param {Vector3} v - The vector to compute the cross product with.
  4276. * @return {Vector3} The result of the cross product.
  4277. */
  4278. cross( v ) {
  4279. return this.crossVectors( this, v );
  4280. }
  4281. /**
  4282. * Calculates the cross product of the given vectors and stores the result
  4283. * in this instance.
  4284. *
  4285. * @param {Vector3} a - The first vector.
  4286. * @param {Vector3} b - The second vector.
  4287. * @return {Vector3} A reference to this vector.
  4288. */
  4289. crossVectors( a, b ) {
  4290. const ax = a.x, ay = a.y, az = a.z;
  4291. const bx = b.x, by = b.y, bz = b.z;
  4292. this.x = ay * bz - az * by;
  4293. this.y = az * bx - ax * bz;
  4294. this.z = ax * by - ay * bx;
  4295. return this;
  4296. }
  4297. /**
  4298. * Projects this vector onto the given one.
  4299. *
  4300. * @param {Vector3} v - The vector to project to.
  4301. * @return {Vector3} A reference to this vector.
  4302. */
  4303. projectOnVector( v ) {
  4304. const denominator = v.lengthSq();
  4305. if ( denominator === 0 ) return this.set( 0, 0, 0 );
  4306. const scalar = v.dot( this ) / denominator;
  4307. return this.copy( v ).multiplyScalar( scalar );
  4308. }
  4309. /**
  4310. * Projects this vector onto a plane by subtracting this
  4311. * vector projected onto the plane's normal from this vector.
  4312. *
  4313. * @param {Vector3} planeNormal - The plane normal.
  4314. * @return {Vector3} A reference to this vector.
  4315. */
  4316. projectOnPlane( planeNormal ) {
  4317. _vector$c.copy( this ).projectOnVector( planeNormal );
  4318. return this.sub( _vector$c );
  4319. }
  4320. /**
  4321. * Reflects this vector off a plane orthogonal to the given normal vector.
  4322. *
  4323. * @param {Vector3} normal - The (normalized) normal vector.
  4324. * @return {Vector3} A reference to this vector.
  4325. */
  4326. reflect( normal ) {
  4327. return this.sub( _vector$c.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  4328. }
  4329. /**
  4330. * Returns the angle between the given vector and this instance in radians.
  4331. *
  4332. * @param {Vector3} v - The vector to compute the angle with.
  4333. * @return {number} The angle in radians.
  4334. */
  4335. angleTo( v ) {
  4336. const denominator = Math.sqrt( this.lengthSq() * v.lengthSq() );
  4337. if ( denominator === 0 ) return Math.PI / 2;
  4338. const theta = this.dot( v ) / denominator;
  4339. // clamp, to handle numerical problems
  4340. return Math.acos( clamp( theta, -1, 1 ) );
  4341. }
  4342. /**
  4343. * Computes the distance from the given vector to this instance.
  4344. *
  4345. * @param {Vector3} v - The vector to compute the distance to.
  4346. * @return {number} The distance.
  4347. */
  4348. distanceTo( v ) {
  4349. return Math.sqrt( this.distanceToSquared( v ) );
  4350. }
  4351. /**
  4352. * Computes the squared distance from the given vector to this instance.
  4353. * If you are just comparing the distance with another distance, you should compare
  4354. * the distance squared instead as it is slightly more efficient to calculate.
  4355. *
  4356. * @param {Vector3} v - The vector to compute the squared distance to.
  4357. * @return {number} The squared distance.
  4358. */
  4359. distanceToSquared( v ) {
  4360. const dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  4361. return dx * dx + dy * dy + dz * dz;
  4362. }
  4363. /**
  4364. * Computes the Manhattan distance from the given vector to this instance.
  4365. *
  4366. * @param {Vector3} v - The vector to compute the Manhattan distance to.
  4367. * @return {number} The Manhattan distance.
  4368. */
  4369. manhattanDistanceTo( v ) {
  4370. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  4371. }
  4372. /**
  4373. * Sets the vector components from the given spherical coordinates.
  4374. *
  4375. * @param {Spherical} s - The spherical coordinates.
  4376. * @return {Vector3} A reference to this vector.
  4377. */
  4378. setFromSpherical( s ) {
  4379. return this.setFromSphericalCoords( s.radius, s.phi, s.theta );
  4380. }
  4381. /**
  4382. * Sets the vector components from the given spherical coordinates.
  4383. *
  4384. * @param {number} radius - The radius.
  4385. * @param {number} phi - The phi angle in radians.
  4386. * @param {number} theta - The theta angle in radians.
  4387. * @return {Vector3} A reference to this vector.
  4388. */
  4389. setFromSphericalCoords( radius, phi, theta ) {
  4390. const sinPhiRadius = Math.sin( phi ) * radius;
  4391. this.x = sinPhiRadius * Math.sin( theta );
  4392. this.y = Math.cos( phi ) * radius;
  4393. this.z = sinPhiRadius * Math.cos( theta );
  4394. return this;
  4395. }
  4396. /**
  4397. * Sets the vector components from the given cylindrical coordinates.
  4398. *
  4399. * @param {Cylindrical} c - The cylindrical coordinates.
  4400. * @return {Vector3} A reference to this vector.
  4401. */
  4402. setFromCylindrical( c ) {
  4403. return this.setFromCylindricalCoords( c.radius, c.theta, c.y );
  4404. }
  4405. /**
  4406. * Sets the vector components from the given cylindrical coordinates.
  4407. *
  4408. * @param {number} radius - The radius.
  4409. * @param {number} theta - The theta angle in radians.
  4410. * @param {number} y - The y value.
  4411. * @return {Vector3} A reference to this vector.
  4412. */
  4413. setFromCylindricalCoords( radius, theta, y ) {
  4414. this.x = radius * Math.sin( theta );
  4415. this.y = y;
  4416. this.z = radius * Math.cos( theta );
  4417. return this;
  4418. }
  4419. /**
  4420. * Sets the vector components to the position elements of the
  4421. * given transformation matrix.
  4422. *
  4423. * @param {Matrix4} m - The 4x4 matrix.
  4424. * @return {Vector3} A reference to this vector.
  4425. */
  4426. setFromMatrixPosition( m ) {
  4427. const e = m.elements;
  4428. this.x = e[ 12 ];
  4429. this.y = e[ 13 ];
  4430. this.z = e[ 14 ];
  4431. return this;
  4432. }
  4433. /**
  4434. * Sets the vector components to the scale elements of the
  4435. * given transformation matrix.
  4436. *
  4437. * @param {Matrix4} m - The 4x4 matrix.
  4438. * @return {Vector3} A reference to this vector.
  4439. */
  4440. setFromMatrixScale( m ) {
  4441. const sx = this.setFromMatrixColumn( m, 0 ).length();
  4442. const sy = this.setFromMatrixColumn( m, 1 ).length();
  4443. const sz = this.setFromMatrixColumn( m, 2 ).length();
  4444. this.x = sx;
  4445. this.y = sy;
  4446. this.z = sz;
  4447. return this;
  4448. }
  4449. /**
  4450. * Sets the vector components from the specified matrix column.
  4451. *
  4452. * @param {Matrix4} m - The 4x4 matrix.
  4453. * @param {number} index - The column index.
  4454. * @return {Vector3} A reference to this vector.
  4455. */
  4456. setFromMatrixColumn( m, index ) {
  4457. return this.fromArray( m.elements, index * 4 );
  4458. }
  4459. /**
  4460. * Sets the vector components from the specified matrix column.
  4461. *
  4462. * @param {Matrix3} m - The 3x3 matrix.
  4463. * @param {number} index - The column index.
  4464. * @return {Vector3} A reference to this vector.
  4465. */
  4466. setFromMatrix3Column( m, index ) {
  4467. return this.fromArray( m.elements, index * 3 );
  4468. }
  4469. /**
  4470. * Sets the vector components from the given Euler angles.
  4471. *
  4472. * @param {Euler} e - The Euler angles to set.
  4473. * @return {Vector3} A reference to this vector.
  4474. */
  4475. setFromEuler( e ) {
  4476. this.x = e._x;
  4477. this.y = e._y;
  4478. this.z = e._z;
  4479. return this;
  4480. }
  4481. /**
  4482. * Sets the vector components from the RGB components of the
  4483. * given color.
  4484. *
  4485. * @param {Color} c - The color to set.
  4486. * @return {Vector3} A reference to this vector.
  4487. */
  4488. setFromColor( c ) {
  4489. this.x = c.r;
  4490. this.y = c.g;
  4491. this.z = c.b;
  4492. return this;
  4493. }
  4494. /**
  4495. * Returns `true` if this vector is equal with the given one.
  4496. *
  4497. * @param {Vector3} v - The vector to test for equality.
  4498. * @return {boolean} Whether this vector is equal with the given one.
  4499. */
  4500. equals( v ) {
  4501. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  4502. }
  4503. /**
  4504. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`
  4505. * and z value to be `array[ offset + 2 ]`.
  4506. *
  4507. * @param {Array<number>} array - An array holding the vector component values.
  4508. * @param {number} [offset=0] - The offset into the array.
  4509. * @return {Vector3} A reference to this vector.
  4510. */
  4511. fromArray( array, offset = 0 ) {
  4512. this.x = array[ offset ];
  4513. this.y = array[ offset + 1 ];
  4514. this.z = array[ offset + 2 ];
  4515. return this;
  4516. }
  4517. /**
  4518. * Writes the components of this vector to the given array. If no array is provided,
  4519. * the method returns a new instance.
  4520. *
  4521. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  4522. * @param {number} [offset=0] - Index of the first element in the array.
  4523. * @return {Array<number>} The vector components.
  4524. */
  4525. toArray( array = [], offset = 0 ) {
  4526. array[ offset ] = this.x;
  4527. array[ offset + 1 ] = this.y;
  4528. array[ offset + 2 ] = this.z;
  4529. return array;
  4530. }
  4531. /**
  4532. * Sets the components of this vector from the given buffer attribute.
  4533. *
  4534. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  4535. * @param {number} index - The index into the attribute.
  4536. * @return {Vector3} A reference to this vector.
  4537. */
  4538. fromBufferAttribute( attribute, index ) {
  4539. this.x = attribute.getX( index );
  4540. this.y = attribute.getY( index );
  4541. this.z = attribute.getZ( index );
  4542. return this;
  4543. }
  4544. /**
  4545. * Sets each component of this vector to a pseudo-random value between `0` and
  4546. * `1`, excluding `1`.
  4547. *
  4548. * @return {Vector3} A reference to this vector.
  4549. */
  4550. random() {
  4551. this.x = Math.random();
  4552. this.y = Math.random();
  4553. this.z = Math.random();
  4554. return this;
  4555. }
  4556. /**
  4557. * Sets this vector to a uniformly random point on a unit sphere.
  4558. *
  4559. * @return {Vector3} A reference to this vector.
  4560. */
  4561. randomDirection() {
  4562. // https://mathworld.wolfram.com/SpherePointPicking.html
  4563. const theta = Math.random() * Math.PI * 2;
  4564. const u = Math.random() * 2 - 1;
  4565. const c = Math.sqrt( 1 - u * u );
  4566. this.x = c * Math.cos( theta );
  4567. this.y = u;
  4568. this.z = c * Math.sin( theta );
  4569. return this;
  4570. }
  4571. *[ Symbol.iterator ]() {
  4572. yield this.x;
  4573. yield this.y;
  4574. yield this.z;
  4575. }
  4576. }
  4577. const _vector$c = /*@__PURE__*/ new Vector3();
  4578. const _quaternion$4 = /*@__PURE__*/ new Quaternion();
  4579. /**
  4580. * Represents a 3x3 matrix.
  4581. *
  4582. * A Note on Row-Major and Column-Major Ordering:
  4583. *
  4584. * The constructor and {@link Matrix3#set} method take arguments in
  4585. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  4586. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  4587. * This means that calling:
  4588. * ```js
  4589. * const m = new THREE.Matrix();
  4590. * m.set( 11, 12, 13,
  4591. * 21, 22, 23,
  4592. * 31, 32, 33 );
  4593. * ```
  4594. * will result in the elements array containing:
  4595. * ```js
  4596. * m.elements = [ 11, 21, 31,
  4597. * 12, 22, 32,
  4598. * 13, 23, 33 ];
  4599. * ```
  4600. * and internally all calculations are performed using column-major ordering.
  4601. * However, as the actual ordering makes no difference mathematically and
  4602. * most people are used to thinking about matrices in row-major order, the
  4603. * three.js documentation shows matrices in row-major order. Just bear in
  4604. * mind that if you are reading the source code, you'll have to take the
  4605. * transpose of any matrices outlined here to make sense of the calculations.
  4606. */
  4607. class Matrix3 {
  4608. /**
  4609. * Constructs a new 3x3 matrix. The arguments are supposed to be
  4610. * in row-major order. If no arguments are provided, the constructor
  4611. * initializes the matrix as an identity matrix.
  4612. *
  4613. * @param {number} [n11] - 1-1 matrix element.
  4614. * @param {number} [n12] - 1-2 matrix element.
  4615. * @param {number} [n13] - 1-3 matrix element.
  4616. * @param {number} [n21] - 2-1 matrix element.
  4617. * @param {number} [n22] - 2-2 matrix element.
  4618. * @param {number} [n23] - 2-3 matrix element.
  4619. * @param {number} [n31] - 3-1 matrix element.
  4620. * @param {number} [n32] - 3-2 matrix element.
  4621. * @param {number} [n33] - 3-3 matrix element.
  4622. */
  4623. constructor( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4624. /**
  4625. * This flag can be used for type testing.
  4626. *
  4627. * @type {boolean}
  4628. * @readonly
  4629. * @default true
  4630. */
  4631. Matrix3.prototype.isMatrix3 = true;
  4632. /**
  4633. * A column-major list of matrix values.
  4634. *
  4635. * @type {Array<number>}
  4636. */
  4637. this.elements = [
  4638. 1, 0, 0,
  4639. 0, 1, 0,
  4640. 0, 0, 1
  4641. ];
  4642. if ( n11 !== undefined ) {
  4643. this.set( n11, n12, n13, n21, n22, n23, n31, n32, n33 );
  4644. }
  4645. }
  4646. /**
  4647. * Sets the elements of the matrix.The arguments are supposed to be
  4648. * in row-major order.
  4649. *
  4650. * @param {number} [n11] - 1-1 matrix element.
  4651. * @param {number} [n12] - 1-2 matrix element.
  4652. * @param {number} [n13] - 1-3 matrix element.
  4653. * @param {number} [n21] - 2-1 matrix element.
  4654. * @param {number} [n22] - 2-2 matrix element.
  4655. * @param {number} [n23] - 2-3 matrix element.
  4656. * @param {number} [n31] - 3-1 matrix element.
  4657. * @param {number} [n32] - 3-2 matrix element.
  4658. * @param {number} [n33] - 3-3 matrix element.
  4659. * @return {Matrix3} A reference to this matrix.
  4660. */
  4661. set( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  4662. const te = this.elements;
  4663. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  4664. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  4665. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  4666. return this;
  4667. }
  4668. /**
  4669. * Sets this matrix to the 3x3 identity matrix.
  4670. *
  4671. * @return {Matrix3} A reference to this matrix.
  4672. */
  4673. identity() {
  4674. this.set(
  4675. 1, 0, 0,
  4676. 0, 1, 0,
  4677. 0, 0, 1
  4678. );
  4679. return this;
  4680. }
  4681. /**
  4682. * Copies the values of the given matrix to this instance.
  4683. *
  4684. * @param {Matrix3} m - The matrix to copy.
  4685. * @return {Matrix3} A reference to this matrix.
  4686. */
  4687. copy( m ) {
  4688. const te = this.elements;
  4689. const me = m.elements;
  4690. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  4691. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  4692. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  4693. return this;
  4694. }
  4695. /**
  4696. * Extracts the basis of this matrix into the three axis vectors provided.
  4697. *
  4698. * @param {Vector3} xAxis - The basis's x axis.
  4699. * @param {Vector3} yAxis - The basis's y axis.
  4700. * @param {Vector3} zAxis - The basis's z axis.
  4701. * @return {Matrix3} A reference to this matrix.
  4702. */
  4703. extractBasis( xAxis, yAxis, zAxis ) {
  4704. xAxis.setFromMatrix3Column( this, 0 );
  4705. yAxis.setFromMatrix3Column( this, 1 );
  4706. zAxis.setFromMatrix3Column( this, 2 );
  4707. return this;
  4708. }
  4709. /**
  4710. * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix.
  4711. *
  4712. * @param {Matrix4} m - The 4x4 matrix.
  4713. * @return {Matrix3} A reference to this matrix.
  4714. */
  4715. setFromMatrix4( m ) {
  4716. const me = m.elements;
  4717. this.set(
  4718. me[ 0 ], me[ 4 ], me[ 8 ],
  4719. me[ 1 ], me[ 5 ], me[ 9 ],
  4720. me[ 2 ], me[ 6 ], me[ 10 ]
  4721. );
  4722. return this;
  4723. }
  4724. /**
  4725. * Post-multiplies this matrix by the given 3x3 matrix.
  4726. *
  4727. * @param {Matrix3} m - The matrix to multiply with.
  4728. * @return {Matrix3} A reference to this matrix.
  4729. */
  4730. multiply( m ) {
  4731. return this.multiplyMatrices( this, m );
  4732. }
  4733. /**
  4734. * Pre-multiplies this matrix by the given 3x3 matrix.
  4735. *
  4736. * @param {Matrix3} m - The matrix to multiply with.
  4737. * @return {Matrix3} A reference to this matrix.
  4738. */
  4739. premultiply( m ) {
  4740. return this.multiplyMatrices( m, this );
  4741. }
  4742. /**
  4743. * Multiples the given 3x3 matrices and stores the result
  4744. * in this matrix.
  4745. *
  4746. * @param {Matrix3} a - The first matrix.
  4747. * @param {Matrix3} b - The second matrix.
  4748. * @return {Matrix3} A reference to this matrix.
  4749. */
  4750. multiplyMatrices( a, b ) {
  4751. const ae = a.elements;
  4752. const be = b.elements;
  4753. const te = this.elements;
  4754. const a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  4755. const a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  4756. const a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  4757. const b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  4758. const b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  4759. const b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  4760. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  4761. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  4762. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  4763. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  4764. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  4765. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  4766. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  4767. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  4768. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  4769. return this;
  4770. }
  4771. /**
  4772. * Multiplies every component of the matrix by the given scalar.
  4773. *
  4774. * @param {number} s - The scalar.
  4775. * @return {Matrix3} A reference to this matrix.
  4776. */
  4777. multiplyScalar( s ) {
  4778. const te = this.elements;
  4779. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  4780. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  4781. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  4782. return this;
  4783. }
  4784. /**
  4785. * Computes and returns the determinant of this matrix.
  4786. *
  4787. * @return {number} The determinant.
  4788. */
  4789. determinant() {
  4790. const te = this.elements;
  4791. const a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  4792. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  4793. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  4794. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  4795. }
  4796. /**
  4797. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  4798. * You can not invert with a determinant of zero. If you attempt this, the method produces
  4799. * a zero matrix instead.
  4800. *
  4801. * @return {Matrix3} A reference to this matrix.
  4802. */
  4803. invert() {
  4804. const te = this.elements,
  4805. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ],
  4806. n12 = te[ 3 ], n22 = te[ 4 ], n32 = te[ 5 ],
  4807. n13 = te[ 6 ], n23 = te[ 7 ], n33 = te[ 8 ],
  4808. t11 = n33 * n22 - n32 * n23,
  4809. t12 = n32 * n13 - n33 * n12,
  4810. t13 = n23 * n12 - n22 * n13,
  4811. det = n11 * t11 + n21 * t12 + n31 * t13;
  4812. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  4813. const detInv = 1 / det;
  4814. te[ 0 ] = t11 * detInv;
  4815. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  4816. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  4817. te[ 3 ] = t12 * detInv;
  4818. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  4819. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  4820. te[ 6 ] = t13 * detInv;
  4821. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  4822. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  4823. return this;
  4824. }
  4825. /**
  4826. * Transposes this matrix in place.
  4827. *
  4828. * @return {Matrix3} A reference to this matrix.
  4829. */
  4830. transpose() {
  4831. let tmp;
  4832. const m = this.elements;
  4833. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  4834. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  4835. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  4836. return this;
  4837. }
  4838. /**
  4839. * Computes the normal matrix which is the inverse transpose of the upper
  4840. * left 3x3 portion of the given 4x4 matrix.
  4841. *
  4842. * @param {Matrix4} matrix4 - The 4x4 matrix.
  4843. * @return {Matrix3} A reference to this matrix.
  4844. */
  4845. getNormalMatrix( matrix4 ) {
  4846. return this.setFromMatrix4( matrix4 ).invert().transpose();
  4847. }
  4848. /**
  4849. * Transposes this matrix into the supplied array, and returns itself unchanged.
  4850. *
  4851. * @param {Array<number>} r - An array to store the transposed matrix elements.
  4852. * @return {Matrix3} A reference to this matrix.
  4853. */
  4854. transposeIntoArray( r ) {
  4855. const m = this.elements;
  4856. r[ 0 ] = m[ 0 ];
  4857. r[ 1 ] = m[ 3 ];
  4858. r[ 2 ] = m[ 6 ];
  4859. r[ 3 ] = m[ 1 ];
  4860. r[ 4 ] = m[ 4 ];
  4861. r[ 5 ] = m[ 7 ];
  4862. r[ 6 ] = m[ 2 ];
  4863. r[ 7 ] = m[ 5 ];
  4864. r[ 8 ] = m[ 8 ];
  4865. return this;
  4866. }
  4867. /**
  4868. * Sets the UV transform matrix from offset, repeat, rotation, and center.
  4869. *
  4870. * @param {number} tx - Offset x.
  4871. * @param {number} ty - Offset y.
  4872. * @param {number} sx - Repeat x.
  4873. * @param {number} sy - Repeat y.
  4874. * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise.
  4875. * @param {number} cx - Center x of rotation.
  4876. * @param {number} cy - Center y of rotation
  4877. * @return {Matrix3} A reference to this matrix.
  4878. */
  4879. setUvTransform( tx, ty, sx, sy, rotation, cx, cy ) {
  4880. const c = Math.cos( rotation );
  4881. const s = Math.sin( rotation );
  4882. this.set(
  4883. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  4884. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  4885. 0, 0, 1
  4886. );
  4887. return this;
  4888. }
  4889. /**
  4890. * Scales this matrix with the given scalar values.
  4891. *
  4892. * @param {number} sx - The amount to scale in the X axis.
  4893. * @param {number} sy - The amount to scale in the Y axis.
  4894. * @return {Matrix3} A reference to this matrix.
  4895. */
  4896. scale( sx, sy ) {
  4897. this.premultiply( _m3.makeScale( sx, sy ) );
  4898. return this;
  4899. }
  4900. /**
  4901. * Rotates this matrix by the given angle.
  4902. *
  4903. * @param {number} theta - The rotation in radians.
  4904. * @return {Matrix3} A reference to this matrix.
  4905. */
  4906. rotate( theta ) {
  4907. this.premultiply( _m3.makeRotation( - theta ) );
  4908. return this;
  4909. }
  4910. /**
  4911. * Translates this matrix by the given scalar values.
  4912. *
  4913. * @param {number} tx - The amount to translate in the X axis.
  4914. * @param {number} ty - The amount to translate in the Y axis.
  4915. * @return {Matrix3} A reference to this matrix.
  4916. */
  4917. translate( tx, ty ) {
  4918. this.premultiply( _m3.makeTranslation( tx, ty ) );
  4919. return this;
  4920. }
  4921. // for 2D Transforms
  4922. /**
  4923. * Sets this matrix as a 2D translation transform.
  4924. *
  4925. * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector.
  4926. * @param {number} y - The amount to translate in the Y axis.
  4927. * @return {Matrix3} A reference to this matrix.
  4928. */
  4929. makeTranslation( x, y ) {
  4930. if ( x.isVector2 ) {
  4931. this.set(
  4932. 1, 0, x.x,
  4933. 0, 1, x.y,
  4934. 0, 0, 1
  4935. );
  4936. } else {
  4937. this.set(
  4938. 1, 0, x,
  4939. 0, 1, y,
  4940. 0, 0, 1
  4941. );
  4942. }
  4943. return this;
  4944. }
  4945. /**
  4946. * Sets this matrix as a 2D rotational transformation.
  4947. *
  4948. * @param {number} theta - The rotation in radians.
  4949. * @return {Matrix3} A reference to this matrix.
  4950. */
  4951. makeRotation( theta ) {
  4952. // counterclockwise
  4953. const c = Math.cos( theta );
  4954. const s = Math.sin( theta );
  4955. this.set(
  4956. c, - s, 0,
  4957. s, c, 0,
  4958. 0, 0, 1
  4959. );
  4960. return this;
  4961. }
  4962. /**
  4963. * Sets this matrix as a 2D scale transform.
  4964. *
  4965. * @param {number} x - The amount to scale in the X axis.
  4966. * @param {number} y - The amount to scale in the Y axis.
  4967. * @return {Matrix3} A reference to this matrix.
  4968. */
  4969. makeScale( x, y ) {
  4970. this.set(
  4971. x, 0, 0,
  4972. 0, y, 0,
  4973. 0, 0, 1
  4974. );
  4975. return this;
  4976. }
  4977. /**
  4978. * Returns `true` if this matrix is equal with the given one.
  4979. *
  4980. * @param {Matrix3} matrix - The matrix to test for equality.
  4981. * @return {boolean} Whether this matrix is equal with the given one.
  4982. */
  4983. equals( matrix ) {
  4984. const te = this.elements;
  4985. const me = matrix.elements;
  4986. for ( let i = 0; i < 9; i ++ ) {
  4987. if ( te[ i ] !== me[ i ] ) return false;
  4988. }
  4989. return true;
  4990. }
  4991. /**
  4992. * Sets the elements of the matrix from the given array.
  4993. *
  4994. * @param {Array<number>} array - The matrix elements in column-major order.
  4995. * @param {number} [offset=0] - Index of the first element in the array.
  4996. * @return {Matrix3} A reference to this matrix.
  4997. */
  4998. fromArray( array, offset = 0 ) {
  4999. for ( let i = 0; i < 9; i ++ ) {
  5000. this.elements[ i ] = array[ i + offset ];
  5001. }
  5002. return this;
  5003. }
  5004. /**
  5005. * Writes the elements of this matrix to the given array. If no array is provided,
  5006. * the method returns a new instance.
  5007. *
  5008. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  5009. * @param {number} [offset=0] - Index of the first element in the array.
  5010. * @return {Array<number>} The matrix elements in column-major order.
  5011. */
  5012. toArray( array = [], offset = 0 ) {
  5013. const te = this.elements;
  5014. array[ offset ] = te[ 0 ];
  5015. array[ offset + 1 ] = te[ 1 ];
  5016. array[ offset + 2 ] = te[ 2 ];
  5017. array[ offset + 3 ] = te[ 3 ];
  5018. array[ offset + 4 ] = te[ 4 ];
  5019. array[ offset + 5 ] = te[ 5 ];
  5020. array[ offset + 6 ] = te[ 6 ];
  5021. array[ offset + 7 ] = te[ 7 ];
  5022. array[ offset + 8 ] = te[ 8 ];
  5023. return array;
  5024. }
  5025. /**
  5026. * Returns a matrix with copied values from this instance.
  5027. *
  5028. * @return {Matrix3} A clone of this instance.
  5029. */
  5030. clone() {
  5031. return new this.constructor().fromArray( this.elements );
  5032. }
  5033. }
  5034. const _m3 = /*@__PURE__*/ new Matrix3();
  5035. const LINEAR_REC709_TO_XYZ = /*@__PURE__*/ new Matrix3().set(
  5036. 0.4123908, 0.3575843, 0.1804808,
  5037. 0.2126390, 0.7151687, 0.0721923,
  5038. 0.0193308, 0.1191948, 0.9505322
  5039. );
  5040. const XYZ_TO_LINEAR_REC709 = /*@__PURE__*/ new Matrix3().set(
  5041. 3.2409699, -1.5373832, -0.4986108,
  5042. -0.9692436, 1.8759675, 0.0415551,
  5043. 0.0556301, -0.203977, 1.0569715
  5044. );
  5045. function createColorManagement() {
  5046. const ColorManagement = {
  5047. enabled: true,
  5048. workingColorSpace: LinearSRGBColorSpace,
  5049. /**
  5050. * Implementations of supported color spaces.
  5051. *
  5052. * Required:
  5053. * - primaries: chromaticity coordinates [ rx ry gx gy bx by ]
  5054. * - whitePoint: reference white [ x y ]
  5055. * - transfer: transfer function (pre-defined)
  5056. * - toXYZ: Matrix3 RGB to XYZ transform
  5057. * - fromXYZ: Matrix3 XYZ to RGB transform
  5058. * - luminanceCoefficients: RGB luminance coefficients
  5059. *
  5060. * Optional:
  5061. * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' }
  5062. * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace }
  5063. *
  5064. * Reference:
  5065. * - https://www.russellcottrell.com/photo/matrixCalculator.htm
  5066. */
  5067. spaces: {},
  5068. convert: function ( color, sourceColorSpace, targetColorSpace ) {
  5069. if ( this.enabled === false || sourceColorSpace === targetColorSpace || ! sourceColorSpace || ! targetColorSpace ) {
  5070. return color;
  5071. }
  5072. if ( this.spaces[ sourceColorSpace ].transfer === SRGBTransfer ) {
  5073. color.r = SRGBToLinear( color.r );
  5074. color.g = SRGBToLinear( color.g );
  5075. color.b = SRGBToLinear( color.b );
  5076. }
  5077. if ( this.spaces[ sourceColorSpace ].primaries !== this.spaces[ targetColorSpace ].primaries ) {
  5078. color.applyMatrix3( this.spaces[ sourceColorSpace ].toXYZ );
  5079. color.applyMatrix3( this.spaces[ targetColorSpace ].fromXYZ );
  5080. }
  5081. if ( this.spaces[ targetColorSpace ].transfer === SRGBTransfer ) {
  5082. color.r = LinearToSRGB( color.r );
  5083. color.g = LinearToSRGB( color.g );
  5084. color.b = LinearToSRGB( color.b );
  5085. }
  5086. return color;
  5087. },
  5088. workingToColorSpace: function ( color, targetColorSpace ) {
  5089. return this.convert( color, this.workingColorSpace, targetColorSpace );
  5090. },
  5091. colorSpaceToWorking: function ( color, sourceColorSpace ) {
  5092. return this.convert( color, sourceColorSpace, this.workingColorSpace );
  5093. },
  5094. getPrimaries: function ( colorSpace ) {
  5095. return this.spaces[ colorSpace ].primaries;
  5096. },
  5097. getTransfer: function ( colorSpace ) {
  5098. if ( colorSpace === NoColorSpace ) return LinearTransfer;
  5099. return this.spaces[ colorSpace ].transfer;
  5100. },
  5101. getToneMappingMode: function ( colorSpace ) {
  5102. return this.spaces[ colorSpace ].outputColorSpaceConfig.toneMappingMode || 'standard';
  5103. },
  5104. getLuminanceCoefficients: function ( target, colorSpace = this.workingColorSpace ) {
  5105. return target.fromArray( this.spaces[ colorSpace ].luminanceCoefficients );
  5106. },
  5107. define: function ( colorSpaces ) {
  5108. Object.assign( this.spaces, colorSpaces );
  5109. },
  5110. // Internal APIs
  5111. _getMatrix: function ( targetMatrix, sourceColorSpace, targetColorSpace ) {
  5112. return targetMatrix
  5113. .copy( this.spaces[ sourceColorSpace ].toXYZ )
  5114. .multiply( this.spaces[ targetColorSpace ].fromXYZ );
  5115. },
  5116. _getDrawingBufferColorSpace: function ( colorSpace ) {
  5117. return this.spaces[ colorSpace ].outputColorSpaceConfig.drawingBufferColorSpace;
  5118. },
  5119. _getUnpackColorSpace: function ( colorSpace = this.workingColorSpace ) {
  5120. return this.spaces[ colorSpace ].workingColorSpaceConfig.unpackColorSpace;
  5121. },
  5122. // Deprecated
  5123. fromWorkingColorSpace: function ( color, targetColorSpace ) {
  5124. warnOnce( 'ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().' ); // @deprecated, r177
  5125. return ColorManagement.workingToColorSpace( color, targetColorSpace );
  5126. },
  5127. toWorkingColorSpace: function ( color, sourceColorSpace ) {
  5128. warnOnce( 'ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().' ); // @deprecated, r177
  5129. return ColorManagement.colorSpaceToWorking( color, sourceColorSpace );
  5130. },
  5131. };
  5132. /******************************************************************************
  5133. * sRGB definitions
  5134. */
  5135. const REC709_PRIMARIES = [ 0.640, 0.330, 0.300, 0.600, 0.150, 0.060 ];
  5136. const REC709_LUMINANCE_COEFFICIENTS = [ 0.2126, 0.7152, 0.0722 ];
  5137. const D65 = [ 0.3127, 0.3290 ];
  5138. ColorManagement.define( {
  5139. [ LinearSRGBColorSpace ]: {
  5140. primaries: REC709_PRIMARIES,
  5141. whitePoint: D65,
  5142. transfer: LinearTransfer,
  5143. toXYZ: LINEAR_REC709_TO_XYZ,
  5144. fromXYZ: XYZ_TO_LINEAR_REC709,
  5145. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5146. workingColorSpaceConfig: { unpackColorSpace: SRGBColorSpace },
  5147. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5148. },
  5149. [ SRGBColorSpace ]: {
  5150. primaries: REC709_PRIMARIES,
  5151. whitePoint: D65,
  5152. transfer: SRGBTransfer,
  5153. toXYZ: LINEAR_REC709_TO_XYZ,
  5154. fromXYZ: XYZ_TO_LINEAR_REC709,
  5155. luminanceCoefficients: REC709_LUMINANCE_COEFFICIENTS,
  5156. outputColorSpaceConfig: { drawingBufferColorSpace: SRGBColorSpace }
  5157. },
  5158. } );
  5159. return ColorManagement;
  5160. }
  5161. const ColorManagement = /*@__PURE__*/ createColorManagement();
  5162. function SRGBToLinear( c ) {
  5163. return ( c < 0.04045 ) ? c * 0.0773993808 : Math.pow( c * 0.9478672986 + 0.0521327014, 2.4 );
  5164. }
  5165. function LinearToSRGB( c ) {
  5166. return ( c < 0.0031308 ) ? c * 12.92 : 1.055 * ( Math.pow( c, 0.41666 ) ) - 0.055;
  5167. }
  5168. let _canvas;
  5169. /**
  5170. * A class containing utility functions for images.
  5171. *
  5172. * @hideconstructor
  5173. */
  5174. class ImageUtils {
  5175. /**
  5176. * Returns a data URI containing a representation of the given image.
  5177. *
  5178. * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object.
  5179. * @param {string} [type='image/png'] - Indicates the image format.
  5180. * @return {string} The data URI.
  5181. */
  5182. static getDataURL( image, type = 'image/png' ) {
  5183. if ( /^data:/i.test( image.src ) ) {
  5184. return image.src;
  5185. }
  5186. if ( typeof HTMLCanvasElement === 'undefined' ) {
  5187. return image.src;
  5188. }
  5189. let canvas;
  5190. if ( image instanceof HTMLCanvasElement ) {
  5191. canvas = image;
  5192. } else {
  5193. if ( _canvas === undefined ) _canvas = createElementNS( 'canvas' );
  5194. _canvas.width = image.width;
  5195. _canvas.height = image.height;
  5196. const context = _canvas.getContext( '2d' );
  5197. if ( image instanceof ImageData ) {
  5198. context.putImageData( image, 0, 0 );
  5199. } else {
  5200. context.drawImage( image, 0, 0, image.width, image.height );
  5201. }
  5202. canvas = _canvas;
  5203. }
  5204. return canvas.toDataURL( type );
  5205. }
  5206. /**
  5207. * Converts the given sRGB image data to linear color space.
  5208. *
  5209. * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object.
  5210. * @return {HTMLCanvasElement|Object} The converted image.
  5211. */
  5212. static sRGBToLinear( image ) {
  5213. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5214. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5215. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5216. const canvas = createElementNS( 'canvas' );
  5217. canvas.width = image.width;
  5218. canvas.height = image.height;
  5219. const context = canvas.getContext( '2d' );
  5220. context.drawImage( image, 0, 0, image.width, image.height );
  5221. const imageData = context.getImageData( 0, 0, image.width, image.height );
  5222. const data = imageData.data;
  5223. for ( let i = 0; i < data.length; i ++ ) {
  5224. data[ i ] = SRGBToLinear( data[ i ] / 255 ) * 255;
  5225. }
  5226. context.putImageData( imageData, 0, 0 );
  5227. return canvas;
  5228. } else if ( image.data ) {
  5229. const data = image.data.slice( 0 );
  5230. for ( let i = 0; i < data.length; i ++ ) {
  5231. if ( data instanceof Uint8Array || data instanceof Uint8ClampedArray ) {
  5232. data[ i ] = Math.floor( SRGBToLinear( data[ i ] / 255 ) * 255 );
  5233. } else {
  5234. // assuming float
  5235. data[ i ] = SRGBToLinear( data[ i ] );
  5236. }
  5237. }
  5238. return {
  5239. data: data,
  5240. width: image.width,
  5241. height: image.height
  5242. };
  5243. } else {
  5244. warn( 'ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied.' );
  5245. return image;
  5246. }
  5247. }
  5248. }
  5249. let _sourceId = 0;
  5250. /**
  5251. * Represents the data source of a texture.
  5252. *
  5253. * The main purpose of this class is to decouple the data definition from the texture
  5254. * definition so the same data can be used with multiple texture instances.
  5255. */
  5256. class Source {
  5257. /**
  5258. * Constructs a new video texture.
  5259. *
  5260. * @param {any} [data=null] - The data definition of a texture.
  5261. */
  5262. constructor( data = null ) {
  5263. /**
  5264. * This flag can be used for type testing.
  5265. *
  5266. * @type {boolean}
  5267. * @readonly
  5268. * @default true
  5269. */
  5270. this.isSource = true;
  5271. /**
  5272. * The ID of the source.
  5273. *
  5274. * @name Source#id
  5275. * @type {number}
  5276. * @readonly
  5277. */
  5278. Object.defineProperty( this, 'id', { value: _sourceId ++ } );
  5279. /**
  5280. * The UUID of the source.
  5281. *
  5282. * @type {string}
  5283. * @readonly
  5284. */
  5285. this.uuid = generateUUID();
  5286. /**
  5287. * The data definition of a texture.
  5288. *
  5289. * @type {any}
  5290. */
  5291. this.data = data;
  5292. /**
  5293. * This property is only relevant when {@link Source#needsUpdate} is set to `true` and
  5294. * provides more control on how texture data should be processed. When `dataReady` is set
  5295. * to `false`, the engine performs the memory allocation (if necessary) but does not transfer
  5296. * the data into the GPU memory.
  5297. *
  5298. * @type {boolean}
  5299. * @default true
  5300. */
  5301. this.dataReady = true;
  5302. /**
  5303. * This starts at `0` and counts how many times {@link Source#needsUpdate} is set to `true`.
  5304. *
  5305. * @type {number}
  5306. * @readonly
  5307. * @default 0
  5308. */
  5309. this.version = 0;
  5310. }
  5311. /**
  5312. * Returns the dimensions of the source into the given target vector.
  5313. *
  5314. * @param {(Vector2|Vector3)} target - The target object the result is written into.
  5315. * @return {(Vector2|Vector3)} The dimensions of the source.
  5316. */
  5317. getSize( target ) {
  5318. const data = this.data;
  5319. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( data instanceof HTMLVideoElement ) ) {
  5320. target.set( data.videoWidth, data.videoHeight, 0 );
  5321. } else if ( ( typeof VideoFrame !== 'undefined' ) && ( data instanceof VideoFrame ) ) {
  5322. target.set( data.displayHeight, data.displayWidth, 0 );
  5323. } else if ( data !== null ) {
  5324. target.set( data.width, data.height, data.depth || 0 );
  5325. } else {
  5326. target.set( 0, 0, 0 );
  5327. }
  5328. return target;
  5329. }
  5330. /**
  5331. * When the property is set to `true`, the engine allocates the memory
  5332. * for the texture (if necessary) and triggers the actual texture upload
  5333. * to the GPU next time the source is used.
  5334. *
  5335. * @type {boolean}
  5336. * @default false
  5337. * @param {boolean} value
  5338. */
  5339. set needsUpdate( value ) {
  5340. if ( value === true ) this.version ++;
  5341. }
  5342. /**
  5343. * Serializes the source into JSON.
  5344. *
  5345. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5346. * @return {Object} A JSON object representing the serialized source.
  5347. * @see {@link ObjectLoader#parse}
  5348. */
  5349. toJSON( meta ) {
  5350. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5351. if ( ! isRootObject && meta.images[ this.uuid ] !== undefined ) {
  5352. return meta.images[ this.uuid ];
  5353. }
  5354. const output = {
  5355. uuid: this.uuid,
  5356. url: ''
  5357. };
  5358. const data = this.data;
  5359. if ( data !== null ) {
  5360. let url;
  5361. if ( Array.isArray( data ) ) {
  5362. // cube texture
  5363. url = [];
  5364. for ( let i = 0, l = data.length; i < l; i ++ ) {
  5365. if ( data[ i ].isDataTexture ) {
  5366. url.push( serializeImage( data[ i ].image ) );
  5367. } else {
  5368. url.push( serializeImage( data[ i ] ) );
  5369. }
  5370. }
  5371. } else {
  5372. // texture
  5373. url = serializeImage( data );
  5374. }
  5375. output.url = url;
  5376. }
  5377. if ( ! isRootObject ) {
  5378. meta.images[ this.uuid ] = output;
  5379. }
  5380. return output;
  5381. }
  5382. }
  5383. function serializeImage( image ) {
  5384. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  5385. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  5386. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ) {
  5387. // default images
  5388. return ImageUtils.getDataURL( image );
  5389. } else {
  5390. if ( image.data ) {
  5391. // images of DataTexture
  5392. return {
  5393. data: Array.from( image.data ),
  5394. width: image.width,
  5395. height: image.height,
  5396. type: image.data.constructor.name
  5397. };
  5398. } else {
  5399. warn( 'Texture: Unable to serialize Texture.' );
  5400. return {};
  5401. }
  5402. }
  5403. }
  5404. let _textureId = 0;
  5405. const _tempVec3 = /*@__PURE__*/ new Vector3();
  5406. /**
  5407. * Base class for all textures.
  5408. *
  5409. * Note: After the initial use of a texture, its dimensions, format, and type
  5410. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  5411. *
  5412. * @augments EventDispatcher
  5413. */
  5414. class Texture extends EventDispatcher {
  5415. /**
  5416. * Constructs a new texture.
  5417. *
  5418. * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data.
  5419. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  5420. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  5421. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  5422. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  5423. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  5424. * @param {number} [format=RGBAFormat] - The texture format.
  5425. * @param {number} [type=UnsignedByteType] - The texture type.
  5426. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  5427. * @param {string} [colorSpace=NoColorSpace] - The color space.
  5428. */
  5429. 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 ) {
  5430. super();
  5431. /**
  5432. * This flag can be used for type testing.
  5433. *
  5434. * @type {boolean}
  5435. * @readonly
  5436. * @default true
  5437. */
  5438. this.isTexture = true;
  5439. /**
  5440. * The ID of the texture.
  5441. *
  5442. * @name Texture#id
  5443. * @type {number}
  5444. * @readonly
  5445. */
  5446. Object.defineProperty( this, 'id', { value: _textureId ++ } );
  5447. /**
  5448. * The UUID of the material.
  5449. *
  5450. * @type {string}
  5451. * @readonly
  5452. */
  5453. this.uuid = generateUUID();
  5454. /**
  5455. * The name of the material.
  5456. *
  5457. * @type {string}
  5458. */
  5459. this.name = '';
  5460. /**
  5461. * The data definition of a texture. A reference to the data source can be
  5462. * shared across textures. This is often useful in context of spritesheets
  5463. * where multiple textures render the same data but with different texture
  5464. * transformations.
  5465. *
  5466. * @type {Source}
  5467. */
  5468. this.source = new Source( image );
  5469. /**
  5470. * An array holding user-defined mipmaps.
  5471. *
  5472. * @type {Array<Object>}
  5473. */
  5474. this.mipmaps = [];
  5475. /**
  5476. * How the texture is applied to the object. The value `UVMapping`
  5477. * is the default, where texture or uv coordinates are used to apply the map.
  5478. *
  5479. * @type {(UVMapping|CubeReflectionMapping|CubeRefractionMapping|EquirectangularReflectionMapping|EquirectangularRefractionMapping|CubeUVReflectionMapping)}
  5480. * @default UVMapping
  5481. */
  5482. this.mapping = mapping;
  5483. /**
  5484. * Lets you select the uv attribute to map the texture to. `0` for `uv`,
  5485. * `1` for `uv1`, `2` for `uv2` and `3` for `uv3`.
  5486. *
  5487. * @type {number}
  5488. * @default 0
  5489. */
  5490. this.channel = 0;
  5491. /**
  5492. * This defines how the texture is wrapped horizontally and corresponds to
  5493. * *U* in UV mapping.
  5494. *
  5495. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5496. * @default ClampToEdgeWrapping
  5497. */
  5498. this.wrapS = wrapS;
  5499. /**
  5500. * This defines how the texture is wrapped horizontally and corresponds to
  5501. * *V* in UV mapping.
  5502. *
  5503. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  5504. * @default ClampToEdgeWrapping
  5505. */
  5506. this.wrapT = wrapT;
  5507. /**
  5508. * How the texture is sampled when a texel covers more than one pixel.
  5509. *
  5510. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5511. * @default LinearFilter
  5512. */
  5513. this.magFilter = magFilter;
  5514. /**
  5515. * How the texture is sampled when a texel covers less than one pixel.
  5516. *
  5517. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  5518. * @default LinearMipmapLinearFilter
  5519. */
  5520. this.minFilter = minFilter;
  5521. /**
  5522. * The number of samples taken along the axis through the pixel that has the
  5523. * highest density of texels. By default, this value is `1`. A higher value
  5524. * gives a less blurry result than a basic mipmap, at the cost of more
  5525. * texture samples being used.
  5526. *
  5527. * @type {number}
  5528. * @default 0
  5529. */
  5530. this.anisotropy = anisotropy;
  5531. /**
  5532. * The format of the texture.
  5533. *
  5534. * @type {number}
  5535. * @default RGBAFormat
  5536. */
  5537. this.format = format;
  5538. /**
  5539. * The default internal format is derived from {@link Texture#format} and {@link Texture#type} and
  5540. * defines how the texture data is going to be stored on the GPU.
  5541. *
  5542. * This property allows to overwrite the default format.
  5543. *
  5544. * @type {?string}
  5545. * @default null
  5546. */
  5547. this.internalFormat = null;
  5548. /**
  5549. * The data type of the texture.
  5550. *
  5551. * @type {number}
  5552. * @default UnsignedByteType
  5553. */
  5554. this.type = type;
  5555. /**
  5556. * How much a single repetition of the texture is offset from the beginning,
  5557. * in each direction U and V. Typical range is `0.0` to `1.0`.
  5558. *
  5559. * @type {Vector2}
  5560. * @default (0,0)
  5561. */
  5562. this.offset = new Vector2( 0, 0 );
  5563. /**
  5564. * How many times the texture is repeated across the surface, in each
  5565. * direction U and V. If repeat is set greater than `1` in either direction,
  5566. * the corresponding wrap parameter should also be set to `RepeatWrapping`
  5567. * or `MirroredRepeatWrapping` to achieve the desired tiling effect.
  5568. *
  5569. * @type {Vector2}
  5570. * @default (1,1)
  5571. */
  5572. this.repeat = new Vector2( 1, 1 );
  5573. /**
  5574. * The point around which rotation occurs. A value of `(0.5, 0.5)` corresponds
  5575. * to the center of the texture. Default is `(0, 0)`, the lower left.
  5576. *
  5577. * @type {Vector2}
  5578. * @default (0,0)
  5579. */
  5580. this.center = new Vector2( 0, 0 );
  5581. /**
  5582. * How much the texture is rotated around the center point, in radians.
  5583. * Positive values are counter-clockwise.
  5584. *
  5585. * @type {number}
  5586. * @default 0
  5587. */
  5588. this.rotation = 0;
  5589. /**
  5590. * Whether to update the texture's uv-transformation {@link Texture#matrix}
  5591. * from the properties {@link Texture#offset}, {@link Texture#repeat},
  5592. * {@link Texture#rotation}, and {@link Texture#center}.
  5593. *
  5594. * Set this to `false` if you are specifying the uv-transform matrix directly.
  5595. *
  5596. * @type {boolean}
  5597. * @default true
  5598. */
  5599. this.matrixAutoUpdate = true;
  5600. /**
  5601. * The uv-transformation matrix of the texture.
  5602. *
  5603. * @type {Matrix3}
  5604. */
  5605. this.matrix = new Matrix3();
  5606. /**
  5607. * Whether to generate mipmaps (if possible) for a texture.
  5608. *
  5609. * Set this to `false` if you are creating mipmaps manually.
  5610. *
  5611. * @type {boolean}
  5612. * @default true
  5613. */
  5614. this.generateMipmaps = true;
  5615. /**
  5616. * If set to `true`, the alpha channel, if present, is multiplied into the
  5617. * color channels when the texture is uploaded to the GPU.
  5618. *
  5619. * Note that this property has no effect when using `ImageBitmap`. You need to
  5620. * configure premultiply alpha on bitmap creation instead.
  5621. *
  5622. * @type {boolean}
  5623. * @default false
  5624. */
  5625. this.premultiplyAlpha = false;
  5626. /**
  5627. * If set to `true`, the texture is flipped along the vertical axis when
  5628. * uploaded to the GPU.
  5629. *
  5630. * Note that this property has no effect when using `ImageBitmap`. You need to
  5631. * configure the flip on bitmap creation instead.
  5632. *
  5633. * @type {boolean}
  5634. * @default true
  5635. */
  5636. this.flipY = true;
  5637. /**
  5638. * Specifies the alignment requirements for the start of each pixel row in memory.
  5639. * The allowable values are `1` (byte-alignment), `2` (rows aligned to even-numbered bytes),
  5640. * `4` (word-alignment), and `8` (rows start on double-word boundaries).
  5641. *
  5642. * @type {number}
  5643. * @default 4
  5644. */
  5645. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  5646. /**
  5647. * Textures containing color data should be annotated with `SRGBColorSpace` or `LinearSRGBColorSpace`.
  5648. *
  5649. * @type {string}
  5650. * @default NoColorSpace
  5651. */
  5652. this.colorSpace = colorSpace;
  5653. /**
  5654. * An object that can be used to store custom data about the texture. It
  5655. * should not hold references to functions as these will not be cloned.
  5656. *
  5657. * @type {Object}
  5658. */
  5659. this.userData = {};
  5660. /**
  5661. * This can be used to only update a subregion or specific rows of the texture (for example, just the
  5662. * first 3 rows). Use the `addUpdateRange()` function to add ranges to this array.
  5663. *
  5664. * @type {Array<Object>}
  5665. */
  5666. this.updateRanges = [];
  5667. /**
  5668. * This starts at `0` and counts how many times {@link Texture#needsUpdate} is set to `true`.
  5669. *
  5670. * @type {number}
  5671. * @readonly
  5672. * @default 0
  5673. */
  5674. this.version = 0;
  5675. /**
  5676. * A callback function, called when the texture is updated (e.g., when
  5677. * {@link Texture#needsUpdate} has been set to true and then the texture is used).
  5678. *
  5679. * @type {?Function}
  5680. * @default null
  5681. */
  5682. this.onUpdate = null;
  5683. /**
  5684. * An optional back reference to the textures render target.
  5685. *
  5686. * @type {?(RenderTarget|WebGLRenderTarget)}
  5687. * @default null
  5688. */
  5689. this.renderTarget = null;
  5690. /**
  5691. * Indicates whether a texture belongs to a render target or not.
  5692. *
  5693. * @type {boolean}
  5694. * @readonly
  5695. * @default false
  5696. */
  5697. this.isRenderTargetTexture = false;
  5698. /**
  5699. * Indicates if a texture should be handled like a texture array.
  5700. *
  5701. * @type {boolean}
  5702. * @readonly
  5703. * @default false
  5704. */
  5705. this.isArrayTexture = image && image.depth && image.depth > 1 ? true : false;
  5706. /**
  5707. * Indicates whether this texture should be processed by `PMREMGenerator` or not
  5708. * (only relevant for render target textures).
  5709. *
  5710. * @type {number}
  5711. * @readonly
  5712. * @default 0
  5713. */
  5714. this.pmremVersion = 0;
  5715. }
  5716. /**
  5717. * The width of the texture in pixels.
  5718. */
  5719. get width() {
  5720. return this.source.getSize( _tempVec3 ).x;
  5721. }
  5722. /**
  5723. * The height of the texture in pixels.
  5724. */
  5725. get height() {
  5726. return this.source.getSize( _tempVec3 ).y;
  5727. }
  5728. /**
  5729. * The depth of the texture in pixels.
  5730. */
  5731. get depth() {
  5732. return this.source.getSize( _tempVec3 ).z;
  5733. }
  5734. /**
  5735. * The image object holding the texture data.
  5736. *
  5737. * @type {?Object}
  5738. */
  5739. get image() {
  5740. return this.source.data;
  5741. }
  5742. set image( value = null ) {
  5743. this.source.data = value;
  5744. }
  5745. /**
  5746. * Updates the texture transformation matrix from the from the properties {@link Texture#offset},
  5747. * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}.
  5748. */
  5749. updateMatrix() {
  5750. this.matrix.setUvTransform( this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y );
  5751. }
  5752. /**
  5753. * Adds a range of data in the data texture to be updated on the GPU.
  5754. *
  5755. * @param {number} start - Position at which to start update.
  5756. * @param {number} count - The number of components to update.
  5757. */
  5758. addUpdateRange( start, count ) {
  5759. this.updateRanges.push( { start, count } );
  5760. }
  5761. /**
  5762. * Clears the update ranges.
  5763. */
  5764. clearUpdateRanges() {
  5765. this.updateRanges.length = 0;
  5766. }
  5767. /**
  5768. * Returns a new texture with copied values from this instance.
  5769. *
  5770. * @return {Texture} A clone of this instance.
  5771. */
  5772. clone() {
  5773. return new this.constructor().copy( this );
  5774. }
  5775. /**
  5776. * Copies the values of the given texture to this instance.
  5777. *
  5778. * @param {Texture} source - The texture to copy.
  5779. * @return {Texture} A reference to this instance.
  5780. */
  5781. copy( source ) {
  5782. this.name = source.name;
  5783. this.source = source.source;
  5784. this.mipmaps = source.mipmaps.slice( 0 );
  5785. this.mapping = source.mapping;
  5786. this.channel = source.channel;
  5787. this.wrapS = source.wrapS;
  5788. this.wrapT = source.wrapT;
  5789. this.magFilter = source.magFilter;
  5790. this.minFilter = source.minFilter;
  5791. this.anisotropy = source.anisotropy;
  5792. this.format = source.format;
  5793. this.internalFormat = source.internalFormat;
  5794. this.type = source.type;
  5795. this.offset.copy( source.offset );
  5796. this.repeat.copy( source.repeat );
  5797. this.center.copy( source.center );
  5798. this.rotation = source.rotation;
  5799. this.matrixAutoUpdate = source.matrixAutoUpdate;
  5800. this.matrix.copy( source.matrix );
  5801. this.generateMipmaps = source.generateMipmaps;
  5802. this.premultiplyAlpha = source.premultiplyAlpha;
  5803. this.flipY = source.flipY;
  5804. this.unpackAlignment = source.unpackAlignment;
  5805. this.colorSpace = source.colorSpace;
  5806. this.renderTarget = source.renderTarget;
  5807. this.isRenderTargetTexture = source.isRenderTargetTexture;
  5808. this.isArrayTexture = source.isArrayTexture;
  5809. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  5810. this.needsUpdate = true;
  5811. return this;
  5812. }
  5813. /**
  5814. * Sets this texture's properties based on `values`.
  5815. * @param {Object} values - A container with texture parameters.
  5816. */
  5817. setValues( values ) {
  5818. for ( const key in values ) {
  5819. const newValue = values[ key ];
  5820. if ( newValue === undefined ) {
  5821. warn( `Texture.setValues(): parameter '${ key }' has value of undefined.` );
  5822. continue;
  5823. }
  5824. const currentValue = this[ key ];
  5825. if ( currentValue === undefined ) {
  5826. warn( `Texture.setValues(): property '${ key }' does not exist.` );
  5827. continue;
  5828. }
  5829. if ( ( currentValue && newValue ) && ( currentValue.isVector2 && newValue.isVector2 ) ) {
  5830. currentValue.copy( newValue );
  5831. } else if ( ( currentValue && newValue ) && ( currentValue.isVector3 && newValue.isVector3 ) ) {
  5832. currentValue.copy( newValue );
  5833. } else if ( ( currentValue && newValue ) && ( currentValue.isMatrix3 && newValue.isMatrix3 ) ) {
  5834. currentValue.copy( newValue );
  5835. } else {
  5836. this[ key ] = newValue;
  5837. }
  5838. }
  5839. }
  5840. /**
  5841. * Serializes the texture into JSON.
  5842. *
  5843. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  5844. * @return {Object} A JSON object representing the serialized texture.
  5845. * @see {@link ObjectLoader#parse}
  5846. */
  5847. toJSON( meta ) {
  5848. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  5849. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  5850. return meta.textures[ this.uuid ];
  5851. }
  5852. const output = {
  5853. metadata: {
  5854. version: 4.7,
  5855. type: 'Texture',
  5856. generator: 'Texture.toJSON'
  5857. },
  5858. uuid: this.uuid,
  5859. name: this.name,
  5860. image: this.source.toJSON( meta ).uuid,
  5861. mapping: this.mapping,
  5862. channel: this.channel,
  5863. repeat: [ this.repeat.x, this.repeat.y ],
  5864. offset: [ this.offset.x, this.offset.y ],
  5865. center: [ this.center.x, this.center.y ],
  5866. rotation: this.rotation,
  5867. wrap: [ this.wrapS, this.wrapT ],
  5868. format: this.format,
  5869. internalFormat: this.internalFormat,
  5870. type: this.type,
  5871. colorSpace: this.colorSpace,
  5872. minFilter: this.minFilter,
  5873. magFilter: this.magFilter,
  5874. anisotropy: this.anisotropy,
  5875. flipY: this.flipY,
  5876. generateMipmaps: this.generateMipmaps,
  5877. premultiplyAlpha: this.premultiplyAlpha,
  5878. unpackAlignment: this.unpackAlignment
  5879. };
  5880. if ( Object.keys( this.userData ).length > 0 ) output.userData = this.userData;
  5881. if ( ! isRootObject ) {
  5882. meta.textures[ this.uuid ] = output;
  5883. }
  5884. return output;
  5885. }
  5886. /**
  5887. * Frees the GPU-related resources allocated by this instance. Call this
  5888. * method whenever this instance is no longer used in your app.
  5889. *
  5890. * @fires Texture#dispose
  5891. */
  5892. dispose() {
  5893. /**
  5894. * Fires when the texture has been disposed of.
  5895. *
  5896. * @event Texture#dispose
  5897. * @type {Object}
  5898. */
  5899. this.dispatchEvent( { type: 'dispose' } );
  5900. }
  5901. /**
  5902. * Transforms the given uv vector with the textures uv transformation matrix.
  5903. *
  5904. * @param {Vector2} uv - The uv vector.
  5905. * @return {Vector2} The transformed uv vector.
  5906. */
  5907. transformUv( uv ) {
  5908. if ( this.mapping !== UVMapping ) return uv;
  5909. uv.applyMatrix3( this.matrix );
  5910. if ( uv.x < 0 || uv.x > 1 ) {
  5911. switch ( this.wrapS ) {
  5912. case RepeatWrapping:
  5913. uv.x = uv.x - Math.floor( uv.x );
  5914. break;
  5915. case ClampToEdgeWrapping:
  5916. uv.x = uv.x < 0 ? 0 : 1;
  5917. break;
  5918. case MirroredRepeatWrapping:
  5919. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  5920. uv.x = Math.ceil( uv.x ) - uv.x;
  5921. } else {
  5922. uv.x = uv.x - Math.floor( uv.x );
  5923. }
  5924. break;
  5925. }
  5926. }
  5927. if ( uv.y < 0 || uv.y > 1 ) {
  5928. switch ( this.wrapT ) {
  5929. case RepeatWrapping:
  5930. uv.y = uv.y - Math.floor( uv.y );
  5931. break;
  5932. case ClampToEdgeWrapping:
  5933. uv.y = uv.y < 0 ? 0 : 1;
  5934. break;
  5935. case MirroredRepeatWrapping:
  5936. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  5937. uv.y = Math.ceil( uv.y ) - uv.y;
  5938. } else {
  5939. uv.y = uv.y - Math.floor( uv.y );
  5940. }
  5941. break;
  5942. }
  5943. }
  5944. if ( this.flipY ) {
  5945. uv.y = 1 - uv.y;
  5946. }
  5947. return uv;
  5948. }
  5949. /**
  5950. * Setting this property to `true` indicates the engine the texture
  5951. * must be updated in the next render. This triggers a texture upload
  5952. * to the GPU and ensures correct texture parameter configuration.
  5953. *
  5954. * @type {boolean}
  5955. * @default false
  5956. * @param {boolean} value
  5957. */
  5958. set needsUpdate( value ) {
  5959. if ( value === true ) {
  5960. this.version ++;
  5961. this.source.needsUpdate = true;
  5962. }
  5963. }
  5964. /**
  5965. * Setting this property to `true` indicates the engine the PMREM
  5966. * must be regenerated.
  5967. *
  5968. * @type {boolean}
  5969. * @default false
  5970. * @param {boolean} value
  5971. */
  5972. set needsPMREMUpdate( value ) {
  5973. if ( value === true ) {
  5974. this.pmremVersion ++;
  5975. }
  5976. }
  5977. }
  5978. /**
  5979. * The default image for all textures.
  5980. *
  5981. * @static
  5982. * @type {?Image}
  5983. * @default null
  5984. */
  5985. Texture.DEFAULT_IMAGE = null;
  5986. /**
  5987. * The default mapping for all textures.
  5988. *
  5989. * @static
  5990. * @type {number}
  5991. * @default UVMapping
  5992. */
  5993. Texture.DEFAULT_MAPPING = UVMapping;
  5994. /**
  5995. * The default anisotropy value for all textures.
  5996. *
  5997. * @static
  5998. * @type {number}
  5999. * @default 1
  6000. */
  6001. Texture.DEFAULT_ANISOTROPY = 1;
  6002. /**
  6003. * Class representing a 4D vector. A 4D vector is an ordered quadruplet of numbers
  6004. * (labeled x, y, z and w), which can be used to represent a number of things, such as:
  6005. *
  6006. * - A point in 4D space.
  6007. * - A direction and length in 4D space. In three.js the length will
  6008. * always be the Euclidean distance(straight-line distance) from `(0, 0, 0, 0)` to `(x, y, z, w)`
  6009. * and the direction is also measured from `(0, 0, 0, 0)` towards `(x, y, z, w)`.
  6010. * - Any arbitrary ordered quadruplet of numbers.
  6011. *
  6012. * There are other things a 4D vector can be used to represent, however these
  6013. * are the most common uses in *three.js*.
  6014. *
  6015. * Iterating through a vector instance will yield its components `(x, y, z, w)` in
  6016. * the corresponding order.
  6017. * ```js
  6018. * const a = new THREE.Vector4( 0, 1, 0, 0 );
  6019. *
  6020. * //no arguments; will be initialised to (0, 0, 0, 1)
  6021. * const b = new THREE.Vector4( );
  6022. *
  6023. * const d = a.dot( b );
  6024. * ```
  6025. */
  6026. class Vector4 {
  6027. /**
  6028. * Constructs a new 4D vector.
  6029. *
  6030. * @param {number} [x=0] - The x value of this vector.
  6031. * @param {number} [y=0] - The y value of this vector.
  6032. * @param {number} [z=0] - The z value of this vector.
  6033. * @param {number} [w=1] - The w value of this vector.
  6034. */
  6035. constructor( x = 0, y = 0, z = 0, w = 1 ) {
  6036. /**
  6037. * This flag can be used for type testing.
  6038. *
  6039. * @type {boolean}
  6040. * @readonly
  6041. * @default true
  6042. */
  6043. Vector4.prototype.isVector4 = true;
  6044. /**
  6045. * The x value of this vector.
  6046. *
  6047. * @type {number}
  6048. */
  6049. this.x = x;
  6050. /**
  6051. * The y value of this vector.
  6052. *
  6053. * @type {number}
  6054. */
  6055. this.y = y;
  6056. /**
  6057. * The z value of this vector.
  6058. *
  6059. * @type {number}
  6060. */
  6061. this.z = z;
  6062. /**
  6063. * The w value of this vector.
  6064. *
  6065. * @type {number}
  6066. */
  6067. this.w = w;
  6068. }
  6069. /**
  6070. * Alias for {@link Vector4#z}.
  6071. *
  6072. * @type {number}
  6073. */
  6074. get width() {
  6075. return this.z;
  6076. }
  6077. set width( value ) {
  6078. this.z = value;
  6079. }
  6080. /**
  6081. * Alias for {@link Vector4#w}.
  6082. *
  6083. * @type {number}
  6084. */
  6085. get height() {
  6086. return this.w;
  6087. }
  6088. set height( value ) {
  6089. this.w = value;
  6090. }
  6091. /**
  6092. * Sets the vector components.
  6093. *
  6094. * @param {number} x - The value of the x component.
  6095. * @param {number} y - The value of the y component.
  6096. * @param {number} z - The value of the z component.
  6097. * @param {number} w - The value of the w component.
  6098. * @return {Vector4} A reference to this vector.
  6099. */
  6100. set( x, y, z, w ) {
  6101. this.x = x;
  6102. this.y = y;
  6103. this.z = z;
  6104. this.w = w;
  6105. return this;
  6106. }
  6107. /**
  6108. * Sets the vector components to the same value.
  6109. *
  6110. * @param {number} scalar - The value to set for all vector components.
  6111. * @return {Vector4} A reference to this vector.
  6112. */
  6113. setScalar( scalar ) {
  6114. this.x = scalar;
  6115. this.y = scalar;
  6116. this.z = scalar;
  6117. this.w = scalar;
  6118. return this;
  6119. }
  6120. /**
  6121. * Sets the vector's x component to the given value
  6122. *
  6123. * @param {number} x - The value to set.
  6124. * @return {Vector4} A reference to this vector.
  6125. */
  6126. setX( x ) {
  6127. this.x = x;
  6128. return this;
  6129. }
  6130. /**
  6131. * Sets the vector's y component to the given value
  6132. *
  6133. * @param {number} y - The value to set.
  6134. * @return {Vector4} A reference to this vector.
  6135. */
  6136. setY( y ) {
  6137. this.y = y;
  6138. return this;
  6139. }
  6140. /**
  6141. * Sets the vector's z component to the given value
  6142. *
  6143. * @param {number} z - The value to set.
  6144. * @return {Vector4} A reference to this vector.
  6145. */
  6146. setZ( z ) {
  6147. this.z = z;
  6148. return this;
  6149. }
  6150. /**
  6151. * Sets the vector's w component to the given value
  6152. *
  6153. * @param {number} w - The value to set.
  6154. * @return {Vector4} A reference to this vector.
  6155. */
  6156. setW( w ) {
  6157. this.w = w;
  6158. return this;
  6159. }
  6160. /**
  6161. * Allows to set a vector component with an index.
  6162. *
  6163. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6164. * `2` equals to z, `3` equals to w.
  6165. * @param {number} value - The value to set.
  6166. * @return {Vector4} A reference to this vector.
  6167. */
  6168. setComponent( index, value ) {
  6169. switch ( index ) {
  6170. case 0: this.x = value; break;
  6171. case 1: this.y = value; break;
  6172. case 2: this.z = value; break;
  6173. case 3: this.w = value; break;
  6174. default: throw new Error( 'index is out of range: ' + index );
  6175. }
  6176. return this;
  6177. }
  6178. /**
  6179. * Returns the value of the vector component which matches the given index.
  6180. *
  6181. * @param {number} index - The component index. `0` equals to x, `1` equals to y,
  6182. * `2` equals to z, `3` equals to w.
  6183. * @return {number} A vector component value.
  6184. */
  6185. getComponent( index ) {
  6186. switch ( index ) {
  6187. case 0: return this.x;
  6188. case 1: return this.y;
  6189. case 2: return this.z;
  6190. case 3: return this.w;
  6191. default: throw new Error( 'index is out of range: ' + index );
  6192. }
  6193. }
  6194. /**
  6195. * Returns a new vector with copied values from this instance.
  6196. *
  6197. * @return {Vector4} A clone of this instance.
  6198. */
  6199. clone() {
  6200. return new this.constructor( this.x, this.y, this.z, this.w );
  6201. }
  6202. /**
  6203. * Copies the values of the given vector to this instance.
  6204. *
  6205. * @param {Vector3|Vector4} v - The vector to copy.
  6206. * @return {Vector4} A reference to this vector.
  6207. */
  6208. copy( v ) {
  6209. this.x = v.x;
  6210. this.y = v.y;
  6211. this.z = v.z;
  6212. this.w = ( v.w !== undefined ) ? v.w : 1;
  6213. return this;
  6214. }
  6215. /**
  6216. * Adds the given vector to this instance.
  6217. *
  6218. * @param {Vector4} v - The vector to add.
  6219. * @return {Vector4} A reference to this vector.
  6220. */
  6221. add( v ) {
  6222. this.x += v.x;
  6223. this.y += v.y;
  6224. this.z += v.z;
  6225. this.w += v.w;
  6226. return this;
  6227. }
  6228. /**
  6229. * Adds the given scalar value to all components of this instance.
  6230. *
  6231. * @param {number} s - The scalar to add.
  6232. * @return {Vector4} A reference to this vector.
  6233. */
  6234. addScalar( s ) {
  6235. this.x += s;
  6236. this.y += s;
  6237. this.z += s;
  6238. this.w += s;
  6239. return this;
  6240. }
  6241. /**
  6242. * Adds the given vectors and stores the result in this instance.
  6243. *
  6244. * @param {Vector4} a - The first vector.
  6245. * @param {Vector4} b - The second vector.
  6246. * @return {Vector4} A reference to this vector.
  6247. */
  6248. addVectors( a, b ) {
  6249. this.x = a.x + b.x;
  6250. this.y = a.y + b.y;
  6251. this.z = a.z + b.z;
  6252. this.w = a.w + b.w;
  6253. return this;
  6254. }
  6255. /**
  6256. * Adds the given vector scaled by the given factor to this instance.
  6257. *
  6258. * @param {Vector4} v - The vector.
  6259. * @param {number} s - The factor that scales `v`.
  6260. * @return {Vector4} A reference to this vector.
  6261. */
  6262. addScaledVector( v, s ) {
  6263. this.x += v.x * s;
  6264. this.y += v.y * s;
  6265. this.z += v.z * s;
  6266. this.w += v.w * s;
  6267. return this;
  6268. }
  6269. /**
  6270. * Subtracts the given vector from this instance.
  6271. *
  6272. * @param {Vector4} v - The vector to subtract.
  6273. * @return {Vector4} A reference to this vector.
  6274. */
  6275. sub( v ) {
  6276. this.x -= v.x;
  6277. this.y -= v.y;
  6278. this.z -= v.z;
  6279. this.w -= v.w;
  6280. return this;
  6281. }
  6282. /**
  6283. * Subtracts the given scalar value from all components of this instance.
  6284. *
  6285. * @param {number} s - The scalar to subtract.
  6286. * @return {Vector4} A reference to this vector.
  6287. */
  6288. subScalar( s ) {
  6289. this.x -= s;
  6290. this.y -= s;
  6291. this.z -= s;
  6292. this.w -= s;
  6293. return this;
  6294. }
  6295. /**
  6296. * Subtracts the given vectors and stores the result in this instance.
  6297. *
  6298. * @param {Vector4} a - The first vector.
  6299. * @param {Vector4} b - The second vector.
  6300. * @return {Vector4} A reference to this vector.
  6301. */
  6302. subVectors( a, b ) {
  6303. this.x = a.x - b.x;
  6304. this.y = a.y - b.y;
  6305. this.z = a.z - b.z;
  6306. this.w = a.w - b.w;
  6307. return this;
  6308. }
  6309. /**
  6310. * Multiplies the given vector with this instance.
  6311. *
  6312. * @param {Vector4} v - The vector to multiply.
  6313. * @return {Vector4} A reference to this vector.
  6314. */
  6315. multiply( v ) {
  6316. this.x *= v.x;
  6317. this.y *= v.y;
  6318. this.z *= v.z;
  6319. this.w *= v.w;
  6320. return this;
  6321. }
  6322. /**
  6323. * Multiplies the given scalar value with all components of this instance.
  6324. *
  6325. * @param {number} scalar - The scalar to multiply.
  6326. * @return {Vector4} A reference to this vector.
  6327. */
  6328. multiplyScalar( scalar ) {
  6329. this.x *= scalar;
  6330. this.y *= scalar;
  6331. this.z *= scalar;
  6332. this.w *= scalar;
  6333. return this;
  6334. }
  6335. /**
  6336. * Multiplies this vector with the given 4x4 matrix.
  6337. *
  6338. * @param {Matrix4} m - The 4x4 matrix.
  6339. * @return {Vector4} A reference to this vector.
  6340. */
  6341. applyMatrix4( m ) {
  6342. const x = this.x, y = this.y, z = this.z, w = this.w;
  6343. const e = m.elements;
  6344. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6345. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6346. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6347. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6348. return this;
  6349. }
  6350. /**
  6351. * Divides this instance by the given vector.
  6352. *
  6353. * @param {Vector4} v - The vector to divide.
  6354. * @return {Vector4} A reference to this vector.
  6355. */
  6356. divide( v ) {
  6357. this.x /= v.x;
  6358. this.y /= v.y;
  6359. this.z /= v.z;
  6360. this.w /= v.w;
  6361. return this;
  6362. }
  6363. /**
  6364. * Divides this vector by the given scalar.
  6365. *
  6366. * @param {number} scalar - The scalar to divide.
  6367. * @return {Vector4} A reference to this vector.
  6368. */
  6369. divideScalar( scalar ) {
  6370. return this.multiplyScalar( 1 / scalar );
  6371. }
  6372. /**
  6373. * Sets the x, y and z components of this
  6374. * vector to the quaternion's axis and w to the angle.
  6375. *
  6376. * @param {Quaternion} q - The Quaternion to set.
  6377. * @return {Vector4} A reference to this vector.
  6378. */
  6379. setAxisAngleFromQuaternion( q ) {
  6380. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6381. // q is assumed to be normalized
  6382. this.w = 2 * Math.acos( q.w );
  6383. const s = Math.sqrt( 1 - q.w * q.w );
  6384. if ( s < 0.0001 ) {
  6385. this.x = 1;
  6386. this.y = 0;
  6387. this.z = 0;
  6388. } else {
  6389. this.x = q.x / s;
  6390. this.y = q.y / s;
  6391. this.z = q.z / s;
  6392. }
  6393. return this;
  6394. }
  6395. /**
  6396. * Sets the x, y and z components of this
  6397. * vector to the axis of rotation and w to the angle.
  6398. *
  6399. * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix.
  6400. * @return {Vector4} A reference to this vector.
  6401. */
  6402. setAxisAngleFromRotationMatrix( m ) {
  6403. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6404. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6405. let angle, x, y, z; // variables for result
  6406. const epsilon = 0.01, // margin to allow for rounding errors
  6407. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6408. te = m.elements,
  6409. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6410. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6411. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6412. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6413. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6414. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6415. // singularity found
  6416. // first check for identity matrix which must have +1 for all terms
  6417. // in leading diagonal and zero in other terms
  6418. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6419. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6420. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6421. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6422. // this singularity is identity matrix so angle = 0
  6423. this.set( 1, 0, 0, 0 );
  6424. return this; // zero angle, arbitrary axis
  6425. }
  6426. // otherwise this singularity is angle = 180
  6427. angle = Math.PI;
  6428. const xx = ( m11 + 1 ) / 2;
  6429. const yy = ( m22 + 1 ) / 2;
  6430. const zz = ( m33 + 1 ) / 2;
  6431. const xy = ( m12 + m21 ) / 4;
  6432. const xz = ( m13 + m31 ) / 4;
  6433. const yz = ( m23 + m32 ) / 4;
  6434. if ( ( xx > yy ) && ( xx > zz ) ) {
  6435. // m11 is the largest diagonal term
  6436. if ( xx < epsilon ) {
  6437. x = 0;
  6438. y = 0.707106781;
  6439. z = 0.707106781;
  6440. } else {
  6441. x = Math.sqrt( xx );
  6442. y = xy / x;
  6443. z = xz / x;
  6444. }
  6445. } else if ( yy > zz ) {
  6446. // m22 is the largest diagonal term
  6447. if ( yy < epsilon ) {
  6448. x = 0.707106781;
  6449. y = 0;
  6450. z = 0.707106781;
  6451. } else {
  6452. y = Math.sqrt( yy );
  6453. x = xy / y;
  6454. z = yz / y;
  6455. }
  6456. } else {
  6457. // m33 is the largest diagonal term so base result on this
  6458. if ( zz < epsilon ) {
  6459. x = 0.707106781;
  6460. y = 0.707106781;
  6461. z = 0;
  6462. } else {
  6463. z = Math.sqrt( zz );
  6464. x = xz / z;
  6465. y = yz / z;
  6466. }
  6467. }
  6468. this.set( x, y, z, angle );
  6469. return this; // return 180 deg rotation
  6470. }
  6471. // as we have reached here there are no singularities so we can handle normally
  6472. let s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  6473. ( m13 - m31 ) * ( m13 - m31 ) +
  6474. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  6475. if ( Math.abs( s ) < 0.001 ) s = 1;
  6476. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  6477. // caught by singularity test above, but I've left it in just in case
  6478. this.x = ( m32 - m23 ) / s;
  6479. this.y = ( m13 - m31 ) / s;
  6480. this.z = ( m21 - m12 ) / s;
  6481. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  6482. return this;
  6483. }
  6484. /**
  6485. * Sets the vector components to the position elements of the
  6486. * given transformation matrix.
  6487. *
  6488. * @param {Matrix4} m - The 4x4 matrix.
  6489. * @return {Vector4} A reference to this vector.
  6490. */
  6491. setFromMatrixPosition( m ) {
  6492. const e = m.elements;
  6493. this.x = e[ 12 ];
  6494. this.y = e[ 13 ];
  6495. this.z = e[ 14 ];
  6496. this.w = e[ 15 ];
  6497. return this;
  6498. }
  6499. /**
  6500. * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w
  6501. * value, replace that value with the corresponding min value.
  6502. *
  6503. * @param {Vector4} v - The vector.
  6504. * @return {Vector4} A reference to this vector.
  6505. */
  6506. min( v ) {
  6507. this.x = Math.min( this.x, v.x );
  6508. this.y = Math.min( this.y, v.y );
  6509. this.z = Math.min( this.z, v.z );
  6510. this.w = Math.min( this.w, v.w );
  6511. return this;
  6512. }
  6513. /**
  6514. * If this vector's x, y, z or w value is less than the given vector's x, y, z or w
  6515. * value, replace that value with the corresponding max value.
  6516. *
  6517. * @param {Vector4} v - The vector.
  6518. * @return {Vector4} A reference to this vector.
  6519. */
  6520. max( v ) {
  6521. this.x = Math.max( this.x, v.x );
  6522. this.y = Math.max( this.y, v.y );
  6523. this.z = Math.max( this.z, v.z );
  6524. this.w = Math.max( this.w, v.w );
  6525. return this;
  6526. }
  6527. /**
  6528. * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w
  6529. * value, it is replaced by the corresponding value.
  6530. * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value,
  6531. * it is replaced by the corresponding value.
  6532. *
  6533. * @param {Vector4} min - The minimum x, y and z values.
  6534. * @param {Vector4} max - The maximum x, y and z values in the desired range.
  6535. * @return {Vector4} A reference to this vector.
  6536. */
  6537. clamp( min, max ) {
  6538. // assumes min < max, componentwise
  6539. this.x = clamp( this.x, min.x, max.x );
  6540. this.y = clamp( this.y, min.y, max.y );
  6541. this.z = clamp( this.z, min.z, max.z );
  6542. this.w = clamp( this.w, min.w, max.w );
  6543. return this;
  6544. }
  6545. /**
  6546. * If this vector's x, y, z or w values are greater than the max value, they are
  6547. * replaced by the max value.
  6548. * If this vector's x, y, z or w values are less than the min value, they are
  6549. * replaced by the min value.
  6550. *
  6551. * @param {number} minVal - The minimum value the components will be clamped to.
  6552. * @param {number} maxVal - The maximum value the components will be clamped to.
  6553. * @return {Vector4} A reference to this vector.
  6554. */
  6555. clampScalar( minVal, maxVal ) {
  6556. this.x = clamp( this.x, minVal, maxVal );
  6557. this.y = clamp( this.y, minVal, maxVal );
  6558. this.z = clamp( this.z, minVal, maxVal );
  6559. this.w = clamp( this.w, minVal, maxVal );
  6560. return this;
  6561. }
  6562. /**
  6563. * If this vector's length is greater than the max value, it is replaced by
  6564. * the max value.
  6565. * If this vector's length is less than the min value, it is replaced by the
  6566. * min value.
  6567. *
  6568. * @param {number} min - The minimum value the vector length will be clamped to.
  6569. * @param {number} max - The maximum value the vector length will be clamped to.
  6570. * @return {Vector4} A reference to this vector.
  6571. */
  6572. clampLength( min, max ) {
  6573. const length = this.length();
  6574. return this.divideScalar( length || 1 ).multiplyScalar( clamp( length, min, max ) );
  6575. }
  6576. /**
  6577. * The components of this vector are rounded down to the nearest integer value.
  6578. *
  6579. * @return {Vector4} A reference to this vector.
  6580. */
  6581. floor() {
  6582. this.x = Math.floor( this.x );
  6583. this.y = Math.floor( this.y );
  6584. this.z = Math.floor( this.z );
  6585. this.w = Math.floor( this.w );
  6586. return this;
  6587. }
  6588. /**
  6589. * The components of this vector are rounded up to the nearest integer value.
  6590. *
  6591. * @return {Vector4} A reference to this vector.
  6592. */
  6593. ceil() {
  6594. this.x = Math.ceil( this.x );
  6595. this.y = Math.ceil( this.y );
  6596. this.z = Math.ceil( this.z );
  6597. this.w = Math.ceil( this.w );
  6598. return this;
  6599. }
  6600. /**
  6601. * The components of this vector are rounded to the nearest integer value
  6602. *
  6603. * @return {Vector4} A reference to this vector.
  6604. */
  6605. round() {
  6606. this.x = Math.round( this.x );
  6607. this.y = Math.round( this.y );
  6608. this.z = Math.round( this.z );
  6609. this.w = Math.round( this.w );
  6610. return this;
  6611. }
  6612. /**
  6613. * The components of this vector are rounded towards zero (up if negative,
  6614. * down if positive) to an integer value.
  6615. *
  6616. * @return {Vector4} A reference to this vector.
  6617. */
  6618. roundToZero() {
  6619. this.x = Math.trunc( this.x );
  6620. this.y = Math.trunc( this.y );
  6621. this.z = Math.trunc( this.z );
  6622. this.w = Math.trunc( this.w );
  6623. return this;
  6624. }
  6625. /**
  6626. * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w.
  6627. *
  6628. * @return {Vector4} A reference to this vector.
  6629. */
  6630. negate() {
  6631. this.x = - this.x;
  6632. this.y = - this.y;
  6633. this.z = - this.z;
  6634. this.w = - this.w;
  6635. return this;
  6636. }
  6637. /**
  6638. * Calculates the dot product of the given vector with this instance.
  6639. *
  6640. * @param {Vector4} v - The vector to compute the dot product with.
  6641. * @return {number} The result of the dot product.
  6642. */
  6643. dot( v ) {
  6644. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  6645. }
  6646. /**
  6647. * Computes the square of the Euclidean length (straight-line length) from
  6648. * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should
  6649. * compare the length squared instead as it is slightly more efficient to calculate.
  6650. *
  6651. * @return {number} The square length of this vector.
  6652. */
  6653. lengthSq() {
  6654. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  6655. }
  6656. /**
  6657. * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w).
  6658. *
  6659. * @return {number} The length of this vector.
  6660. */
  6661. length() {
  6662. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  6663. }
  6664. /**
  6665. * Computes the Manhattan length of this vector.
  6666. *
  6667. * @return {number} The length of this vector.
  6668. */
  6669. manhattanLength() {
  6670. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  6671. }
  6672. /**
  6673. * Converts this vector to a unit vector - that is, sets it equal to a vector
  6674. * with the same direction as this one, but with a vector length of `1`.
  6675. *
  6676. * @return {Vector4} A reference to this vector.
  6677. */
  6678. normalize() {
  6679. return this.divideScalar( this.length() || 1 );
  6680. }
  6681. /**
  6682. * Sets this vector to a vector with the same direction as this one, but
  6683. * with the specified length.
  6684. *
  6685. * @param {number} length - The new length of this vector.
  6686. * @return {Vector4} A reference to this vector.
  6687. */
  6688. setLength( length ) {
  6689. return this.normalize().multiplyScalar( length );
  6690. }
  6691. /**
  6692. * Linearly interpolates between the given vector and this instance, where
  6693. * alpha is the percent distance along the line - alpha = 0 will be this
  6694. * vector, and alpha = 1 will be the given one.
  6695. *
  6696. * @param {Vector4} v - The vector to interpolate towards.
  6697. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6698. * @return {Vector4} A reference to this vector.
  6699. */
  6700. lerp( v, alpha ) {
  6701. this.x += ( v.x - this.x ) * alpha;
  6702. this.y += ( v.y - this.y ) * alpha;
  6703. this.z += ( v.z - this.z ) * alpha;
  6704. this.w += ( v.w - this.w ) * alpha;
  6705. return this;
  6706. }
  6707. /**
  6708. * Linearly interpolates between the given vectors, where alpha is the percent
  6709. * distance along the line - alpha = 0 will be first vector, and alpha = 1 will
  6710. * be the second one. The result is stored in this instance.
  6711. *
  6712. * @param {Vector4} v1 - The first vector.
  6713. * @param {Vector4} v2 - The second vector.
  6714. * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`.
  6715. * @return {Vector4} A reference to this vector.
  6716. */
  6717. lerpVectors( v1, v2, alpha ) {
  6718. this.x = v1.x + ( v2.x - v1.x ) * alpha;
  6719. this.y = v1.y + ( v2.y - v1.y ) * alpha;
  6720. this.z = v1.z + ( v2.z - v1.z ) * alpha;
  6721. this.w = v1.w + ( v2.w - v1.w ) * alpha;
  6722. return this;
  6723. }
  6724. /**
  6725. * Returns `true` if this vector is equal with the given one.
  6726. *
  6727. * @param {Vector4} v - The vector to test for equality.
  6728. * @return {boolean} Whether this vector is equal with the given one.
  6729. */
  6730. equals( v ) {
  6731. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  6732. }
  6733. /**
  6734. * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`,
  6735. * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`.
  6736. *
  6737. * @param {Array<number>} array - An array holding the vector component values.
  6738. * @param {number} [offset=0] - The offset into the array.
  6739. * @return {Vector4} A reference to this vector.
  6740. */
  6741. fromArray( array, offset = 0 ) {
  6742. this.x = array[ offset ];
  6743. this.y = array[ offset + 1 ];
  6744. this.z = array[ offset + 2 ];
  6745. this.w = array[ offset + 3 ];
  6746. return this;
  6747. }
  6748. /**
  6749. * Writes the components of this vector to the given array. If no array is provided,
  6750. * the method returns a new instance.
  6751. *
  6752. * @param {Array<number>} [array=[]] - The target array holding the vector components.
  6753. * @param {number} [offset=0] - Index of the first element in the array.
  6754. * @return {Array<number>} The vector components.
  6755. */
  6756. toArray( array = [], offset = 0 ) {
  6757. array[ offset ] = this.x;
  6758. array[ offset + 1 ] = this.y;
  6759. array[ offset + 2 ] = this.z;
  6760. array[ offset + 3 ] = this.w;
  6761. return array;
  6762. }
  6763. /**
  6764. * Sets the components of this vector from the given buffer attribute.
  6765. *
  6766. * @param {BufferAttribute} attribute - The buffer attribute holding vector data.
  6767. * @param {number} index - The index into the attribute.
  6768. * @return {Vector4} A reference to this vector.
  6769. */
  6770. fromBufferAttribute( attribute, index ) {
  6771. this.x = attribute.getX( index );
  6772. this.y = attribute.getY( index );
  6773. this.z = attribute.getZ( index );
  6774. this.w = attribute.getW( index );
  6775. return this;
  6776. }
  6777. /**
  6778. * Sets each component of this vector to a pseudo-random value between `0` and
  6779. * `1`, excluding `1`.
  6780. *
  6781. * @return {Vector4} A reference to this vector.
  6782. */
  6783. random() {
  6784. this.x = Math.random();
  6785. this.y = Math.random();
  6786. this.z = Math.random();
  6787. this.w = Math.random();
  6788. return this;
  6789. }
  6790. *[ Symbol.iterator ]() {
  6791. yield this.x;
  6792. yield this.y;
  6793. yield this.z;
  6794. yield this.w;
  6795. }
  6796. }
  6797. /**
  6798. * A render target is a buffer where the video card draws pixels for a scene
  6799. * that is being rendered in the background. It is used in different effects,
  6800. * such as applying postprocessing to a rendered image before displaying it
  6801. * on the screen.
  6802. *
  6803. * @augments EventDispatcher
  6804. */
  6805. class RenderTarget extends EventDispatcher {
  6806. /**
  6807. * Render target options.
  6808. *
  6809. * @typedef {Object} RenderTarget~Options
  6810. * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not.
  6811. * @property {number} [magFilter=LinearFilter] - The mag filter.
  6812. * @property {number} [minFilter=LinearFilter] - The min filter.
  6813. * @property {number} [format=RGBAFormat] - The texture format.
  6814. * @property {number} [type=UnsignedByteType] - The texture type.
  6815. * @property {?string} [internalFormat=null] - The texture's internal format.
  6816. * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6817. * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode.
  6818. * @property {number} [anisotropy=1] - The texture's anisotropy value.
  6819. * @property {string} [colorSpace=NoColorSpace] - The texture's color space.
  6820. * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not.
  6821. * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not.
  6822. * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not.
  6823. * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not.
  6824. * @property {?Texture} [depthTexture=null] - Reference to a depth texture.
  6825. * @property {number} [samples=0] - The MSAA samples count.
  6826. * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`.
  6827. * @property {number} [depth=1] - The texture depth.
  6828. * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering.
  6829. */
  6830. /**
  6831. * Constructs a new render target.
  6832. *
  6833. * @param {number} [width=1] - The width of the render target.
  6834. * @param {number} [height=1] - The height of the render target.
  6835. * @param {RenderTarget~Options} [options] - The configuration object.
  6836. */
  6837. constructor( width = 1, height = 1, options = {} ) {
  6838. super();
  6839. options = Object.assign( {
  6840. generateMipmaps: false,
  6841. internalFormat: null,
  6842. minFilter: LinearFilter,
  6843. depthBuffer: true,
  6844. stencilBuffer: false,
  6845. resolveDepthBuffer: true,
  6846. resolveStencilBuffer: true,
  6847. depthTexture: null,
  6848. samples: 0,
  6849. count: 1,
  6850. depth: 1,
  6851. multiview: false
  6852. }, options );
  6853. /**
  6854. * This flag can be used for type testing.
  6855. *
  6856. * @type {boolean}
  6857. * @readonly
  6858. * @default true
  6859. */
  6860. this.isRenderTarget = true;
  6861. /**
  6862. * The width of the render target.
  6863. *
  6864. * @type {number}
  6865. * @default 1
  6866. */
  6867. this.width = width;
  6868. /**
  6869. * The height of the render target.
  6870. *
  6871. * @type {number}
  6872. * @default 1
  6873. */
  6874. this.height = height;
  6875. /**
  6876. * The depth of the render target.
  6877. *
  6878. * @type {number}
  6879. * @default 1
  6880. */
  6881. this.depth = options.depth;
  6882. /**
  6883. * A rectangular area inside the render target's viewport. Fragments that are
  6884. * outside the area will be discarded.
  6885. *
  6886. * @type {Vector4}
  6887. * @default (0,0,width,height)
  6888. */
  6889. this.scissor = new Vector4( 0, 0, width, height );
  6890. /**
  6891. * Indicates whether the scissor test should be enabled when rendering into
  6892. * this render target or not.
  6893. *
  6894. * @type {boolean}
  6895. * @default false
  6896. */
  6897. this.scissorTest = false;
  6898. /**
  6899. * A rectangular area representing the render target's viewport.
  6900. *
  6901. * @type {Vector4}
  6902. * @default (0,0,width,height)
  6903. */
  6904. this.viewport = new Vector4( 0, 0, width, height );
  6905. const image = { width: width, height: height, depth: options.depth };
  6906. const texture = new Texture( image );
  6907. /**
  6908. * An array of textures. Each color attachment is represented as a separate texture.
  6909. * Has at least a single entry for the default color attachment.
  6910. *
  6911. * @type {Array<Texture>}
  6912. */
  6913. this.textures = [];
  6914. const count = options.count;
  6915. for ( let i = 0; i < count; i ++ ) {
  6916. this.textures[ i ] = texture.clone();
  6917. this.textures[ i ].isRenderTargetTexture = true;
  6918. this.textures[ i ].renderTarget = this;
  6919. }
  6920. this._setTextureOptions( options );
  6921. /**
  6922. * Whether to allocate a depth buffer or not.
  6923. *
  6924. * @type {boolean}
  6925. * @default true
  6926. */
  6927. this.depthBuffer = options.depthBuffer;
  6928. /**
  6929. * Whether to allocate a stencil buffer or not.
  6930. *
  6931. * @type {boolean}
  6932. * @default false
  6933. */
  6934. this.stencilBuffer = options.stencilBuffer;
  6935. /**
  6936. * Whether to resolve the depth buffer or not.
  6937. *
  6938. * @type {boolean}
  6939. * @default true
  6940. */
  6941. this.resolveDepthBuffer = options.resolveDepthBuffer;
  6942. /**
  6943. * Whether to resolve the stencil buffer or not.
  6944. *
  6945. * @type {boolean}
  6946. * @default true
  6947. */
  6948. this.resolveStencilBuffer = options.resolveStencilBuffer;
  6949. this._depthTexture = null;
  6950. this.depthTexture = options.depthTexture;
  6951. /**
  6952. * The number of MSAA samples.
  6953. *
  6954. * A value of `0` disables MSAA.
  6955. *
  6956. * @type {number}
  6957. * @default 0
  6958. */
  6959. this.samples = options.samples;
  6960. /**
  6961. * Whether to this target is used in multiview rendering.
  6962. *
  6963. * @type {boolean}
  6964. * @default false
  6965. */
  6966. this.multiview = options.multiview;
  6967. }
  6968. _setTextureOptions( options = {} ) {
  6969. const values = {
  6970. minFilter: LinearFilter,
  6971. generateMipmaps: false,
  6972. flipY: false,
  6973. internalFormat: null
  6974. };
  6975. if ( options.mapping !== undefined ) values.mapping = options.mapping;
  6976. if ( options.wrapS !== undefined ) values.wrapS = options.wrapS;
  6977. if ( options.wrapT !== undefined ) values.wrapT = options.wrapT;
  6978. if ( options.wrapR !== undefined ) values.wrapR = options.wrapR;
  6979. if ( options.magFilter !== undefined ) values.magFilter = options.magFilter;
  6980. if ( options.minFilter !== undefined ) values.minFilter = options.minFilter;
  6981. if ( options.format !== undefined ) values.format = options.format;
  6982. if ( options.type !== undefined ) values.type = options.type;
  6983. if ( options.anisotropy !== undefined ) values.anisotropy = options.anisotropy;
  6984. if ( options.colorSpace !== undefined ) values.colorSpace = options.colorSpace;
  6985. if ( options.flipY !== undefined ) values.flipY = options.flipY;
  6986. if ( options.generateMipmaps !== undefined ) values.generateMipmaps = options.generateMipmaps;
  6987. if ( options.internalFormat !== undefined ) values.internalFormat = options.internalFormat;
  6988. for ( let i = 0; i < this.textures.length; i ++ ) {
  6989. const texture = this.textures[ i ];
  6990. texture.setValues( values );
  6991. }
  6992. }
  6993. /**
  6994. * The texture representing the default color attachment.
  6995. *
  6996. * @type {Texture}
  6997. */
  6998. get texture() {
  6999. return this.textures[ 0 ];
  7000. }
  7001. set texture( value ) {
  7002. this.textures[ 0 ] = value;
  7003. }
  7004. set depthTexture( current ) {
  7005. if ( this._depthTexture !== null ) this._depthTexture.renderTarget = null;
  7006. if ( current !== null ) current.renderTarget = this;
  7007. this._depthTexture = current;
  7008. }
  7009. /**
  7010. * Instead of saving the depth in a renderbuffer, a texture
  7011. * can be used instead which is useful for further processing
  7012. * e.g. in context of post-processing.
  7013. *
  7014. * @type {?DepthTexture}
  7015. * @default null
  7016. */
  7017. get depthTexture() {
  7018. return this._depthTexture;
  7019. }
  7020. /**
  7021. * Sets the size of this render target.
  7022. *
  7023. * @param {number} width - The width.
  7024. * @param {number} height - The height.
  7025. * @param {number} [depth=1] - The depth.
  7026. */
  7027. setSize( width, height, depth = 1 ) {
  7028. if ( this.width !== width || this.height !== height || this.depth !== depth ) {
  7029. this.width = width;
  7030. this.height = height;
  7031. this.depth = depth;
  7032. for ( let i = 0, il = this.textures.length; i < il; i ++ ) {
  7033. this.textures[ i ].image.width = width;
  7034. this.textures[ i ].image.height = height;
  7035. this.textures[ i ].image.depth = depth;
  7036. if ( this.textures[ i ].isData3DTexture !== true ) { // Fix for #31693
  7037. // TODO: Reconsider setting isArrayTexture flag here and in the ctor of Texture.
  7038. // Maybe a method `isArrayTexture()` or just a getter could replace a flag since
  7039. // both are evaluated on each call?
  7040. this.textures[ i ].isArrayTexture = this.textures[ i ].image.depth > 1;
  7041. }
  7042. }
  7043. this.dispose();
  7044. }
  7045. this.viewport.set( 0, 0, width, height );
  7046. this.scissor.set( 0, 0, width, height );
  7047. }
  7048. /**
  7049. * Returns a new render target with copied values from this instance.
  7050. *
  7051. * @return {RenderTarget} A clone of this instance.
  7052. */
  7053. clone() {
  7054. return new this.constructor().copy( this );
  7055. }
  7056. /**
  7057. * Copies the settings of the given render target. This is a structural copy so
  7058. * no resources are shared between render targets after the copy. That includes
  7059. * all MRT textures and the depth texture.
  7060. *
  7061. * @param {RenderTarget} source - The render target to copy.
  7062. * @return {RenderTarget} A reference to this instance.
  7063. */
  7064. copy( source ) {
  7065. this.width = source.width;
  7066. this.height = source.height;
  7067. this.depth = source.depth;
  7068. this.scissor.copy( source.scissor );
  7069. this.scissorTest = source.scissorTest;
  7070. this.viewport.copy( source.viewport );
  7071. this.textures.length = 0;
  7072. for ( let i = 0, il = source.textures.length; i < il; i ++ ) {
  7073. this.textures[ i ] = source.textures[ i ].clone();
  7074. this.textures[ i ].isRenderTargetTexture = true;
  7075. this.textures[ i ].renderTarget = this;
  7076. // ensure image object is not shared, see #20328
  7077. const image = Object.assign( {}, source.textures[ i ].image );
  7078. this.textures[ i ].source = new Source( image );
  7079. }
  7080. this.depthBuffer = source.depthBuffer;
  7081. this.stencilBuffer = source.stencilBuffer;
  7082. this.resolveDepthBuffer = source.resolveDepthBuffer;
  7083. this.resolveStencilBuffer = source.resolveStencilBuffer;
  7084. if ( source.depthTexture !== null ) this.depthTexture = source.depthTexture.clone();
  7085. this.samples = source.samples;
  7086. return this;
  7087. }
  7088. /**
  7089. * Frees the GPU-related resources allocated by this instance. Call this
  7090. * method whenever this instance is no longer used in your app.
  7091. *
  7092. * @fires RenderTarget#dispose
  7093. */
  7094. dispose() {
  7095. this.dispatchEvent( { type: 'dispose' } );
  7096. }
  7097. }
  7098. /**
  7099. * A render target used in context of {@link WebGLRenderer}.
  7100. *
  7101. * @augments RenderTarget
  7102. */
  7103. class WebGLRenderTarget extends RenderTarget {
  7104. /**
  7105. * Constructs a new 3D render target.
  7106. *
  7107. * @param {number} [width=1] - The width of the render target.
  7108. * @param {number} [height=1] - The height of the render target.
  7109. * @param {RenderTarget~Options} [options] - The configuration object.
  7110. */
  7111. constructor( width = 1, height = 1, options = {} ) {
  7112. super( width, height, options );
  7113. /**
  7114. * This flag can be used for type testing.
  7115. *
  7116. * @type {boolean}
  7117. * @readonly
  7118. * @default true
  7119. */
  7120. this.isWebGLRenderTarget = true;
  7121. }
  7122. }
  7123. /**
  7124. * Creates an array of textures directly from raw buffer data.
  7125. *
  7126. * @augments Texture
  7127. */
  7128. class DataArrayTexture extends Texture {
  7129. /**
  7130. * Constructs a new data array texture.
  7131. *
  7132. * @param {?TypedArray} [data=null] - The buffer data.
  7133. * @param {number} [width=1] - The width of the texture.
  7134. * @param {number} [height=1] - The height of the texture.
  7135. * @param {number} [depth=1] - The depth of the texture.
  7136. */
  7137. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7138. super( null );
  7139. /**
  7140. * This flag can be used for type testing.
  7141. *
  7142. * @type {boolean}
  7143. * @readonly
  7144. * @default true
  7145. */
  7146. this.isDataArrayTexture = true;
  7147. /**
  7148. * The image definition of a data texture.
  7149. *
  7150. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7151. */
  7152. this.image = { data, width, height, depth };
  7153. /**
  7154. * How the texture is sampled when a texel covers more than one pixel.
  7155. *
  7156. * Overwritten and set to `NearestFilter` by default.
  7157. *
  7158. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7159. * @default NearestFilter
  7160. */
  7161. this.magFilter = NearestFilter;
  7162. /**
  7163. * How the texture is sampled when a texel covers less than one pixel.
  7164. *
  7165. * Overwritten and set to `NearestFilter` by default.
  7166. *
  7167. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7168. * @default NearestFilter
  7169. */
  7170. this.minFilter = NearestFilter;
  7171. /**
  7172. * This defines how the texture is wrapped in the depth and corresponds to
  7173. * *W* in UVW mapping.
  7174. *
  7175. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7176. * @default ClampToEdgeWrapping
  7177. */
  7178. this.wrapR = ClampToEdgeWrapping;
  7179. /**
  7180. * Whether to generate mipmaps (if possible) for a texture.
  7181. *
  7182. * Overwritten and set to `false` by default.
  7183. *
  7184. * @type {boolean}
  7185. * @default false
  7186. */
  7187. this.generateMipmaps = false;
  7188. /**
  7189. * If set to `true`, the texture is flipped along the vertical axis when
  7190. * uploaded to the GPU.
  7191. *
  7192. * Overwritten and set to `false` by default.
  7193. *
  7194. * @type {boolean}
  7195. * @default false
  7196. */
  7197. this.flipY = false;
  7198. /**
  7199. * Specifies the alignment requirements for the start of each pixel row in memory.
  7200. *
  7201. * Overwritten and set to `1` by default.
  7202. *
  7203. * @type {boolean}
  7204. * @default 1
  7205. */
  7206. this.unpackAlignment = 1;
  7207. /**
  7208. * A set of all layers which need to be updated in the texture.
  7209. *
  7210. * @type {Set<number>}
  7211. */
  7212. this.layerUpdates = new Set();
  7213. }
  7214. /**
  7215. * Describes that a specific layer of the texture needs to be updated.
  7216. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  7217. * entire data texture array is sent to the GPU. Marking specific
  7218. * layers will only transmit subsets of all mipmaps associated with a
  7219. * specific depth in the array which is often much more performant.
  7220. *
  7221. * @param {number} layerIndex - The layer index that should be updated.
  7222. */
  7223. addLayerUpdate( layerIndex ) {
  7224. this.layerUpdates.add( layerIndex );
  7225. }
  7226. /**
  7227. * Resets the layer updates registry.
  7228. */
  7229. clearLayerUpdates() {
  7230. this.layerUpdates.clear();
  7231. }
  7232. }
  7233. /**
  7234. * An array render target used in context of {@link WebGLRenderer}.
  7235. *
  7236. * @augments WebGLRenderTarget
  7237. */
  7238. class WebGLArrayRenderTarget extends WebGLRenderTarget {
  7239. /**
  7240. * Constructs a new array render target.
  7241. *
  7242. * @param {number} [width=1] - The width of the render target.
  7243. * @param {number} [height=1] - The height of the render target.
  7244. * @param {number} [depth=1] - The height of the render target.
  7245. * @param {RenderTarget~Options} [options] - The configuration object.
  7246. */
  7247. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7248. super( width, height, options );
  7249. /**
  7250. * This flag can be used for type testing.
  7251. *
  7252. * @type {boolean}
  7253. * @readonly
  7254. * @default true
  7255. */
  7256. this.isWebGLArrayRenderTarget = true;
  7257. this.depth = depth;
  7258. /**
  7259. * Overwritten with a different texture type.
  7260. *
  7261. * @type {DataArrayTexture}
  7262. */
  7263. this.texture = new DataArrayTexture( null, width, height, depth );
  7264. this._setTextureOptions( options );
  7265. this.texture.isRenderTargetTexture = true;
  7266. }
  7267. }
  7268. /**
  7269. * Creates a three-dimensional texture from raw data, with parameters to
  7270. * divide it into width, height, and depth.
  7271. *
  7272. * @augments Texture
  7273. */
  7274. class Data3DTexture extends Texture {
  7275. /**
  7276. * Constructs a new data array texture.
  7277. *
  7278. * @param {?TypedArray} [data=null] - The buffer data.
  7279. * @param {number} [width=1] - The width of the texture.
  7280. * @param {number} [height=1] - The height of the texture.
  7281. * @param {number} [depth=1] - The depth of the texture.
  7282. */
  7283. constructor( data = null, width = 1, height = 1, depth = 1 ) {
  7284. // We're going to add .setXXX() methods for setting properties later.
  7285. // Users can still set in Data3DTexture directly.
  7286. //
  7287. // const texture = new THREE.Data3DTexture( data, width, height, depth );
  7288. // texture.anisotropy = 16;
  7289. //
  7290. // See #14839
  7291. super( null );
  7292. /**
  7293. * This flag can be used for type testing.
  7294. *
  7295. * @type {boolean}
  7296. * @readonly
  7297. * @default true
  7298. */
  7299. this.isData3DTexture = true;
  7300. /**
  7301. * The image definition of a data texture.
  7302. *
  7303. * @type {{data:TypedArray,width:number,height:number,depth:number}}
  7304. */
  7305. this.image = { data, width, height, depth };
  7306. /**
  7307. * How the texture is sampled when a texel covers more than one pixel.
  7308. *
  7309. * Overwritten and set to `NearestFilter` by default.
  7310. *
  7311. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7312. * @default NearestFilter
  7313. */
  7314. this.magFilter = NearestFilter;
  7315. /**
  7316. * How the texture is sampled when a texel covers less than one pixel.
  7317. *
  7318. * Overwritten and set to `NearestFilter` by default.
  7319. *
  7320. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  7321. * @default NearestFilter
  7322. */
  7323. this.minFilter = NearestFilter;
  7324. /**
  7325. * This defines how the texture is wrapped in the depth and corresponds to
  7326. * *W* in UVW mapping.
  7327. *
  7328. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  7329. * @default ClampToEdgeWrapping
  7330. */
  7331. this.wrapR = ClampToEdgeWrapping;
  7332. /**
  7333. * Whether to generate mipmaps (if possible) for a texture.
  7334. *
  7335. * Overwritten and set to `false` by default.
  7336. *
  7337. * @type {boolean}
  7338. * @default false
  7339. */
  7340. this.generateMipmaps = false;
  7341. /**
  7342. * If set to `true`, the texture is flipped along the vertical axis when
  7343. * uploaded to the GPU.
  7344. *
  7345. * Overwritten and set to `false` by default.
  7346. *
  7347. * @type {boolean}
  7348. * @default false
  7349. */
  7350. this.flipY = false;
  7351. /**
  7352. * Specifies the alignment requirements for the start of each pixel row in memory.
  7353. *
  7354. * Overwritten and set to `1` by default.
  7355. *
  7356. * @type {boolean}
  7357. * @default 1
  7358. */
  7359. this.unpackAlignment = 1;
  7360. }
  7361. }
  7362. /**
  7363. * A 3D render target used in context of {@link WebGLRenderer}.
  7364. *
  7365. * @augments WebGLRenderTarget
  7366. */
  7367. class WebGL3DRenderTarget extends WebGLRenderTarget {
  7368. /**
  7369. * Constructs a new 3D render target.
  7370. *
  7371. * @param {number} [width=1] - The width of the render target.
  7372. * @param {number} [height=1] - The height of the render target.
  7373. * @param {number} [depth=1] - The height of the render target.
  7374. * @param {RenderTarget~Options} [options] - The configuration object.
  7375. */
  7376. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  7377. super( width, height, options );
  7378. /**
  7379. * This flag can be used for type testing.
  7380. *
  7381. * @type {boolean}
  7382. * @readonly
  7383. * @default true
  7384. */
  7385. this.isWebGL3DRenderTarget = true;
  7386. this.depth = depth;
  7387. /**
  7388. * Overwritten with a different texture type.
  7389. *
  7390. * @type {Data3DTexture}
  7391. */
  7392. this.texture = new Data3DTexture( null, width, height, depth );
  7393. this._setTextureOptions( options );
  7394. this.texture.isRenderTargetTexture = true;
  7395. }
  7396. }
  7397. /**
  7398. * Represents an axis-aligned bounding box (AABB) in 3D space.
  7399. */
  7400. class Box3 {
  7401. /**
  7402. * Constructs a new bounding box.
  7403. *
  7404. * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box.
  7405. * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  7406. */
  7407. constructor( min = new Vector3( + Infinity, + Infinity, + Infinity ), max = new Vector3( - Infinity, - Infinity, - Infinity ) ) {
  7408. /**
  7409. * This flag can be used for type testing.
  7410. *
  7411. * @type {boolean}
  7412. * @readonly
  7413. * @default true
  7414. */
  7415. this.isBox3 = true;
  7416. /**
  7417. * The lower boundary of the box.
  7418. *
  7419. * @type {Vector3}
  7420. */
  7421. this.min = min;
  7422. /**
  7423. * The upper boundary of the box.
  7424. *
  7425. * @type {Vector3}
  7426. */
  7427. this.max = max;
  7428. }
  7429. /**
  7430. * Sets the lower and upper boundaries of this box.
  7431. * Please note that this method only copies the values from the given objects.
  7432. *
  7433. * @param {Vector3} min - The lower boundary of the box.
  7434. * @param {Vector3} max - The upper boundary of the box.
  7435. * @return {Box3} A reference to this bounding box.
  7436. */
  7437. set( min, max ) {
  7438. this.min.copy( min );
  7439. this.max.copy( max );
  7440. return this;
  7441. }
  7442. /**
  7443. * Sets the upper and lower bounds of this box so it encloses the position data
  7444. * in the given array.
  7445. *
  7446. * @param {Array<number>} array - An array holding 3D position data.
  7447. * @return {Box3} A reference to this bounding box.
  7448. */
  7449. setFromArray( array ) {
  7450. this.makeEmpty();
  7451. for ( let i = 0, il = array.length; i < il; i += 3 ) {
  7452. this.expandByPoint( _vector$b.fromArray( array, i ) );
  7453. }
  7454. return this;
  7455. }
  7456. /**
  7457. * Sets the upper and lower bounds of this box so it encloses the position data
  7458. * in the given buffer attribute.
  7459. *
  7460. * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data.
  7461. * @return {Box3} A reference to this bounding box.
  7462. */
  7463. setFromBufferAttribute( attribute ) {
  7464. this.makeEmpty();
  7465. for ( let i = 0, il = attribute.count; i < il; i ++ ) {
  7466. this.expandByPoint( _vector$b.fromBufferAttribute( attribute, i ) );
  7467. }
  7468. return this;
  7469. }
  7470. /**
  7471. * Sets the upper and lower bounds of this box so it encloses the position data
  7472. * in the given array.
  7473. *
  7474. * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}.
  7475. * @return {Box3} A reference to this bounding box.
  7476. */
  7477. setFromPoints( points ) {
  7478. this.makeEmpty();
  7479. for ( let i = 0, il = points.length; i < il; i ++ ) {
  7480. this.expandByPoint( points[ i ] );
  7481. }
  7482. return this;
  7483. }
  7484. /**
  7485. * Centers this box on the given center vector and sets this box's width, height and
  7486. * depth to the given size values.
  7487. *
  7488. * @param {Vector3} center - The center of the box.
  7489. * @param {Vector3} size - The x, y and z dimensions of the box.
  7490. * @return {Box3} A reference to this bounding box.
  7491. */
  7492. setFromCenterAndSize( center, size ) {
  7493. const halfSize = _vector$b.copy( size ).multiplyScalar( 0.5 );
  7494. this.min.copy( center ).sub( halfSize );
  7495. this.max.copy( center ).add( halfSize );
  7496. return this;
  7497. }
  7498. /**
  7499. * Computes the world-axis-aligned bounding box for the given 3D object
  7500. * (including its children), accounting for the object's, and children's,
  7501. * world transforms. The function may result in a larger box than strictly necessary.
  7502. *
  7503. * @param {Object3D} object - The 3D object to compute the bounding box for.
  7504. * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest
  7505. * world-axis-aligned bounding box at the expense of more computation.
  7506. * @return {Box3} A reference to this bounding box.
  7507. */
  7508. setFromObject( object, precise = false ) {
  7509. this.makeEmpty();
  7510. return this.expandByObject( object, precise );
  7511. }
  7512. /**
  7513. * Returns a new box with copied values from this instance.
  7514. *
  7515. * @return {Box3} A clone of this instance.
  7516. */
  7517. clone() {
  7518. return new this.constructor().copy( this );
  7519. }
  7520. /**
  7521. * Copies the values of the given box to this instance.
  7522. *
  7523. * @param {Box3} box - The box to copy.
  7524. * @return {Box3} A reference to this bounding box.
  7525. */
  7526. copy( box ) {
  7527. this.min.copy( box.min );
  7528. this.max.copy( box.max );
  7529. return this;
  7530. }
  7531. /**
  7532. * Makes this box empty which means in encloses a zero space in 3D.
  7533. *
  7534. * @return {Box3} A reference to this bounding box.
  7535. */
  7536. makeEmpty() {
  7537. this.min.x = this.min.y = this.min.z = + Infinity;
  7538. this.max.x = this.max.y = this.max.z = - Infinity;
  7539. return this;
  7540. }
  7541. /**
  7542. * Returns true if this box includes zero points within its bounds.
  7543. * Note that a box with equal lower and upper bounds still includes one
  7544. * point, the one both bounds share.
  7545. *
  7546. * @return {boolean} Whether this box is empty or not.
  7547. */
  7548. isEmpty() {
  7549. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  7550. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  7551. }
  7552. /**
  7553. * Returns the center point of this box.
  7554. *
  7555. * @param {Vector3} target - The target vector that is used to store the method's result.
  7556. * @return {Vector3} The center point.
  7557. */
  7558. getCenter( target ) {
  7559. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  7560. }
  7561. /**
  7562. * Returns the dimensions of this box.
  7563. *
  7564. * @param {Vector3} target - The target vector that is used to store the method's result.
  7565. * @return {Vector3} The size.
  7566. */
  7567. getSize( target ) {
  7568. return this.isEmpty() ? target.set( 0, 0, 0 ) : target.subVectors( this.max, this.min );
  7569. }
  7570. /**
  7571. * Expands the boundaries of this box to include the given point.
  7572. *
  7573. * @param {Vector3} point - The point that should be included by the bounding box.
  7574. * @return {Box3} A reference to this bounding box.
  7575. */
  7576. expandByPoint( point ) {
  7577. this.min.min( point );
  7578. this.max.max( point );
  7579. return this;
  7580. }
  7581. /**
  7582. * Expands this box equilaterally by the given vector. The width of this
  7583. * box will be expanded by the x component of the vector in both
  7584. * directions. The height of this box will be expanded by the y component of
  7585. * the vector in both directions. The depth of this box will be
  7586. * expanded by the z component of the vector in both directions.
  7587. *
  7588. * @param {Vector3} vector - The vector that should expand the bounding box.
  7589. * @return {Box3} A reference to this bounding box.
  7590. */
  7591. expandByVector( vector ) {
  7592. this.min.sub( vector );
  7593. this.max.add( vector );
  7594. return this;
  7595. }
  7596. /**
  7597. * Expands each dimension of the box by the given scalar. If negative, the
  7598. * dimensions of the box will be contracted.
  7599. *
  7600. * @param {number} scalar - The scalar value that should expand the bounding box.
  7601. * @return {Box3} A reference to this bounding box.
  7602. */
  7603. expandByScalar( scalar ) {
  7604. this.min.addScalar( - scalar );
  7605. this.max.addScalar( scalar );
  7606. return this;
  7607. }
  7608. /**
  7609. * Expands the boundaries of this box to include the given 3D object and
  7610. * its children, accounting for the object's, and children's, world
  7611. * transforms. The function may result in a larger box than strictly
  7612. * necessary (unless the precise parameter is set to true).
  7613. *
  7614. * @param {Object3D} object - The 3D object that should expand the bounding box.
  7615. * @param {boolean} precise - If set to `true`, the method expands the bounding box
  7616. * as little as necessary at the expense of more computation.
  7617. * @return {Box3} A reference to this bounding box.
  7618. */
  7619. expandByObject( object, precise = false ) {
  7620. // Computes the world-axis-aligned bounding box of an object (including its children),
  7621. // accounting for both the object's, and children's, world transforms
  7622. object.updateWorldMatrix( false, false );
  7623. const geometry = object.geometry;
  7624. if ( geometry !== undefined ) {
  7625. const positionAttribute = geometry.getAttribute( 'position' );
  7626. // precise AABB computation based on vertex data requires at least a position attribute.
  7627. // instancing isn't supported so far and uses the normal (conservative) code path.
  7628. if ( precise === true && positionAttribute !== undefined && object.isInstancedMesh !== true ) {
  7629. for ( let i = 0, l = positionAttribute.count; i < l; i ++ ) {
  7630. if ( object.isMesh === true ) {
  7631. object.getVertexPosition( i, _vector$b );
  7632. } else {
  7633. _vector$b.fromBufferAttribute( positionAttribute, i );
  7634. }
  7635. _vector$b.applyMatrix4( object.matrixWorld );
  7636. this.expandByPoint( _vector$b );
  7637. }
  7638. } else {
  7639. if ( object.boundingBox !== undefined ) {
  7640. // object-level bounding box
  7641. if ( object.boundingBox === null ) {
  7642. object.computeBoundingBox();
  7643. }
  7644. _box$4.copy( object.boundingBox );
  7645. } else {
  7646. // geometry-level bounding box
  7647. if ( geometry.boundingBox === null ) {
  7648. geometry.computeBoundingBox();
  7649. }
  7650. _box$4.copy( geometry.boundingBox );
  7651. }
  7652. _box$4.applyMatrix4( object.matrixWorld );
  7653. this.union( _box$4 );
  7654. }
  7655. }
  7656. const children = object.children;
  7657. for ( let i = 0, l = children.length; i < l; i ++ ) {
  7658. this.expandByObject( children[ i ], precise );
  7659. }
  7660. return this;
  7661. }
  7662. /**
  7663. * Returns `true` if the given point lies within or on the boundaries of this box.
  7664. *
  7665. * @param {Vector3} point - The point to test.
  7666. * @return {boolean} Whether the bounding box contains the given point or not.
  7667. */
  7668. containsPoint( point ) {
  7669. return point.x >= this.min.x && point.x <= this.max.x &&
  7670. point.y >= this.min.y && point.y <= this.max.y &&
  7671. point.z >= this.min.z && point.z <= this.max.z;
  7672. }
  7673. /**
  7674. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  7675. * If this box and the given one are identical, this function also returns `true`.
  7676. *
  7677. * @param {Box3} box - The bounding box to test.
  7678. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  7679. */
  7680. containsBox( box ) {
  7681. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  7682. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  7683. this.min.z <= box.min.z && box.max.z <= this.max.z;
  7684. }
  7685. /**
  7686. * Returns a point as a proportion of this box's width, height and depth.
  7687. *
  7688. * @param {Vector3} point - A point in 3D space.
  7689. * @param {Vector3} target - The target vector that is used to store the method's result.
  7690. * @return {Vector3} A point as a proportion of this box's width, height and depth.
  7691. */
  7692. getParameter( point, target ) {
  7693. // This can potentially have a divide by zero if the box
  7694. // has a size dimension of 0.
  7695. return target.set(
  7696. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  7697. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  7698. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  7699. );
  7700. }
  7701. /**
  7702. * Returns `true` if the given bounding box intersects with this bounding box.
  7703. *
  7704. * @param {Box3} box - The bounding box to test.
  7705. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  7706. */
  7707. intersectsBox( box ) {
  7708. // using 6 splitting planes to rule out intersections.
  7709. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  7710. box.max.y >= this.min.y && box.min.y <= this.max.y &&
  7711. box.max.z >= this.min.z && box.min.z <= this.max.z;
  7712. }
  7713. /**
  7714. * Returns `true` if the given bounding sphere intersects with this bounding box.
  7715. *
  7716. * @param {Sphere} sphere - The bounding sphere to test.
  7717. * @return {boolean} Whether the given bounding sphere intersects with this bounding box.
  7718. */
  7719. intersectsSphere( sphere ) {
  7720. // Find the point on the AABB closest to the sphere center.
  7721. this.clampPoint( sphere.center, _vector$b );
  7722. // If that point is inside the sphere, the AABB and sphere intersect.
  7723. return _vector$b.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  7724. }
  7725. /**
  7726. * Returns `true` if the given plane intersects with this bounding box.
  7727. *
  7728. * @param {Plane} plane - The plane to test.
  7729. * @return {boolean} Whether the given plane intersects with this bounding box.
  7730. */
  7731. intersectsPlane( plane ) {
  7732. // We compute the minimum and maximum dot product values. If those values
  7733. // are on the same side (back or front) of the plane, then there is no intersection.
  7734. let min, max;
  7735. if ( plane.normal.x > 0 ) {
  7736. min = plane.normal.x * this.min.x;
  7737. max = plane.normal.x * this.max.x;
  7738. } else {
  7739. min = plane.normal.x * this.max.x;
  7740. max = plane.normal.x * this.min.x;
  7741. }
  7742. if ( plane.normal.y > 0 ) {
  7743. min += plane.normal.y * this.min.y;
  7744. max += plane.normal.y * this.max.y;
  7745. } else {
  7746. min += plane.normal.y * this.max.y;
  7747. max += plane.normal.y * this.min.y;
  7748. }
  7749. if ( plane.normal.z > 0 ) {
  7750. min += plane.normal.z * this.min.z;
  7751. max += plane.normal.z * this.max.z;
  7752. } else {
  7753. min += plane.normal.z * this.max.z;
  7754. max += plane.normal.z * this.min.z;
  7755. }
  7756. return ( min <= - plane.constant && max >= - plane.constant );
  7757. }
  7758. /**
  7759. * Returns `true` if the given triangle intersects with this bounding box.
  7760. *
  7761. * @param {Triangle} triangle - The triangle to test.
  7762. * @return {boolean} Whether the given triangle intersects with this bounding box.
  7763. */
  7764. intersectsTriangle( triangle ) {
  7765. if ( this.isEmpty() ) {
  7766. return false;
  7767. }
  7768. // compute box center and extents
  7769. this.getCenter( _center );
  7770. _extents.subVectors( this.max, _center );
  7771. // translate triangle to aabb origin
  7772. _v0$3.subVectors( triangle.a, _center );
  7773. _v1$7.subVectors( triangle.b, _center );
  7774. _v2$4.subVectors( triangle.c, _center );
  7775. // compute edge vectors for triangle
  7776. _f0.subVectors( _v1$7, _v0$3 );
  7777. _f1.subVectors( _v2$4, _v1$7 );
  7778. _f2.subVectors( _v0$3, _v2$4 );
  7779. // test against axes that are given by cross product combinations of the edges of the triangle and the edges of the aabb
  7780. // 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
  7781. // axis_ij = u_i x f_j (u0, u1, u2 = face normals of aabb = x,y,z axes vectors since aabb is axis aligned)
  7782. let axes = [
  7783. 0, - _f0.z, _f0.y, 0, - _f1.z, _f1.y, 0, - _f2.z, _f2.y,
  7784. _f0.z, 0, - _f0.x, _f1.z, 0, - _f1.x, _f2.z, 0, - _f2.x,
  7785. - _f0.y, _f0.x, 0, - _f1.y, _f1.x, 0, - _f2.y, _f2.x, 0
  7786. ];
  7787. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7788. return false;
  7789. }
  7790. // test 3 face normals from the aabb
  7791. axes = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ];
  7792. if ( ! satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents ) ) {
  7793. return false;
  7794. }
  7795. // finally testing the face normal of the triangle
  7796. // use already existing triangle edge vectors here
  7797. _triangleNormal.crossVectors( _f0, _f1 );
  7798. axes = [ _triangleNormal.x, _triangleNormal.y, _triangleNormal.z ];
  7799. return satForAxes( axes, _v0$3, _v1$7, _v2$4, _extents );
  7800. }
  7801. /**
  7802. * Clamps the given point within the bounds of this box.
  7803. *
  7804. * @param {Vector3} point - The point to clamp.
  7805. * @param {Vector3} target - The target vector that is used to store the method's result.
  7806. * @return {Vector3} The clamped point.
  7807. */
  7808. clampPoint( point, target ) {
  7809. return target.copy( point ).clamp( this.min, this.max );
  7810. }
  7811. /**
  7812. * Returns the euclidean distance from any edge of this box to the specified point. If
  7813. * the given point lies inside of this box, the distance will be `0`.
  7814. *
  7815. * @param {Vector3} point - The point to compute the distance to.
  7816. * @return {number} The euclidean distance.
  7817. */
  7818. distanceToPoint( point ) {
  7819. return this.clampPoint( point, _vector$b ).distanceTo( point );
  7820. }
  7821. /**
  7822. * Returns a bounding sphere that encloses this bounding box.
  7823. *
  7824. * @param {Sphere} target - The target sphere that is used to store the method's result.
  7825. * @return {Sphere} The bounding sphere that encloses this bounding box.
  7826. */
  7827. getBoundingSphere( target ) {
  7828. if ( this.isEmpty() ) {
  7829. target.makeEmpty();
  7830. } else {
  7831. this.getCenter( target.center );
  7832. target.radius = this.getSize( _vector$b ).length() * 0.5;
  7833. }
  7834. return target;
  7835. }
  7836. /**
  7837. * Computes the intersection of this bounding box and the given one, setting the upper
  7838. * bound of this box to the lesser of the two boxes' upper bounds and the
  7839. * lower bound of this box to the greater of the two boxes' lower bounds. If
  7840. * there's no overlap, makes this box empty.
  7841. *
  7842. * @param {Box3} box - The bounding box to intersect with.
  7843. * @return {Box3} A reference to this bounding box.
  7844. */
  7845. intersect( box ) {
  7846. this.min.max( box.min );
  7847. this.max.min( box.max );
  7848. // 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.
  7849. if ( this.isEmpty() ) this.makeEmpty();
  7850. return this;
  7851. }
  7852. /**
  7853. * Computes the union of this box and another and the given one, setting the upper
  7854. * bound of this box to the greater of the two boxes' upper bounds and the
  7855. * lower bound of this box to the lesser of the two boxes' lower bounds.
  7856. *
  7857. * @param {Box3} box - The bounding box that will be unioned with this instance.
  7858. * @return {Box3} A reference to this bounding box.
  7859. */
  7860. union( box ) {
  7861. this.min.min( box.min );
  7862. this.max.max( box.max );
  7863. return this;
  7864. }
  7865. /**
  7866. * Transforms this bounding box by the given 4x4 transformation matrix.
  7867. *
  7868. * @param {Matrix4} matrix - The transformation matrix.
  7869. * @return {Box3} A reference to this bounding box.
  7870. */
  7871. applyMatrix4( matrix ) {
  7872. // transform of empty box is an empty box.
  7873. if ( this.isEmpty() ) return this;
  7874. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  7875. _points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  7876. _points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  7877. _points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  7878. _points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  7879. _points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  7880. _points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  7881. _points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  7882. _points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  7883. this.setFromPoints( _points );
  7884. return this;
  7885. }
  7886. /**
  7887. * Adds the given offset to both the upper and lower bounds of this bounding box,
  7888. * effectively moving it in 3D space.
  7889. *
  7890. * @param {Vector3} offset - The offset that should be used to translate the bounding box.
  7891. * @return {Box3} A reference to this bounding box.
  7892. */
  7893. translate( offset ) {
  7894. this.min.add( offset );
  7895. this.max.add( offset );
  7896. return this;
  7897. }
  7898. /**
  7899. * Returns `true` if this bounding box is equal with the given one.
  7900. *
  7901. * @param {Box3} box - The box to test for equality.
  7902. * @return {boolean} Whether this bounding box is equal with the given one.
  7903. */
  7904. equals( box ) {
  7905. return box.min.equals( this.min ) && box.max.equals( this.max );
  7906. }
  7907. /**
  7908. * Returns a serialized structure of the bounding box.
  7909. *
  7910. * @return {Object} Serialized structure with fields representing the object state.
  7911. */
  7912. toJSON() {
  7913. return {
  7914. min: this.min.toArray(),
  7915. max: this.max.toArray()
  7916. };
  7917. }
  7918. /**
  7919. * Returns a serialized structure of the bounding box.
  7920. *
  7921. * @param {Object} json - The serialized json to set the box from.
  7922. * @return {Box3} A reference to this bounding box.
  7923. */
  7924. fromJSON( json ) {
  7925. this.min.fromArray( json.min );
  7926. this.max.fromArray( json.max );
  7927. return this;
  7928. }
  7929. }
  7930. const _points = [
  7931. /*@__PURE__*/ new Vector3(),
  7932. /*@__PURE__*/ new Vector3(),
  7933. /*@__PURE__*/ new Vector3(),
  7934. /*@__PURE__*/ new Vector3(),
  7935. /*@__PURE__*/ new Vector3(),
  7936. /*@__PURE__*/ new Vector3(),
  7937. /*@__PURE__*/ new Vector3(),
  7938. /*@__PURE__*/ new Vector3()
  7939. ];
  7940. const _vector$b = /*@__PURE__*/ new Vector3();
  7941. const _box$4 = /*@__PURE__*/ new Box3();
  7942. // triangle centered vertices
  7943. const _v0$3 = /*@__PURE__*/ new Vector3();
  7944. const _v1$7 = /*@__PURE__*/ new Vector3();
  7945. const _v2$4 = /*@__PURE__*/ new Vector3();
  7946. // triangle edge vectors
  7947. const _f0 = /*@__PURE__*/ new Vector3();
  7948. const _f1 = /*@__PURE__*/ new Vector3();
  7949. const _f2 = /*@__PURE__*/ new Vector3();
  7950. const _center = /*@__PURE__*/ new Vector3();
  7951. const _extents = /*@__PURE__*/ new Vector3();
  7952. const _triangleNormal = /*@__PURE__*/ new Vector3();
  7953. const _testAxis = /*@__PURE__*/ new Vector3();
  7954. function satForAxes( axes, v0, v1, v2, extents ) {
  7955. for ( let i = 0, j = axes.length - 3; i <= j; i += 3 ) {
  7956. _testAxis.fromArray( axes, i );
  7957. // project the aabb onto the separating axis
  7958. const r = extents.x * Math.abs( _testAxis.x ) + extents.y * Math.abs( _testAxis.y ) + extents.z * Math.abs( _testAxis.z );
  7959. // project all 3 vertices of the triangle onto the separating axis
  7960. const p0 = v0.dot( _testAxis );
  7961. const p1 = v1.dot( _testAxis );
  7962. const p2 = v2.dot( _testAxis );
  7963. // actual test, basically see if either of the most extreme of the triangle points intersects r
  7964. if ( Math.max( - Math.max( p0, p1, p2 ), Math.min( p0, p1, p2 ) ) > r ) {
  7965. // points of the projected triangle are outside the projected half-length of the aabb
  7966. // the axis is separating and we can exit
  7967. return false;
  7968. }
  7969. }
  7970. return true;
  7971. }
  7972. const _box$3 = /*@__PURE__*/ new Box3();
  7973. const _v1$6 = /*@__PURE__*/ new Vector3();
  7974. const _v2$3 = /*@__PURE__*/ new Vector3();
  7975. /**
  7976. * An analytical 3D sphere defined by a center and radius. This class is mainly
  7977. * used as a Bounding Sphere for 3D objects.
  7978. */
  7979. class Sphere {
  7980. /**
  7981. * Constructs a new sphere.
  7982. *
  7983. * @param {Vector3} [center=(0,0,0)] - The center of the sphere
  7984. * @param {number} [radius=-1] - The radius of the sphere.
  7985. */
  7986. constructor( center = new Vector3(), radius = -1 ) {
  7987. /**
  7988. * This flag can be used for type testing.
  7989. *
  7990. * @type {boolean}
  7991. * @readonly
  7992. * @default true
  7993. */
  7994. this.isSphere = true;
  7995. /**
  7996. * The center of the sphere
  7997. *
  7998. * @type {Vector3}
  7999. */
  8000. this.center = center;
  8001. /**
  8002. * The radius of the sphere.
  8003. *
  8004. * @type {number}
  8005. */
  8006. this.radius = radius;
  8007. }
  8008. /**
  8009. * Sets the sphere's components by copying the given values.
  8010. *
  8011. * @param {Vector3} center - The center.
  8012. * @param {number} radius - The radius.
  8013. * @return {Sphere} A reference to this sphere.
  8014. */
  8015. set( center, radius ) {
  8016. this.center.copy( center );
  8017. this.radius = radius;
  8018. return this;
  8019. }
  8020. /**
  8021. * Computes the minimum bounding sphere for list of points.
  8022. * If the optional center point is given, it is used as the sphere's
  8023. * center. Otherwise, the center of the axis-aligned bounding box
  8024. * encompassing the points is calculated.
  8025. *
  8026. * @param {Array<Vector3>} points - A list of points in 3D space.
  8027. * @param {Vector3} [optionalCenter] - The center of the sphere.
  8028. * @return {Sphere} A reference to this sphere.
  8029. */
  8030. setFromPoints( points, optionalCenter ) {
  8031. const center = this.center;
  8032. if ( optionalCenter !== undefined ) {
  8033. center.copy( optionalCenter );
  8034. } else {
  8035. _box$3.setFromPoints( points ).getCenter( center );
  8036. }
  8037. let maxRadiusSq = 0;
  8038. for ( let i = 0, il = points.length; i < il; i ++ ) {
  8039. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  8040. }
  8041. this.radius = Math.sqrt( maxRadiusSq );
  8042. return this;
  8043. }
  8044. /**
  8045. * Copies the values of the given sphere to this instance.
  8046. *
  8047. * @param {Sphere} sphere - The sphere to copy.
  8048. * @return {Sphere} A reference to this sphere.
  8049. */
  8050. copy( sphere ) {
  8051. this.center.copy( sphere.center );
  8052. this.radius = sphere.radius;
  8053. return this;
  8054. }
  8055. /**
  8056. * Returns `true` if the sphere is empty (the radius set to a negative number).
  8057. *
  8058. * Spheres with a radius of `0` contain only their center point and are not
  8059. * considered to be empty.
  8060. *
  8061. * @return {boolean} Whether this sphere is empty or not.
  8062. */
  8063. isEmpty() {
  8064. return ( this.radius < 0 );
  8065. }
  8066. /**
  8067. * Makes this sphere empty which means in encloses a zero space in 3D.
  8068. *
  8069. * @return {Sphere} A reference to this sphere.
  8070. */
  8071. makeEmpty() {
  8072. this.center.set( 0, 0, 0 );
  8073. this.radius = -1;
  8074. return this;
  8075. }
  8076. /**
  8077. * Returns `true` if this sphere contains the given point inclusive of
  8078. * the surface of the sphere.
  8079. *
  8080. * @param {Vector3} point - The point to check.
  8081. * @return {boolean} Whether this sphere contains the given point or not.
  8082. */
  8083. containsPoint( point ) {
  8084. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  8085. }
  8086. /**
  8087. * Returns the closest distance from the boundary of the sphere to the
  8088. * given point. If the sphere contains the point, the distance will
  8089. * be negative.
  8090. *
  8091. * @param {Vector3} point - The point to compute the distance to.
  8092. * @return {number} The distance to the point.
  8093. */
  8094. distanceToPoint( point ) {
  8095. return ( point.distanceTo( this.center ) - this.radius );
  8096. }
  8097. /**
  8098. * Returns `true` if this sphere intersects with the given one.
  8099. *
  8100. * @param {Sphere} sphere - The sphere to test.
  8101. * @return {boolean} Whether this sphere intersects with the given one or not.
  8102. */
  8103. intersectsSphere( sphere ) {
  8104. const radiusSum = this.radius + sphere.radius;
  8105. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  8106. }
  8107. /**
  8108. * Returns `true` if this sphere intersects with the given box.
  8109. *
  8110. * @param {Box3} box - The box to test.
  8111. * @return {boolean} Whether this sphere intersects with the given box or not.
  8112. */
  8113. intersectsBox( box ) {
  8114. return box.intersectsSphere( this );
  8115. }
  8116. /**
  8117. * Returns `true` if this sphere intersects with the given plane.
  8118. *
  8119. * @param {Plane} plane - The plane to test.
  8120. * @return {boolean} Whether this sphere intersects with the given plane or not.
  8121. */
  8122. intersectsPlane( plane ) {
  8123. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  8124. }
  8125. /**
  8126. * Clamps a point within the sphere. If the point is outside the sphere, it
  8127. * will clamp it to the closest point on the edge of the sphere. Points
  8128. * already inside the sphere will not be affected.
  8129. *
  8130. * @param {Vector3} point - The plane to clamp.
  8131. * @param {Vector3} target - The target vector that is used to store the method's result.
  8132. * @return {Vector3} The clamped point.
  8133. */
  8134. clampPoint( point, target ) {
  8135. const deltaLengthSq = this.center.distanceToSquared( point );
  8136. target.copy( point );
  8137. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  8138. target.sub( this.center ).normalize();
  8139. target.multiplyScalar( this.radius ).add( this.center );
  8140. }
  8141. return target;
  8142. }
  8143. /**
  8144. * Returns a bounding box that encloses this sphere.
  8145. *
  8146. * @param {Box3} target - The target box that is used to store the method's result.
  8147. * @return {Box3} The bounding box that encloses this sphere.
  8148. */
  8149. getBoundingBox( target ) {
  8150. if ( this.isEmpty() ) {
  8151. // Empty sphere produces empty bounding box
  8152. target.makeEmpty();
  8153. return target;
  8154. }
  8155. target.set( this.center, this.center );
  8156. target.expandByScalar( this.radius );
  8157. return target;
  8158. }
  8159. /**
  8160. * Transforms this sphere with the given 4x4 transformation matrix.
  8161. *
  8162. * @param {Matrix4} matrix - The transformation matrix.
  8163. * @return {Sphere} A reference to this sphere.
  8164. */
  8165. applyMatrix4( matrix ) {
  8166. this.center.applyMatrix4( matrix );
  8167. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  8168. return this;
  8169. }
  8170. /**
  8171. * Translates the sphere's center by the given offset.
  8172. *
  8173. * @param {Vector3} offset - The offset.
  8174. * @return {Sphere} A reference to this sphere.
  8175. */
  8176. translate( offset ) {
  8177. this.center.add( offset );
  8178. return this;
  8179. }
  8180. /**
  8181. * Expands the boundaries of this sphere to include the given point.
  8182. *
  8183. * @param {Vector3} point - The point to include.
  8184. * @return {Sphere} A reference to this sphere.
  8185. */
  8186. expandByPoint( point ) {
  8187. if ( this.isEmpty() ) {
  8188. this.center.copy( point );
  8189. this.radius = 0;
  8190. return this;
  8191. }
  8192. _v1$6.subVectors( point, this.center );
  8193. const lengthSq = _v1$6.lengthSq();
  8194. if ( lengthSq > ( this.radius * this.radius ) ) {
  8195. // calculate the minimal sphere
  8196. const length = Math.sqrt( lengthSq );
  8197. const delta = ( length - this.radius ) * 0.5;
  8198. this.center.addScaledVector( _v1$6, delta / length );
  8199. this.radius += delta;
  8200. }
  8201. return this;
  8202. }
  8203. /**
  8204. * Expands this sphere to enclose both the original sphere and the given sphere.
  8205. *
  8206. * @param {Sphere} sphere - The sphere to include.
  8207. * @return {Sphere} A reference to this sphere.
  8208. */
  8209. union( sphere ) {
  8210. if ( sphere.isEmpty() ) {
  8211. return this;
  8212. }
  8213. if ( this.isEmpty() ) {
  8214. this.copy( sphere );
  8215. return this;
  8216. }
  8217. if ( this.center.equals( sphere.center ) === true ) {
  8218. this.radius = Math.max( this.radius, sphere.radius );
  8219. } else {
  8220. _v2$3.subVectors( sphere.center, this.center ).setLength( sphere.radius );
  8221. this.expandByPoint( _v1$6.copy( sphere.center ).add( _v2$3 ) );
  8222. this.expandByPoint( _v1$6.copy( sphere.center ).sub( _v2$3 ) );
  8223. }
  8224. return this;
  8225. }
  8226. /**
  8227. * Returns `true` if this sphere is equal with the given one.
  8228. *
  8229. * @param {Sphere} sphere - The sphere to test for equality.
  8230. * @return {boolean} Whether this bounding sphere is equal with the given one.
  8231. */
  8232. equals( sphere ) {
  8233. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  8234. }
  8235. /**
  8236. * Returns a new sphere with copied values from this instance.
  8237. *
  8238. * @return {Sphere} A clone of this instance.
  8239. */
  8240. clone() {
  8241. return new this.constructor().copy( this );
  8242. }
  8243. /**
  8244. * Returns a serialized structure of the bounding sphere.
  8245. *
  8246. * @return {Object} Serialized structure with fields representing the object state.
  8247. */
  8248. toJSON() {
  8249. return {
  8250. radius: this.radius,
  8251. center: this.center.toArray()
  8252. };
  8253. }
  8254. /**
  8255. * Returns a serialized structure of the bounding sphere.
  8256. *
  8257. * @param {Object} json - The serialized json to set the sphere from.
  8258. * @return {Box3} A reference to this bounding sphere.
  8259. */
  8260. fromJSON( json ) {
  8261. this.radius = json.radius;
  8262. this.center.fromArray( json.center );
  8263. return this;
  8264. }
  8265. }
  8266. const _vector$a = /*@__PURE__*/ new Vector3();
  8267. const _segCenter = /*@__PURE__*/ new Vector3();
  8268. const _segDir = /*@__PURE__*/ new Vector3();
  8269. const _diff = /*@__PURE__*/ new Vector3();
  8270. const _edge1 = /*@__PURE__*/ new Vector3();
  8271. const _edge2 = /*@__PURE__*/ new Vector3();
  8272. const _normal$1 = /*@__PURE__*/ new Vector3();
  8273. /**
  8274. * A ray that emits from an origin in a certain direction. The class is used by
  8275. * {@link Raycaster} to assist with raycasting. Raycasting is used for
  8276. * mouse picking (working out what objects in the 3D space the mouse is over)
  8277. * amongst other things.
  8278. */
  8279. class Ray {
  8280. /**
  8281. * Constructs a new ray.
  8282. *
  8283. * @param {Vector3} [origin=(0,0,0)] - The origin of the ray.
  8284. * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray.
  8285. */
  8286. constructor( origin = new Vector3(), direction = new Vector3( 0, 0, -1 ) ) {
  8287. /**
  8288. * The origin of the ray.
  8289. *
  8290. * @type {Vector3}
  8291. */
  8292. this.origin = origin;
  8293. /**
  8294. * The (normalized) direction of the ray.
  8295. *
  8296. * @type {Vector3}
  8297. */
  8298. this.direction = direction;
  8299. }
  8300. /**
  8301. * Sets the ray's components by copying the given values.
  8302. *
  8303. * @param {Vector3} origin - The origin.
  8304. * @param {Vector3} direction - The direction.
  8305. * @return {Ray} A reference to this ray.
  8306. */
  8307. set( origin, direction ) {
  8308. this.origin.copy( origin );
  8309. this.direction.copy( direction );
  8310. return this;
  8311. }
  8312. /**
  8313. * Copies the values of the given ray to this instance.
  8314. *
  8315. * @param {Ray} ray - The ray to copy.
  8316. * @return {Ray} A reference to this ray.
  8317. */
  8318. copy( ray ) {
  8319. this.origin.copy( ray.origin );
  8320. this.direction.copy( ray.direction );
  8321. return this;
  8322. }
  8323. /**
  8324. * Returns a vector that is located at a given distance along this ray.
  8325. *
  8326. * @param {number} t - The distance along the ray to retrieve a position for.
  8327. * @param {Vector3} target - The target vector that is used to store the method's result.
  8328. * @return {Vector3} A position on the ray.
  8329. */
  8330. at( t, target ) {
  8331. return target.copy( this.origin ).addScaledVector( this.direction, t );
  8332. }
  8333. /**
  8334. * Adjusts the direction of the ray to point at the given vector in world space.
  8335. *
  8336. * @param {Vector3} v - The target position.
  8337. * @return {Ray} A reference to this ray.
  8338. */
  8339. lookAt( v ) {
  8340. this.direction.copy( v ).sub( this.origin ).normalize();
  8341. return this;
  8342. }
  8343. /**
  8344. * Shift the origin of this ray along its direction by the given distance.
  8345. *
  8346. * @param {number} t - The distance along the ray to interpolate.
  8347. * @return {Ray} A reference to this ray.
  8348. */
  8349. recast( t ) {
  8350. this.origin.copy( this.at( t, _vector$a ) );
  8351. return this;
  8352. }
  8353. /**
  8354. * Returns the point along this ray that is closest to the given point.
  8355. *
  8356. * @param {Vector3} point - A point in 3D space to get the closet location on the ray for.
  8357. * @param {Vector3} target - The target vector that is used to store the method's result.
  8358. * @return {Vector3} The closest point on this ray.
  8359. */
  8360. closestPointToPoint( point, target ) {
  8361. target.subVectors( point, this.origin );
  8362. const directionDistance = target.dot( this.direction );
  8363. if ( directionDistance < 0 ) {
  8364. return target.copy( this.origin );
  8365. }
  8366. return target.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8367. }
  8368. /**
  8369. * Returns the distance of the closest approach between this ray and the given point.
  8370. *
  8371. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8372. * @return {number} The distance.
  8373. */
  8374. distanceToPoint( point ) {
  8375. return Math.sqrt( this.distanceSqToPoint( point ) );
  8376. }
  8377. /**
  8378. * Returns the squared distance of the closest approach between this ray and the given point.
  8379. *
  8380. * @param {Vector3} point - A point in 3D space to compute the distance to.
  8381. * @return {number} The squared distance.
  8382. */
  8383. distanceSqToPoint( point ) {
  8384. const directionDistance = _vector$a.subVectors( point, this.origin ).dot( this.direction );
  8385. // point behind the ray
  8386. if ( directionDistance < 0 ) {
  8387. return this.origin.distanceToSquared( point );
  8388. }
  8389. _vector$a.copy( this.origin ).addScaledVector( this.direction, directionDistance );
  8390. return _vector$a.distanceToSquared( point );
  8391. }
  8392. /**
  8393. * Returns the squared distance between this ray and the given line segment.
  8394. *
  8395. * @param {Vector3} v0 - The start point of the line segment.
  8396. * @param {Vector3} v1 - The end point of the line segment.
  8397. * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment.
  8398. * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray.
  8399. * @return {number} The squared distance.
  8400. */
  8401. distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  8402. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteDistRaySegment.h
  8403. // It returns the min distance between the ray and the segment
  8404. // defined by v0 and v1
  8405. // It can also set two optional targets :
  8406. // - The closest point on the ray
  8407. // - The closest point on the segment
  8408. _segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  8409. _segDir.copy( v1 ).sub( v0 ).normalize();
  8410. _diff.copy( this.origin ).sub( _segCenter );
  8411. const segExtent = v0.distanceTo( v1 ) * 0.5;
  8412. const a01 = - this.direction.dot( _segDir );
  8413. const b0 = _diff.dot( this.direction );
  8414. const b1 = - _diff.dot( _segDir );
  8415. const c = _diff.lengthSq();
  8416. const det = Math.abs( 1 - a01 * a01 );
  8417. let s0, s1, sqrDist, extDet;
  8418. if ( det > 0 ) {
  8419. // The ray and segment are not parallel.
  8420. s0 = a01 * b1 - b0;
  8421. s1 = a01 * b0 - b1;
  8422. extDet = segExtent * det;
  8423. if ( s0 >= 0 ) {
  8424. if ( s1 >= - extDet ) {
  8425. if ( s1 <= extDet ) {
  8426. // region 0
  8427. // Minimum at interior points of ray and segment.
  8428. const invDet = 1 / det;
  8429. s0 *= invDet;
  8430. s1 *= invDet;
  8431. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  8432. } else {
  8433. // region 1
  8434. s1 = segExtent;
  8435. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8436. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8437. }
  8438. } else {
  8439. // region 5
  8440. s1 = - segExtent;
  8441. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8442. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8443. }
  8444. } else {
  8445. if ( s1 <= - extDet ) {
  8446. // region 4
  8447. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  8448. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8449. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8450. } else if ( s1 <= extDet ) {
  8451. // region 3
  8452. s0 = 0;
  8453. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8454. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  8455. } else {
  8456. // region 2
  8457. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  8458. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  8459. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8460. }
  8461. }
  8462. } else {
  8463. // Ray and segment are parallel.
  8464. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  8465. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  8466. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  8467. }
  8468. if ( optionalPointOnRay ) {
  8469. optionalPointOnRay.copy( this.origin ).addScaledVector( this.direction, s0 );
  8470. }
  8471. if ( optionalPointOnSegment ) {
  8472. optionalPointOnSegment.copy( _segCenter ).addScaledVector( _segDir, s1 );
  8473. }
  8474. return sqrDist;
  8475. }
  8476. /**
  8477. * Intersects this ray with the given sphere, returning the intersection
  8478. * point or `null` if there is no intersection.
  8479. *
  8480. * @param {Sphere} sphere - The sphere to intersect.
  8481. * @param {Vector3} target - The target vector that is used to store the method's result.
  8482. * @return {?Vector3} The intersection point.
  8483. */
  8484. intersectSphere( sphere, target ) {
  8485. _vector$a.subVectors( sphere.center, this.origin );
  8486. const tca = _vector$a.dot( this.direction );
  8487. const d2 = _vector$a.dot( _vector$a ) - tca * tca;
  8488. const radius2 = sphere.radius * sphere.radius;
  8489. if ( d2 > radius2 ) return null;
  8490. const thc = Math.sqrt( radius2 - d2 );
  8491. // t0 = first intersect point - entrance on front of sphere
  8492. const t0 = tca - thc;
  8493. // t1 = second intersect point - exit point on back of sphere
  8494. const t1 = tca + thc;
  8495. // test to see if t1 is behind the ray - if so, return null
  8496. if ( t1 < 0 ) return null;
  8497. // test to see if t0 is behind the ray:
  8498. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  8499. // in order to always return an intersect point that is in front of the ray.
  8500. if ( t0 < 0 ) return this.at( t1, target );
  8501. // else t0 is in front of the ray, so return the first collision point scaled by t0
  8502. return this.at( t0, target );
  8503. }
  8504. /**
  8505. * Returns `true` if this ray intersects with the given sphere.
  8506. *
  8507. * @param {Sphere} sphere - The sphere to intersect.
  8508. * @return {boolean} Whether this ray intersects with the given sphere or not.
  8509. */
  8510. intersectsSphere( sphere ) {
  8511. if ( sphere.radius < 0 ) return false; // handle empty spheres, see #31187
  8512. return this.distanceSqToPoint( sphere.center ) <= ( sphere.radius * sphere.radius );
  8513. }
  8514. /**
  8515. * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray
  8516. * does not intersect with the plane.
  8517. *
  8518. * @param {Plane} plane - The plane to compute the distance to.
  8519. * @return {?number} Whether this ray intersects with the given sphere or not.
  8520. */
  8521. distanceToPlane( plane ) {
  8522. const denominator = plane.normal.dot( this.direction );
  8523. if ( denominator === 0 ) {
  8524. // line is coplanar, return origin
  8525. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  8526. return 0;
  8527. }
  8528. // Null is preferable to undefined since undefined means.... it is undefined
  8529. return null;
  8530. }
  8531. const t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  8532. // Return if the ray never intersects the plane
  8533. return t >= 0 ? t : null;
  8534. }
  8535. /**
  8536. * Intersects this ray with the given plane, returning the intersection
  8537. * point or `null` if there is no intersection.
  8538. *
  8539. * @param {Plane} plane - The plane to intersect.
  8540. * @param {Vector3} target - The target vector that is used to store the method's result.
  8541. * @return {?Vector3} The intersection point.
  8542. */
  8543. intersectPlane( plane, target ) {
  8544. const t = this.distanceToPlane( plane );
  8545. if ( t === null ) {
  8546. return null;
  8547. }
  8548. return this.at( t, target );
  8549. }
  8550. /**
  8551. * Returns `true` if this ray intersects with the given plane.
  8552. *
  8553. * @param {Plane} plane - The plane to intersect.
  8554. * @return {boolean} Whether this ray intersects with the given plane or not.
  8555. */
  8556. intersectsPlane( plane ) {
  8557. // check if the ray lies on the plane first
  8558. const distToPoint = plane.distanceToPoint( this.origin );
  8559. if ( distToPoint === 0 ) {
  8560. return true;
  8561. }
  8562. const denominator = plane.normal.dot( this.direction );
  8563. if ( denominator * distToPoint < 0 ) {
  8564. return true;
  8565. }
  8566. // ray origin is behind the plane (and is pointing behind it)
  8567. return false;
  8568. }
  8569. /**
  8570. * Intersects this ray with the given bounding box, returning the intersection
  8571. * point or `null` if there is no intersection.
  8572. *
  8573. * @param {Box3} box - The box to intersect.
  8574. * @param {Vector3} target - The target vector that is used to store the method's result.
  8575. * @return {?Vector3} The intersection point.
  8576. */
  8577. intersectBox( box, target ) {
  8578. let tmin, tmax, tymin, tymax, tzmin, tzmax;
  8579. const invdirx = 1 / this.direction.x,
  8580. invdiry = 1 / this.direction.y,
  8581. invdirz = 1 / this.direction.z;
  8582. const origin = this.origin;
  8583. if ( invdirx >= 0 ) {
  8584. tmin = ( box.min.x - origin.x ) * invdirx;
  8585. tmax = ( box.max.x - origin.x ) * invdirx;
  8586. } else {
  8587. tmin = ( box.max.x - origin.x ) * invdirx;
  8588. tmax = ( box.min.x - origin.x ) * invdirx;
  8589. }
  8590. if ( invdiry >= 0 ) {
  8591. tymin = ( box.min.y - origin.y ) * invdiry;
  8592. tymax = ( box.max.y - origin.y ) * invdiry;
  8593. } else {
  8594. tymin = ( box.max.y - origin.y ) * invdiry;
  8595. tymax = ( box.min.y - origin.y ) * invdiry;
  8596. }
  8597. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  8598. if ( tymin > tmin || isNaN( tmin ) ) tmin = tymin;
  8599. if ( tymax < tmax || isNaN( tmax ) ) tmax = tymax;
  8600. if ( invdirz >= 0 ) {
  8601. tzmin = ( box.min.z - origin.z ) * invdirz;
  8602. tzmax = ( box.max.z - origin.z ) * invdirz;
  8603. } else {
  8604. tzmin = ( box.max.z - origin.z ) * invdirz;
  8605. tzmax = ( box.min.z - origin.z ) * invdirz;
  8606. }
  8607. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  8608. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  8609. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  8610. //return point closest to the ray (positive side)
  8611. if ( tmax < 0 ) return null;
  8612. return this.at( tmin >= 0 ? tmin : tmax, target );
  8613. }
  8614. /**
  8615. * Returns `true` if this ray intersects with the given box.
  8616. *
  8617. * @param {Box3} box - The box to intersect.
  8618. * @return {boolean} Whether this ray intersects with the given box or not.
  8619. */
  8620. intersectsBox( box ) {
  8621. return this.intersectBox( box, _vector$a ) !== null;
  8622. }
  8623. /**
  8624. * Intersects this ray with the given triangle, returning the intersection
  8625. * point or `null` if there is no intersection.
  8626. *
  8627. * @param {Vector3} a - The first vertex of the triangle.
  8628. * @param {Vector3} b - The second vertex of the triangle.
  8629. * @param {Vector3} c - The third vertex of the triangle.
  8630. * @param {boolean} backfaceCulling - Whether to use backface culling or not.
  8631. * @param {Vector3} target - The target vector that is used to store the method's result.
  8632. * @return {?Vector3} The intersection point.
  8633. */
  8634. intersectTriangle( a, b, c, backfaceCulling, target ) {
  8635. // Compute the offset origin, edges, and normal.
  8636. // from https://github.com/pmjoniak/GeometricTools/blob/master/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  8637. _edge1.subVectors( b, a );
  8638. _edge2.subVectors( c, a );
  8639. _normal$1.crossVectors( _edge1, _edge2 );
  8640. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  8641. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  8642. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  8643. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  8644. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  8645. let DdN = this.direction.dot( _normal$1 );
  8646. let sign;
  8647. if ( DdN > 0 ) {
  8648. if ( backfaceCulling ) return null;
  8649. sign = 1;
  8650. } else if ( DdN < 0 ) {
  8651. sign = -1;
  8652. DdN = - DdN;
  8653. } else {
  8654. return null;
  8655. }
  8656. _diff.subVectors( this.origin, a );
  8657. const DdQxE2 = sign * this.direction.dot( _edge2.crossVectors( _diff, _edge2 ) );
  8658. // b1 < 0, no intersection
  8659. if ( DdQxE2 < 0 ) {
  8660. return null;
  8661. }
  8662. const DdE1xQ = sign * this.direction.dot( _edge1.cross( _diff ) );
  8663. // b2 < 0, no intersection
  8664. if ( DdE1xQ < 0 ) {
  8665. return null;
  8666. }
  8667. // b1+b2 > 1, no intersection
  8668. if ( DdQxE2 + DdE1xQ > DdN ) {
  8669. return null;
  8670. }
  8671. // Line intersects triangle, check if ray does.
  8672. const QdN = - sign * _diff.dot( _normal$1 );
  8673. // t < 0, no intersection
  8674. if ( QdN < 0 ) {
  8675. return null;
  8676. }
  8677. // Ray intersects triangle.
  8678. return this.at( QdN / DdN, target );
  8679. }
  8680. /**
  8681. * Transforms this ray with the given 4x4 transformation matrix.
  8682. *
  8683. * @param {Matrix4} matrix4 - The transformation matrix.
  8684. * @return {Ray} A reference to this ray.
  8685. */
  8686. applyMatrix4( matrix4 ) {
  8687. this.origin.applyMatrix4( matrix4 );
  8688. this.direction.transformDirection( matrix4 );
  8689. return this;
  8690. }
  8691. /**
  8692. * Returns `true` if this ray is equal with the given one.
  8693. *
  8694. * @param {Ray} ray - The ray to test for equality.
  8695. * @return {boolean} Whether this ray is equal with the given one.
  8696. */
  8697. equals( ray ) {
  8698. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  8699. }
  8700. /**
  8701. * Returns a new ray with copied values from this instance.
  8702. *
  8703. * @return {Ray} A clone of this instance.
  8704. */
  8705. clone() {
  8706. return new this.constructor().copy( this );
  8707. }
  8708. }
  8709. /**
  8710. * Represents a 4x4 matrix.
  8711. *
  8712. * The most common use of a 4x4 matrix in 3D computer graphics is as a transformation matrix.
  8713. * For an introduction to transformation matrices as used in WebGL, check out [this tutorial](https://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices)
  8714. *
  8715. * This allows a 3D vector representing a point in 3D space to undergo
  8716. * transformations such as translation, rotation, shear, scale, reflection,
  8717. * orthogonal or perspective projection and so on, by being multiplied by the
  8718. * matrix. This is known as `applying` the matrix to the vector.
  8719. *
  8720. * A Note on Row-Major and Column-Major Ordering:
  8721. *
  8722. * The constructor and {@link Matrix3#set} method take arguments in
  8723. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  8724. * order, while internally they are stored in the {@link Matrix3#elements} array in column-major order.
  8725. * This means that calling:
  8726. * ```js
  8727. * const m = new THREE.Matrix4();
  8728. * m.set( 11, 12, 13, 14,
  8729. * 21, 22, 23, 24,
  8730. * 31, 32, 33, 34,
  8731. * 41, 42, 43, 44 );
  8732. * ```
  8733. * will result in the elements array containing:
  8734. * ```js
  8735. * m.elements = [ 11, 21, 31, 41,
  8736. * 12, 22, 32, 42,
  8737. * 13, 23, 33, 43,
  8738. * 14, 24, 34, 44 ];
  8739. * ```
  8740. * and internally all calculations are performed using column-major ordering.
  8741. * However, as the actual ordering makes no difference mathematically and
  8742. * most people are used to thinking about matrices in row-major order, the
  8743. * three.js documentation shows matrices in row-major order. Just bear in
  8744. * mind that if you are reading the source code, you'll have to take the
  8745. * transpose of any matrices outlined here to make sense of the calculations.
  8746. */
  8747. class Matrix4 {
  8748. /**
  8749. * Constructs a new 4x4 matrix. The arguments are supposed to be
  8750. * in row-major order. If no arguments are provided, the constructor
  8751. * initializes the matrix as an identity matrix.
  8752. *
  8753. * @param {number} [n11] - 1-1 matrix element.
  8754. * @param {number} [n12] - 1-2 matrix element.
  8755. * @param {number} [n13] - 1-3 matrix element.
  8756. * @param {number} [n14] - 1-4 matrix element.
  8757. * @param {number} [n21] - 2-1 matrix element.
  8758. * @param {number} [n22] - 2-2 matrix element.
  8759. * @param {number} [n23] - 2-3 matrix element.
  8760. * @param {number} [n24] - 2-4 matrix element.
  8761. * @param {number} [n31] - 3-1 matrix element.
  8762. * @param {number} [n32] - 3-2 matrix element.
  8763. * @param {number} [n33] - 3-3 matrix element.
  8764. * @param {number} [n34] - 3-4 matrix element.
  8765. * @param {number} [n41] - 4-1 matrix element.
  8766. * @param {number} [n42] - 4-2 matrix element.
  8767. * @param {number} [n43] - 4-3 matrix element.
  8768. * @param {number} [n44] - 4-4 matrix element.
  8769. */
  8770. constructor( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8771. /**
  8772. * This flag can be used for type testing.
  8773. *
  8774. * @type {boolean}
  8775. * @readonly
  8776. * @default true
  8777. */
  8778. Matrix4.prototype.isMatrix4 = true;
  8779. /**
  8780. * A column-major list of matrix values.
  8781. *
  8782. * @type {Array<number>}
  8783. */
  8784. this.elements = [
  8785. 1, 0, 0, 0,
  8786. 0, 1, 0, 0,
  8787. 0, 0, 1, 0,
  8788. 0, 0, 0, 1
  8789. ];
  8790. if ( n11 !== undefined ) {
  8791. this.set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 );
  8792. }
  8793. }
  8794. /**
  8795. * Sets the elements of the matrix.The arguments are supposed to be
  8796. * in row-major order.
  8797. *
  8798. * @param {number} [n11] - 1-1 matrix element.
  8799. * @param {number} [n12] - 1-2 matrix element.
  8800. * @param {number} [n13] - 1-3 matrix element.
  8801. * @param {number} [n14] - 1-4 matrix element.
  8802. * @param {number} [n21] - 2-1 matrix element.
  8803. * @param {number} [n22] - 2-2 matrix element.
  8804. * @param {number} [n23] - 2-3 matrix element.
  8805. * @param {number} [n24] - 2-4 matrix element.
  8806. * @param {number} [n31] - 3-1 matrix element.
  8807. * @param {number} [n32] - 3-2 matrix element.
  8808. * @param {number} [n33] - 3-3 matrix element.
  8809. * @param {number} [n34] - 3-4 matrix element.
  8810. * @param {number} [n41] - 4-1 matrix element.
  8811. * @param {number} [n42] - 4-2 matrix element.
  8812. * @param {number} [n43] - 4-3 matrix element.
  8813. * @param {number} [n44] - 4-4 matrix element.
  8814. * @return {Matrix4} A reference to this matrix.
  8815. */
  8816. set( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  8817. const te = this.elements;
  8818. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  8819. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  8820. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  8821. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  8822. return this;
  8823. }
  8824. /**
  8825. * Sets this matrix to the 4x4 identity matrix.
  8826. *
  8827. * @return {Matrix4} A reference to this matrix.
  8828. */
  8829. identity() {
  8830. this.set(
  8831. 1, 0, 0, 0,
  8832. 0, 1, 0, 0,
  8833. 0, 0, 1, 0,
  8834. 0, 0, 0, 1
  8835. );
  8836. return this;
  8837. }
  8838. /**
  8839. * Returns a matrix with copied values from this instance.
  8840. *
  8841. * @return {Matrix4} A clone of this instance.
  8842. */
  8843. clone() {
  8844. return new Matrix4().fromArray( this.elements );
  8845. }
  8846. /**
  8847. * Copies the values of the given matrix to this instance.
  8848. *
  8849. * @param {Matrix4} m - The matrix to copy.
  8850. * @return {Matrix4} A reference to this matrix.
  8851. */
  8852. copy( m ) {
  8853. const te = this.elements;
  8854. const me = m.elements;
  8855. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  8856. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  8857. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  8858. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  8859. return this;
  8860. }
  8861. /**
  8862. * Copies the translation component of the given matrix
  8863. * into this matrix's translation component.
  8864. *
  8865. * @param {Matrix4} m - The matrix to copy the translation component.
  8866. * @return {Matrix4} A reference to this matrix.
  8867. */
  8868. copyPosition( m ) {
  8869. const te = this.elements, me = m.elements;
  8870. te[ 12 ] = me[ 12 ];
  8871. te[ 13 ] = me[ 13 ];
  8872. te[ 14 ] = me[ 14 ];
  8873. return this;
  8874. }
  8875. /**
  8876. * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix.
  8877. *
  8878. * @param {Matrix3} m - The 3x3 matrix.
  8879. * @return {Matrix4} A reference to this matrix.
  8880. */
  8881. setFromMatrix3( m ) {
  8882. const me = m.elements;
  8883. this.set(
  8884. me[ 0 ], me[ 3 ], me[ 6 ], 0,
  8885. me[ 1 ], me[ 4 ], me[ 7 ], 0,
  8886. me[ 2 ], me[ 5 ], me[ 8 ], 0,
  8887. 0, 0, 0, 1
  8888. );
  8889. return this;
  8890. }
  8891. /**
  8892. * Extracts the basis of this matrix into the three axis vectors provided.
  8893. *
  8894. * @param {Vector3} xAxis - The basis's x axis.
  8895. * @param {Vector3} yAxis - The basis's y axis.
  8896. * @param {Vector3} zAxis - The basis's z axis.
  8897. * @return {Matrix4} A reference to this matrix.
  8898. */
  8899. extractBasis( xAxis, yAxis, zAxis ) {
  8900. xAxis.setFromMatrixColumn( this, 0 );
  8901. yAxis.setFromMatrixColumn( this, 1 );
  8902. zAxis.setFromMatrixColumn( this, 2 );
  8903. return this;
  8904. }
  8905. /**
  8906. * Sets the given basis vectors to this matrix.
  8907. *
  8908. * @param {Vector3} xAxis - The basis's x axis.
  8909. * @param {Vector3} yAxis - The basis's y axis.
  8910. * @param {Vector3} zAxis - The basis's z axis.
  8911. * @return {Matrix4} A reference to this matrix.
  8912. */
  8913. makeBasis( xAxis, yAxis, zAxis ) {
  8914. this.set(
  8915. xAxis.x, yAxis.x, zAxis.x, 0,
  8916. xAxis.y, yAxis.y, zAxis.y, 0,
  8917. xAxis.z, yAxis.z, zAxis.z, 0,
  8918. 0, 0, 0, 1
  8919. );
  8920. return this;
  8921. }
  8922. /**
  8923. * Extracts the rotation component of the given matrix
  8924. * into this matrix's rotation component.
  8925. *
  8926. * Note: This method does not support reflection matrices.
  8927. *
  8928. * @param {Matrix4} m - The matrix.
  8929. * @return {Matrix4} A reference to this matrix.
  8930. */
  8931. extractRotation( m ) {
  8932. const te = this.elements;
  8933. const me = m.elements;
  8934. const scaleX = 1 / _v1$5.setFromMatrixColumn( m, 0 ).length();
  8935. const scaleY = 1 / _v1$5.setFromMatrixColumn( m, 1 ).length();
  8936. const scaleZ = 1 / _v1$5.setFromMatrixColumn( m, 2 ).length();
  8937. te[ 0 ] = me[ 0 ] * scaleX;
  8938. te[ 1 ] = me[ 1 ] * scaleX;
  8939. te[ 2 ] = me[ 2 ] * scaleX;
  8940. te[ 3 ] = 0;
  8941. te[ 4 ] = me[ 4 ] * scaleY;
  8942. te[ 5 ] = me[ 5 ] * scaleY;
  8943. te[ 6 ] = me[ 6 ] * scaleY;
  8944. te[ 7 ] = 0;
  8945. te[ 8 ] = me[ 8 ] * scaleZ;
  8946. te[ 9 ] = me[ 9 ] * scaleZ;
  8947. te[ 10 ] = me[ 10 ] * scaleZ;
  8948. te[ 11 ] = 0;
  8949. te[ 12 ] = 0;
  8950. te[ 13 ] = 0;
  8951. te[ 14 ] = 0;
  8952. te[ 15 ] = 1;
  8953. return this;
  8954. }
  8955. /**
  8956. * Sets the rotation component (the upper left 3x3 matrix) of this matrix to
  8957. * the rotation specified by the given Euler angles. The rest of
  8958. * the matrix is set to the identity. Depending on the {@link Euler#order},
  8959. * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix)
  8960. * for a complete list.
  8961. *
  8962. * @param {Euler} euler - The Euler angles.
  8963. * @return {Matrix4} A reference to this matrix.
  8964. */
  8965. makeRotationFromEuler( euler ) {
  8966. const te = this.elements;
  8967. const x = euler.x, y = euler.y, z = euler.z;
  8968. const a = Math.cos( x ), b = Math.sin( x );
  8969. const c = Math.cos( y ), d = Math.sin( y );
  8970. const e = Math.cos( z ), f = Math.sin( z );
  8971. if ( euler.order === 'XYZ' ) {
  8972. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  8973. te[ 0 ] = c * e;
  8974. te[ 4 ] = - c * f;
  8975. te[ 8 ] = d;
  8976. te[ 1 ] = af + be * d;
  8977. te[ 5 ] = ae - bf * d;
  8978. te[ 9 ] = - b * c;
  8979. te[ 2 ] = bf - ae * d;
  8980. te[ 6 ] = be + af * d;
  8981. te[ 10 ] = a * c;
  8982. } else if ( euler.order === 'YXZ' ) {
  8983. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8984. te[ 0 ] = ce + df * b;
  8985. te[ 4 ] = de * b - cf;
  8986. te[ 8 ] = a * d;
  8987. te[ 1 ] = a * f;
  8988. te[ 5 ] = a * e;
  8989. te[ 9 ] = - b;
  8990. te[ 2 ] = cf * b - de;
  8991. te[ 6 ] = df + ce * b;
  8992. te[ 10 ] = a * c;
  8993. } else if ( euler.order === 'ZXY' ) {
  8994. const ce = c * e, cf = c * f, de = d * e, df = d * f;
  8995. te[ 0 ] = ce - df * b;
  8996. te[ 4 ] = - a * f;
  8997. te[ 8 ] = de + cf * b;
  8998. te[ 1 ] = cf + de * b;
  8999. te[ 5 ] = a * e;
  9000. te[ 9 ] = df - ce * b;
  9001. te[ 2 ] = - a * d;
  9002. te[ 6 ] = b;
  9003. te[ 10 ] = a * c;
  9004. } else if ( euler.order === 'ZYX' ) {
  9005. const ae = a * e, af = a * f, be = b * e, bf = b * f;
  9006. te[ 0 ] = c * e;
  9007. te[ 4 ] = be * d - af;
  9008. te[ 8 ] = ae * d + bf;
  9009. te[ 1 ] = c * f;
  9010. te[ 5 ] = bf * d + ae;
  9011. te[ 9 ] = af * d - be;
  9012. te[ 2 ] = - d;
  9013. te[ 6 ] = b * c;
  9014. te[ 10 ] = a * c;
  9015. } else if ( euler.order === 'YZX' ) {
  9016. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9017. te[ 0 ] = c * e;
  9018. te[ 4 ] = bd - ac * f;
  9019. te[ 8 ] = bc * f + ad;
  9020. te[ 1 ] = f;
  9021. te[ 5 ] = a * e;
  9022. te[ 9 ] = - b * e;
  9023. te[ 2 ] = - d * e;
  9024. te[ 6 ] = ad * f + bc;
  9025. te[ 10 ] = ac - bd * f;
  9026. } else if ( euler.order === 'XZY' ) {
  9027. const ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  9028. te[ 0 ] = c * e;
  9029. te[ 4 ] = - f;
  9030. te[ 8 ] = d * e;
  9031. te[ 1 ] = ac * f + bd;
  9032. te[ 5 ] = a * e;
  9033. te[ 9 ] = ad * f - bc;
  9034. te[ 2 ] = bc * f - ad;
  9035. te[ 6 ] = b * e;
  9036. te[ 10 ] = bd * f + ac;
  9037. }
  9038. // bottom row
  9039. te[ 3 ] = 0;
  9040. te[ 7 ] = 0;
  9041. te[ 11 ] = 0;
  9042. // last column
  9043. te[ 12 ] = 0;
  9044. te[ 13 ] = 0;
  9045. te[ 14 ] = 0;
  9046. te[ 15 ] = 1;
  9047. return this;
  9048. }
  9049. /**
  9050. * Sets the rotation component of this matrix to the rotation specified by
  9051. * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion)
  9052. * The rest of the matrix is set to the identity.
  9053. *
  9054. * @param {Quaternion} q - The Quaternion.
  9055. * @return {Matrix4} A reference to this matrix.
  9056. */
  9057. makeRotationFromQuaternion( q ) {
  9058. return this.compose( _zero, q, _one );
  9059. }
  9060. /**
  9061. * Sets the rotation component of the transformation matrix, looking from `eye` towards
  9062. * `target`, and oriented by the up-direction.
  9063. *
  9064. * @param {Vector3} eye - The eye vector.
  9065. * @param {Vector3} target - The target vector.
  9066. * @param {Vector3} up - The up vector.
  9067. * @return {Matrix4} A reference to this matrix.
  9068. */
  9069. lookAt( eye, target, up ) {
  9070. const te = this.elements;
  9071. _z.subVectors( eye, target );
  9072. if ( _z.lengthSq() === 0 ) {
  9073. // eye and target are in the same position
  9074. _z.z = 1;
  9075. }
  9076. _z.normalize();
  9077. _x.crossVectors( up, _z );
  9078. if ( _x.lengthSq() === 0 ) {
  9079. // up and z are parallel
  9080. if ( Math.abs( up.z ) === 1 ) {
  9081. _z.x += 0.0001;
  9082. } else {
  9083. _z.z += 0.0001;
  9084. }
  9085. _z.normalize();
  9086. _x.crossVectors( up, _z );
  9087. }
  9088. _x.normalize();
  9089. _y.crossVectors( _z, _x );
  9090. te[ 0 ] = _x.x; te[ 4 ] = _y.x; te[ 8 ] = _z.x;
  9091. te[ 1 ] = _x.y; te[ 5 ] = _y.y; te[ 9 ] = _z.y;
  9092. te[ 2 ] = _x.z; te[ 6 ] = _y.z; te[ 10 ] = _z.z;
  9093. return this;
  9094. }
  9095. /**
  9096. * Post-multiplies this matrix by the given 4x4 matrix.
  9097. *
  9098. * @param {Matrix4} m - The matrix to multiply with.
  9099. * @return {Matrix4} A reference to this matrix.
  9100. */
  9101. multiply( m ) {
  9102. return this.multiplyMatrices( this, m );
  9103. }
  9104. /**
  9105. * Pre-multiplies this matrix by the given 4x4 matrix.
  9106. *
  9107. * @param {Matrix4} m - The matrix to multiply with.
  9108. * @return {Matrix4} A reference to this matrix.
  9109. */
  9110. premultiply( m ) {
  9111. return this.multiplyMatrices( m, this );
  9112. }
  9113. /**
  9114. * Multiples the given 4x4 matrices and stores the result
  9115. * in this matrix.
  9116. *
  9117. * @param {Matrix4} a - The first matrix.
  9118. * @param {Matrix4} b - The second matrix.
  9119. * @return {Matrix4} A reference to this matrix.
  9120. */
  9121. multiplyMatrices( a, b ) {
  9122. const ae = a.elements;
  9123. const be = b.elements;
  9124. const te = this.elements;
  9125. const a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  9126. const a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  9127. const a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  9128. const a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  9129. const b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  9130. const b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  9131. const b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  9132. const b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  9133. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  9134. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  9135. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  9136. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  9137. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  9138. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  9139. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  9140. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  9141. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  9142. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  9143. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  9144. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  9145. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  9146. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  9147. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  9148. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  9149. return this;
  9150. }
  9151. /**
  9152. * Multiplies every component of the matrix by the given scalar.
  9153. *
  9154. * @param {number} s - The scalar.
  9155. * @return {Matrix4} A reference to this matrix.
  9156. */
  9157. multiplyScalar( s ) {
  9158. const te = this.elements;
  9159. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  9160. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  9161. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  9162. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  9163. return this;
  9164. }
  9165. /**
  9166. * Computes and returns the determinant of this matrix.
  9167. *
  9168. * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html).
  9169. *
  9170. * @return {number} The determinant.
  9171. */
  9172. determinant() {
  9173. const te = this.elements;
  9174. const n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  9175. const n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  9176. const n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  9177. const n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  9178. const t11 = n23 * n34 - n24 * n33;
  9179. const t12 = n22 * n34 - n24 * n32;
  9180. const t13 = n22 * n33 - n23 * n32;
  9181. const t21 = n21 * n34 - n24 * n31;
  9182. const t22 = n21 * n33 - n23 * n31;
  9183. const t23 = n21 * n32 - n22 * n31;
  9184. return n11 * ( n42 * t11 - n43 * t12 + n44 * t13 ) -
  9185. n12 * ( n41 * t11 - n43 * t21 + n44 * t22 ) +
  9186. n13 * ( n41 * t12 - n42 * t21 + n44 * t23 ) -
  9187. n14 * ( n41 * t13 - n42 * t22 + n43 * t23 );
  9188. }
  9189. /**
  9190. * Transposes this matrix in place.
  9191. *
  9192. * @return {Matrix4} A reference to this matrix.
  9193. */
  9194. transpose() {
  9195. const te = this.elements;
  9196. let tmp;
  9197. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  9198. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  9199. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  9200. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  9201. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  9202. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  9203. return this;
  9204. }
  9205. /**
  9206. * Sets the position component for this matrix from the given vector,
  9207. * without affecting the rest of the matrix.
  9208. *
  9209. * @param {number|Vector3} x - The x component of the vector or alternatively the vector object.
  9210. * @param {number} y - The y component of the vector.
  9211. * @param {number} z - The z component of the vector.
  9212. * @return {Matrix4} A reference to this matrix.
  9213. */
  9214. setPosition( x, y, z ) {
  9215. const te = this.elements;
  9216. if ( x.isVector3 ) {
  9217. te[ 12 ] = x.x;
  9218. te[ 13 ] = x.y;
  9219. te[ 14 ] = x.z;
  9220. } else {
  9221. te[ 12 ] = x;
  9222. te[ 13 ] = y;
  9223. te[ 14 ] = z;
  9224. }
  9225. return this;
  9226. }
  9227. /**
  9228. * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution).
  9229. * You can not invert with a determinant of zero. If you attempt this, the method produces
  9230. * a zero matrix instead.
  9231. *
  9232. * @return {Matrix4} A reference to this matrix.
  9233. */
  9234. invert() {
  9235. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  9236. const te = this.elements,
  9237. n11 = te[ 0 ], n21 = te[ 1 ], n31 = te[ 2 ], n41 = te[ 3 ],
  9238. n12 = te[ 4 ], n22 = te[ 5 ], n32 = te[ 6 ], n42 = te[ 7 ],
  9239. n13 = te[ 8 ], n23 = te[ 9 ], n33 = te[ 10 ], n43 = te[ 11 ],
  9240. n14 = te[ 12 ], n24 = te[ 13 ], n34 = te[ 14 ], n44 = te[ 15 ],
  9241. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  9242. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  9243. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  9244. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  9245. const det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  9246. if ( det === 0 ) return this.set( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 );
  9247. const detInv = 1 / det;
  9248. te[ 0 ] = t11 * detInv;
  9249. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  9250. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  9251. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  9252. te[ 4 ] = t12 * detInv;
  9253. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  9254. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  9255. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  9256. te[ 8 ] = t13 * detInv;
  9257. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  9258. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  9259. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  9260. te[ 12 ] = t14 * detInv;
  9261. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  9262. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  9263. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  9264. return this;
  9265. }
  9266. /**
  9267. * Multiplies the columns of this matrix by the given vector.
  9268. *
  9269. * @param {Vector3} v - The scale vector.
  9270. * @return {Matrix4} A reference to this matrix.
  9271. */
  9272. scale( v ) {
  9273. const te = this.elements;
  9274. const x = v.x, y = v.y, z = v.z;
  9275. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  9276. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  9277. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  9278. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  9279. return this;
  9280. }
  9281. /**
  9282. * Gets the maximum scale value of the three axes.
  9283. *
  9284. * @return {number} The maximum scale.
  9285. */
  9286. getMaxScaleOnAxis() {
  9287. const te = this.elements;
  9288. const scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  9289. const scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  9290. const scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  9291. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  9292. }
  9293. /**
  9294. * Sets this matrix as a translation transform from the given vector.
  9295. *
  9296. * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector.
  9297. * @param {number} y - The amount to translate in the Y axis.
  9298. * @param {number} z - The amount to translate in the z axis.
  9299. * @return {Matrix4} A reference to this matrix.
  9300. */
  9301. makeTranslation( x, y, z ) {
  9302. if ( x.isVector3 ) {
  9303. this.set(
  9304. 1, 0, 0, x.x,
  9305. 0, 1, 0, x.y,
  9306. 0, 0, 1, x.z,
  9307. 0, 0, 0, 1
  9308. );
  9309. } else {
  9310. this.set(
  9311. 1, 0, 0, x,
  9312. 0, 1, 0, y,
  9313. 0, 0, 1, z,
  9314. 0, 0, 0, 1
  9315. );
  9316. }
  9317. return this;
  9318. }
  9319. /**
  9320. * Sets this matrix as a rotational transformation around the X axis by
  9321. * the given angle.
  9322. *
  9323. * @param {number} theta - The rotation in radians.
  9324. * @return {Matrix4} A reference to this matrix.
  9325. */
  9326. makeRotationX( theta ) {
  9327. const c = Math.cos( theta ), s = Math.sin( theta );
  9328. this.set(
  9329. 1, 0, 0, 0,
  9330. 0, c, - s, 0,
  9331. 0, s, c, 0,
  9332. 0, 0, 0, 1
  9333. );
  9334. return this;
  9335. }
  9336. /**
  9337. * Sets this matrix as a rotational transformation around the Y axis by
  9338. * the given angle.
  9339. *
  9340. * @param {number} theta - The rotation in radians.
  9341. * @return {Matrix4} A reference to this matrix.
  9342. */
  9343. makeRotationY( theta ) {
  9344. const c = Math.cos( theta ), s = Math.sin( theta );
  9345. this.set(
  9346. c, 0, s, 0,
  9347. 0, 1, 0, 0,
  9348. - s, 0, c, 0,
  9349. 0, 0, 0, 1
  9350. );
  9351. return this;
  9352. }
  9353. /**
  9354. * Sets this matrix as a rotational transformation around the Z axis by
  9355. * the given angle.
  9356. *
  9357. * @param {number} theta - The rotation in radians.
  9358. * @return {Matrix4} A reference to this matrix.
  9359. */
  9360. makeRotationZ( theta ) {
  9361. const c = Math.cos( theta ), s = Math.sin( theta );
  9362. this.set(
  9363. c, - s, 0, 0,
  9364. s, c, 0, 0,
  9365. 0, 0, 1, 0,
  9366. 0, 0, 0, 1
  9367. );
  9368. return this;
  9369. }
  9370. /**
  9371. * Sets this matrix as a rotational transformation around the given axis by
  9372. * the given angle.
  9373. *
  9374. * This is a somewhat controversial but mathematically sound alternative to
  9375. * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199).
  9376. *
  9377. * @param {Vector3} axis - The normalized rotation axis.
  9378. * @param {number} angle - The rotation in radians.
  9379. * @return {Matrix4} A reference to this matrix.
  9380. */
  9381. makeRotationAxis( axis, angle ) {
  9382. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  9383. const c = Math.cos( angle );
  9384. const s = Math.sin( angle );
  9385. const t = 1 - c;
  9386. const x = axis.x, y = axis.y, z = axis.z;
  9387. const tx = t * x, ty = t * y;
  9388. this.set(
  9389. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  9390. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  9391. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  9392. 0, 0, 0, 1
  9393. );
  9394. return this;
  9395. }
  9396. /**
  9397. * Sets this matrix as a scale transformation.
  9398. *
  9399. * @param {number} x - The amount to scale in the X axis.
  9400. * @param {number} y - The amount to scale in the Y axis.
  9401. * @param {number} z - The amount to scale in the Z axis.
  9402. * @return {Matrix4} A reference to this matrix.
  9403. */
  9404. makeScale( x, y, z ) {
  9405. this.set(
  9406. x, 0, 0, 0,
  9407. 0, y, 0, 0,
  9408. 0, 0, z, 0,
  9409. 0, 0, 0, 1
  9410. );
  9411. return this;
  9412. }
  9413. /**
  9414. * Sets this matrix as a shear transformation.
  9415. *
  9416. * @param {number} xy - The amount to shear X by Y.
  9417. * @param {number} xz - The amount to shear X by Z.
  9418. * @param {number} yx - The amount to shear Y by X.
  9419. * @param {number} yz - The amount to shear Y by Z.
  9420. * @param {number} zx - The amount to shear Z by X.
  9421. * @param {number} zy - The amount to shear Z by Y.
  9422. * @return {Matrix4} A reference to this matrix.
  9423. */
  9424. makeShear( xy, xz, yx, yz, zx, zy ) {
  9425. this.set(
  9426. 1, yx, zx, 0,
  9427. xy, 1, zy, 0,
  9428. xz, yz, 1, 0,
  9429. 0, 0, 0, 1
  9430. );
  9431. return this;
  9432. }
  9433. /**
  9434. * Sets this matrix to the transformation composed of the given position,
  9435. * rotation (Quaternion) and scale.
  9436. *
  9437. * @param {Vector3} position - The position vector.
  9438. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9439. * @param {Vector3} scale - The scale vector.
  9440. * @return {Matrix4} A reference to this matrix.
  9441. */
  9442. compose( position, quaternion, scale ) {
  9443. const te = this.elements;
  9444. const x = quaternion._x, y = quaternion._y, z = quaternion._z, w = quaternion._w;
  9445. const x2 = x + x, y2 = y + y, z2 = z + z;
  9446. const xx = x * x2, xy = x * y2, xz = x * z2;
  9447. const yy = y * y2, yz = y * z2, zz = z * z2;
  9448. const wx = w * x2, wy = w * y2, wz = w * z2;
  9449. const sx = scale.x, sy = scale.y, sz = scale.z;
  9450. te[ 0 ] = ( 1 - ( yy + zz ) ) * sx;
  9451. te[ 1 ] = ( xy + wz ) * sx;
  9452. te[ 2 ] = ( xz - wy ) * sx;
  9453. te[ 3 ] = 0;
  9454. te[ 4 ] = ( xy - wz ) * sy;
  9455. te[ 5 ] = ( 1 - ( xx + zz ) ) * sy;
  9456. te[ 6 ] = ( yz + wx ) * sy;
  9457. te[ 7 ] = 0;
  9458. te[ 8 ] = ( xz + wy ) * sz;
  9459. te[ 9 ] = ( yz - wx ) * sz;
  9460. te[ 10 ] = ( 1 - ( xx + yy ) ) * sz;
  9461. te[ 11 ] = 0;
  9462. te[ 12 ] = position.x;
  9463. te[ 13 ] = position.y;
  9464. te[ 14 ] = position.z;
  9465. te[ 15 ] = 1;
  9466. return this;
  9467. }
  9468. /**
  9469. * Decomposes this matrix into its position, rotation and scale components
  9470. * and provides the result in the given objects.
  9471. *
  9472. * Note: Not all matrices are decomposable in this way. For example, if an
  9473. * object has a non-uniformly scaled parent, then the object's world matrix
  9474. * may not be decomposable, and this method may not be appropriate.
  9475. *
  9476. * @param {Vector3} position - The position vector.
  9477. * @param {Quaternion} quaternion - The rotation as a Quaternion.
  9478. * @param {Vector3} scale - The scale vector.
  9479. * @return {Matrix4} A reference to this matrix.
  9480. */
  9481. decompose( position, quaternion, scale ) {
  9482. const te = this.elements;
  9483. let sx = _v1$5.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  9484. const sy = _v1$5.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  9485. const sz = _v1$5.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  9486. // if determine is negative, we need to invert one scale
  9487. const det = this.determinant();
  9488. if ( det < 0 ) sx = - sx;
  9489. position.x = te[ 12 ];
  9490. position.y = te[ 13 ];
  9491. position.z = te[ 14 ];
  9492. // scale the rotation part
  9493. _m1$4.copy( this );
  9494. const invSX = 1 / sx;
  9495. const invSY = 1 / sy;
  9496. const invSZ = 1 / sz;
  9497. _m1$4.elements[ 0 ] *= invSX;
  9498. _m1$4.elements[ 1 ] *= invSX;
  9499. _m1$4.elements[ 2 ] *= invSX;
  9500. _m1$4.elements[ 4 ] *= invSY;
  9501. _m1$4.elements[ 5 ] *= invSY;
  9502. _m1$4.elements[ 6 ] *= invSY;
  9503. _m1$4.elements[ 8 ] *= invSZ;
  9504. _m1$4.elements[ 9 ] *= invSZ;
  9505. _m1$4.elements[ 10 ] *= invSZ;
  9506. quaternion.setFromRotationMatrix( _m1$4 );
  9507. scale.x = sx;
  9508. scale.y = sy;
  9509. scale.z = sz;
  9510. return this;
  9511. }
  9512. /**
  9513. * Creates a perspective projection matrix. This is used internally by
  9514. * {@link PerspectiveCamera#updateProjectionMatrix}.
  9515. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9516. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9517. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9518. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9519. * @param {number} near - The distance from the camera to the near plane.
  9520. * @param {number} far - The distance from the camera to the far plane.
  9521. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9522. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9523. * @return {Matrix4} A reference to this matrix.
  9524. */
  9525. makePerspective( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9526. const te = this.elements;
  9527. const x = 2 * near / ( right - left );
  9528. const y = 2 * near / ( top - bottom );
  9529. const a = ( right + left ) / ( right - left );
  9530. const b = ( top + bottom ) / ( top - bottom );
  9531. let c, d;
  9532. if ( reversedDepth ) {
  9533. c = near / ( far - near );
  9534. d = ( far * near ) / ( far - near );
  9535. } else {
  9536. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9537. c = - ( far + near ) / ( far - near );
  9538. d = ( -2 * far * near ) / ( far - near );
  9539. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9540. c = - far / ( far - near );
  9541. d = ( - far * near ) / ( far - near );
  9542. } else {
  9543. throw new Error( 'THREE.Matrix4.makePerspective(): Invalid coordinate system: ' + coordinateSystem );
  9544. }
  9545. }
  9546. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  9547. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  9548. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9549. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = -1; te[ 15 ] = 0;
  9550. return this;
  9551. }
  9552. /**
  9553. * Creates a orthographic projection matrix. This is used internally by
  9554. * {@link OrthographicCamera#updateProjectionMatrix}.
  9555. * @param {number} left - Left boundary of the viewing frustum at the near plane.
  9556. * @param {number} right - Right boundary of the viewing frustum at the near plane.
  9557. * @param {number} top - Top boundary of the viewing frustum at the near plane.
  9558. * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane.
  9559. * @param {number} near - The distance from the camera to the near plane.
  9560. * @param {number} far - The distance from the camera to the far plane.
  9561. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system.
  9562. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  9563. * @return {Matrix4} A reference to this matrix.
  9564. */
  9565. makeOrthographic( left, right, top, bottom, near, far, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  9566. const te = this.elements;
  9567. const x = 2 / ( right - left );
  9568. const y = 2 / ( top - bottom );
  9569. const a = - ( right + left ) / ( right - left );
  9570. const b = - ( top + bottom ) / ( top - bottom );
  9571. let c, d;
  9572. if ( reversedDepth ) {
  9573. c = 1 / ( far - near );
  9574. d = far / ( far - near );
  9575. } else {
  9576. if ( coordinateSystem === WebGLCoordinateSystem ) {
  9577. c = -2 / ( far - near );
  9578. d = - ( far + near ) / ( far - near );
  9579. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  9580. c = -1 / ( far - near );
  9581. d = - near / ( far - near );
  9582. } else {
  9583. throw new Error( 'THREE.Matrix4.makeOrthographic(): Invalid coordinate system: ' + coordinateSystem );
  9584. }
  9585. }
  9586. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = a;
  9587. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = 0; te[ 13 ] = b;
  9588. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  9589. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  9590. return this;
  9591. }
  9592. /**
  9593. * Returns `true` if this matrix is equal with the given one.
  9594. *
  9595. * @param {Matrix4} matrix - The matrix to test for equality.
  9596. * @return {boolean} Whether this matrix is equal with the given one.
  9597. */
  9598. equals( matrix ) {
  9599. const te = this.elements;
  9600. const me = matrix.elements;
  9601. for ( let i = 0; i < 16; i ++ ) {
  9602. if ( te[ i ] !== me[ i ] ) return false;
  9603. }
  9604. return true;
  9605. }
  9606. /**
  9607. * Sets the elements of the matrix from the given array.
  9608. *
  9609. * @param {Array<number>} array - The matrix elements in column-major order.
  9610. * @param {number} [offset=0] - Index of the first element in the array.
  9611. * @return {Matrix4} A reference to this matrix.
  9612. */
  9613. fromArray( array, offset = 0 ) {
  9614. for ( let i = 0; i < 16; i ++ ) {
  9615. this.elements[ i ] = array[ i + offset ];
  9616. }
  9617. return this;
  9618. }
  9619. /**
  9620. * Writes the elements of this matrix to the given array. If no array is provided,
  9621. * the method returns a new instance.
  9622. *
  9623. * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order.
  9624. * @param {number} [offset=0] - Index of the first element in the array.
  9625. * @return {Array<number>} The matrix elements in column-major order.
  9626. */
  9627. toArray( array = [], offset = 0 ) {
  9628. const te = this.elements;
  9629. array[ offset ] = te[ 0 ];
  9630. array[ offset + 1 ] = te[ 1 ];
  9631. array[ offset + 2 ] = te[ 2 ];
  9632. array[ offset + 3 ] = te[ 3 ];
  9633. array[ offset + 4 ] = te[ 4 ];
  9634. array[ offset + 5 ] = te[ 5 ];
  9635. array[ offset + 6 ] = te[ 6 ];
  9636. array[ offset + 7 ] = te[ 7 ];
  9637. array[ offset + 8 ] = te[ 8 ];
  9638. array[ offset + 9 ] = te[ 9 ];
  9639. array[ offset + 10 ] = te[ 10 ];
  9640. array[ offset + 11 ] = te[ 11 ];
  9641. array[ offset + 12 ] = te[ 12 ];
  9642. array[ offset + 13 ] = te[ 13 ];
  9643. array[ offset + 14 ] = te[ 14 ];
  9644. array[ offset + 15 ] = te[ 15 ];
  9645. return array;
  9646. }
  9647. }
  9648. const _v1$5 = /*@__PURE__*/ new Vector3();
  9649. const _m1$4 = /*@__PURE__*/ new Matrix4();
  9650. const _zero = /*@__PURE__*/ new Vector3( 0, 0, 0 );
  9651. const _one = /*@__PURE__*/ new Vector3( 1, 1, 1 );
  9652. const _x = /*@__PURE__*/ new Vector3();
  9653. const _y = /*@__PURE__*/ new Vector3();
  9654. const _z = /*@__PURE__*/ new Vector3();
  9655. const _matrix$2 = /*@__PURE__*/ new Matrix4();
  9656. const _quaternion$3 = /*@__PURE__*/ new Quaternion();
  9657. /**
  9658. * A class representing Euler angles.
  9659. *
  9660. * Euler angles describe a rotational transformation by rotating an object on
  9661. * its various axes in specified amounts per axis, and a specified axis
  9662. * order.
  9663. *
  9664. * Iterating through an instance will yield its components (x, y, z,
  9665. * order) in the corresponding order.
  9666. *
  9667. * ```js
  9668. * const a = new THREE.Euler( 0, 1, 1.57, 'XYZ' );
  9669. * const b = new THREE.Vector3( 1, 0, 1 );
  9670. * b.applyEuler(a);
  9671. * ```
  9672. */
  9673. class Euler {
  9674. /**
  9675. * Constructs a new euler instance.
  9676. *
  9677. * @param {number} [x=0] - The angle of the x axis in radians.
  9678. * @param {number} [y=0] - The angle of the y axis in radians.
  9679. * @param {number} [z=0] - The angle of the z axis in radians.
  9680. * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied.
  9681. */
  9682. constructor( x = 0, y = 0, z = 0, order = Euler.DEFAULT_ORDER ) {
  9683. /**
  9684. * This flag can be used for type testing.
  9685. *
  9686. * @type {boolean}
  9687. * @readonly
  9688. * @default true
  9689. */
  9690. this.isEuler = true;
  9691. this._x = x;
  9692. this._y = y;
  9693. this._z = z;
  9694. this._order = order;
  9695. }
  9696. /**
  9697. * The angle of the x axis in radians.
  9698. *
  9699. * @type {number}
  9700. * @default 0
  9701. */
  9702. get x() {
  9703. return this._x;
  9704. }
  9705. set x( value ) {
  9706. this._x = value;
  9707. this._onChangeCallback();
  9708. }
  9709. /**
  9710. * The angle of the y axis in radians.
  9711. *
  9712. * @type {number}
  9713. * @default 0
  9714. */
  9715. get y() {
  9716. return this._y;
  9717. }
  9718. set y( value ) {
  9719. this._y = value;
  9720. this._onChangeCallback();
  9721. }
  9722. /**
  9723. * The angle of the z axis in radians.
  9724. *
  9725. * @type {number}
  9726. * @default 0
  9727. */
  9728. get z() {
  9729. return this._z;
  9730. }
  9731. set z( value ) {
  9732. this._z = value;
  9733. this._onChangeCallback();
  9734. }
  9735. /**
  9736. * A string representing the order that the rotations are applied.
  9737. *
  9738. * @type {string}
  9739. * @default 'XYZ'
  9740. */
  9741. get order() {
  9742. return this._order;
  9743. }
  9744. set order( value ) {
  9745. this._order = value;
  9746. this._onChangeCallback();
  9747. }
  9748. /**
  9749. * Sets the Euler components.
  9750. *
  9751. * @param {number} x - The angle of the x axis in radians.
  9752. * @param {number} y - The angle of the y axis in radians.
  9753. * @param {number} z - The angle of the z axis in radians.
  9754. * @param {string} [order] - A string representing the order that the rotations are applied.
  9755. * @return {Euler} A reference to this Euler instance.
  9756. */
  9757. set( x, y, z, order = this._order ) {
  9758. this._x = x;
  9759. this._y = y;
  9760. this._z = z;
  9761. this._order = order;
  9762. this._onChangeCallback();
  9763. return this;
  9764. }
  9765. /**
  9766. * Returns a new Euler instance with copied values from this instance.
  9767. *
  9768. * @return {Euler} A clone of this instance.
  9769. */
  9770. clone() {
  9771. return new this.constructor( this._x, this._y, this._z, this._order );
  9772. }
  9773. /**
  9774. * Copies the values of the given Euler instance to this instance.
  9775. *
  9776. * @param {Euler} euler - The Euler instance to copy.
  9777. * @return {Euler} A reference to this Euler instance.
  9778. */
  9779. copy( euler ) {
  9780. this._x = euler._x;
  9781. this._y = euler._y;
  9782. this._z = euler._z;
  9783. this._order = euler._order;
  9784. this._onChangeCallback();
  9785. return this;
  9786. }
  9787. /**
  9788. * Sets the angles of this Euler instance from a pure rotation matrix.
  9789. *
  9790. * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled).
  9791. * @param {string} [order] - A string representing the order that the rotations are applied.
  9792. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9793. * @return {Euler} A reference to this Euler instance.
  9794. */
  9795. setFromRotationMatrix( m, order = this._order, update = true ) {
  9796. const te = m.elements;
  9797. const m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  9798. const m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  9799. const m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  9800. switch ( order ) {
  9801. case 'XYZ':
  9802. this._y = Math.asin( clamp( m13, -1, 1 ) );
  9803. if ( Math.abs( m13 ) < 0.9999999 ) {
  9804. this._x = Math.atan2( - m23, m33 );
  9805. this._z = Math.atan2( - m12, m11 );
  9806. } else {
  9807. this._x = Math.atan2( m32, m22 );
  9808. this._z = 0;
  9809. }
  9810. break;
  9811. case 'YXZ':
  9812. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  9813. if ( Math.abs( m23 ) < 0.9999999 ) {
  9814. this._y = Math.atan2( m13, m33 );
  9815. this._z = Math.atan2( m21, m22 );
  9816. } else {
  9817. this._y = Math.atan2( - m31, m11 );
  9818. this._z = 0;
  9819. }
  9820. break;
  9821. case 'ZXY':
  9822. this._x = Math.asin( clamp( m32, -1, 1 ) );
  9823. if ( Math.abs( m32 ) < 0.9999999 ) {
  9824. this._y = Math.atan2( - m31, m33 );
  9825. this._z = Math.atan2( - m12, m22 );
  9826. } else {
  9827. this._y = 0;
  9828. this._z = Math.atan2( m21, m11 );
  9829. }
  9830. break;
  9831. case 'ZYX':
  9832. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  9833. if ( Math.abs( m31 ) < 0.9999999 ) {
  9834. this._x = Math.atan2( m32, m33 );
  9835. this._z = Math.atan2( m21, m11 );
  9836. } else {
  9837. this._x = 0;
  9838. this._z = Math.atan2( - m12, m22 );
  9839. }
  9840. break;
  9841. case 'YZX':
  9842. this._z = Math.asin( clamp( m21, -1, 1 ) );
  9843. if ( Math.abs( m21 ) < 0.9999999 ) {
  9844. this._x = Math.atan2( - m23, m22 );
  9845. this._y = Math.atan2( - m31, m11 );
  9846. } else {
  9847. this._x = 0;
  9848. this._y = Math.atan2( m13, m33 );
  9849. }
  9850. break;
  9851. case 'XZY':
  9852. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  9853. if ( Math.abs( m12 ) < 0.9999999 ) {
  9854. this._x = Math.atan2( m32, m22 );
  9855. this._y = Math.atan2( m13, m11 );
  9856. } else {
  9857. this._x = Math.atan2( - m23, m33 );
  9858. this._y = 0;
  9859. }
  9860. break;
  9861. default:
  9862. warn( 'Euler: .setFromRotationMatrix() encountered an unknown order: ' + order );
  9863. }
  9864. this._order = order;
  9865. if ( update === true ) this._onChangeCallback();
  9866. return this;
  9867. }
  9868. /**
  9869. * Sets the angles of this Euler instance from a normalized quaternion.
  9870. *
  9871. * @param {Quaternion} q - A normalized Quaternion.
  9872. * @param {string} [order] - A string representing the order that the rotations are applied.
  9873. * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not.
  9874. * @return {Euler} A reference to this Euler instance.
  9875. */
  9876. setFromQuaternion( q, order, update ) {
  9877. _matrix$2.makeRotationFromQuaternion( q );
  9878. return this.setFromRotationMatrix( _matrix$2, order, update );
  9879. }
  9880. /**
  9881. * Sets the angles of this Euler instance from the given vector.
  9882. *
  9883. * @param {Vector3} v - The vector.
  9884. * @param {string} [order] - A string representing the order that the rotations are applied.
  9885. * @return {Euler} A reference to this Euler instance.
  9886. */
  9887. setFromVector3( v, order = this._order ) {
  9888. return this.set( v.x, v.y, v.z, order );
  9889. }
  9890. /**
  9891. * Resets the euler angle with a new order by creating a quaternion from this
  9892. * euler angle and then setting this euler angle with the quaternion and the
  9893. * new order.
  9894. *
  9895. * Warning: This discards revolution information.
  9896. *
  9897. * @param {string} [newOrder] - A string representing the new order that the rotations are applied.
  9898. * @return {Euler} A reference to this Euler instance.
  9899. */
  9900. reorder( newOrder ) {
  9901. _quaternion$3.setFromEuler( this );
  9902. return this.setFromQuaternion( _quaternion$3, newOrder );
  9903. }
  9904. /**
  9905. * Returns `true` if this Euler instance is equal with the given one.
  9906. *
  9907. * @param {Euler} euler - The Euler instance to test for equality.
  9908. * @return {boolean} Whether this Euler instance is equal with the given one.
  9909. */
  9910. equals( euler ) {
  9911. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  9912. }
  9913. /**
  9914. * Sets this Euler instance's components to values from the given array. The first three
  9915. * entries of the array are assign to the x,y and z components. An optional fourth entry
  9916. * defines the Euler order.
  9917. *
  9918. * @param {Array<number,number,number,?string>} array - An array holding the Euler component values.
  9919. * @return {Euler} A reference to this Euler instance.
  9920. */
  9921. fromArray( array ) {
  9922. this._x = array[ 0 ];
  9923. this._y = array[ 1 ];
  9924. this._z = array[ 2 ];
  9925. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  9926. this._onChangeCallback();
  9927. return this;
  9928. }
  9929. /**
  9930. * Writes the components of this Euler instance to the given array. If no array is provided,
  9931. * the method returns a new instance.
  9932. *
  9933. * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components.
  9934. * @param {number} [offset=0] - Index of the first element in the array.
  9935. * @return {Array<number,number,number,string>} The Euler components.
  9936. */
  9937. toArray( array = [], offset = 0 ) {
  9938. array[ offset ] = this._x;
  9939. array[ offset + 1 ] = this._y;
  9940. array[ offset + 2 ] = this._z;
  9941. array[ offset + 3 ] = this._order;
  9942. return array;
  9943. }
  9944. _onChange( callback ) {
  9945. this._onChangeCallback = callback;
  9946. return this;
  9947. }
  9948. _onChangeCallback() {}
  9949. *[ Symbol.iterator ]() {
  9950. yield this._x;
  9951. yield this._y;
  9952. yield this._z;
  9953. yield this._order;
  9954. }
  9955. }
  9956. /**
  9957. * The default Euler angle order.
  9958. *
  9959. * @static
  9960. * @type {string}
  9961. * @default 'XYZ'
  9962. */
  9963. Euler.DEFAULT_ORDER = 'XYZ';
  9964. /**
  9965. * A layers object assigns an 3D object to 1 or more of 32
  9966. * layers numbered `0` to `31` - internally the layers are stored as a
  9967. * bit mask], and by default all 3D objects are a member of layer `0`.
  9968. *
  9969. * This can be used to control visibility - an object must share a layer with
  9970. * a camera to be visible when that camera's view is
  9971. * rendered.
  9972. *
  9973. * All classes that inherit from {@link Object3D} have an `layers` property which
  9974. * is an instance of this class.
  9975. */
  9976. class Layers {
  9977. /**
  9978. * Constructs a new layers instance, with membership
  9979. * initially set to layer `0`.
  9980. */
  9981. constructor() {
  9982. /**
  9983. * A bit mask storing which of the 32 layers this layers object is currently
  9984. * a member of.
  9985. *
  9986. * @type {number}
  9987. */
  9988. this.mask = 1 | 0;
  9989. }
  9990. /**
  9991. * Sets membership to the given layer, and remove membership all other layers.
  9992. *
  9993. * @param {number} layer - The layer to set.
  9994. */
  9995. set( layer ) {
  9996. this.mask = ( 1 << layer | 0 ) >>> 0;
  9997. }
  9998. /**
  9999. * Adds membership of the given layer.
  10000. *
  10001. * @param {number} layer - The layer to enable.
  10002. */
  10003. enable( layer ) {
  10004. this.mask |= 1 << layer | 0;
  10005. }
  10006. /**
  10007. * Adds membership to all layers.
  10008. */
  10009. enableAll() {
  10010. this.mask = 0xffffffff | 0;
  10011. }
  10012. /**
  10013. * Toggles the membership of the given layer.
  10014. *
  10015. * @param {number} layer - The layer to toggle.
  10016. */
  10017. toggle( layer ) {
  10018. this.mask ^= 1 << layer | 0;
  10019. }
  10020. /**
  10021. * Removes membership of the given layer.
  10022. *
  10023. * @param {number} layer - The layer to enable.
  10024. */
  10025. disable( layer ) {
  10026. this.mask &= ~ ( 1 << layer | 0 );
  10027. }
  10028. /**
  10029. * Removes the membership from all layers.
  10030. */
  10031. disableAll() {
  10032. this.mask = 0;
  10033. }
  10034. /**
  10035. * Returns `true` if this and the given layers object have at least one
  10036. * layer in common.
  10037. *
  10038. * @param {Layers} layers - The layers to test.
  10039. * @return {boolean } Whether this and the given layers object have at least one layer in common or not.
  10040. */
  10041. test( layers ) {
  10042. return ( this.mask & layers.mask ) !== 0;
  10043. }
  10044. /**
  10045. * Returns `true` if the given layer is enabled.
  10046. *
  10047. * @param {number} layer - The layer to test.
  10048. * @return {boolean } Whether the given layer is enabled or not.
  10049. */
  10050. isEnabled( layer ) {
  10051. return ( this.mask & ( 1 << layer | 0 ) ) !== 0;
  10052. }
  10053. }
  10054. let _object3DId = 0;
  10055. const _v1$4 = /*@__PURE__*/ new Vector3();
  10056. const _q1 = /*@__PURE__*/ new Quaternion();
  10057. const _m1$3 = /*@__PURE__*/ new Matrix4();
  10058. const _target = /*@__PURE__*/ new Vector3();
  10059. const _position$3 = /*@__PURE__*/ new Vector3();
  10060. const _scale$2 = /*@__PURE__*/ new Vector3();
  10061. const _quaternion$2 = /*@__PURE__*/ new Quaternion();
  10062. const _xAxis = /*@__PURE__*/ new Vector3( 1, 0, 0 );
  10063. const _yAxis = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  10064. const _zAxis = /*@__PURE__*/ new Vector3( 0, 0, 1 );
  10065. /**
  10066. * Fires when the object has been added to its parent object.
  10067. *
  10068. * @event Object3D#added
  10069. * @type {Object}
  10070. */
  10071. const _addedEvent = { type: 'added' };
  10072. /**
  10073. * Fires when the object has been removed from its parent object.
  10074. *
  10075. * @event Object3D#removed
  10076. * @type {Object}
  10077. */
  10078. const _removedEvent = { type: 'removed' };
  10079. /**
  10080. * Fires when a new child object has been added.
  10081. *
  10082. * @event Object3D#childadded
  10083. * @type {Object}
  10084. */
  10085. const _childaddedEvent = { type: 'childadded', child: null };
  10086. /**
  10087. * Fires when a child object has been removed.
  10088. *
  10089. * @event Object3D#childremoved
  10090. * @type {Object}
  10091. */
  10092. const _childremovedEvent = { type: 'childremoved', child: null };
  10093. /**
  10094. * This is the base class for most objects in three.js and provides a set of
  10095. * properties and methods for manipulating objects in 3D space.
  10096. *
  10097. * @augments EventDispatcher
  10098. */
  10099. class Object3D extends EventDispatcher {
  10100. /**
  10101. * Constructs a new 3D object.
  10102. */
  10103. constructor() {
  10104. super();
  10105. /**
  10106. * This flag can be used for type testing.
  10107. *
  10108. * @type {boolean}
  10109. * @readonly
  10110. * @default true
  10111. */
  10112. this.isObject3D = true;
  10113. /**
  10114. * The ID of the 3D object.
  10115. *
  10116. * @name Object3D#id
  10117. * @type {number}
  10118. * @readonly
  10119. */
  10120. Object.defineProperty( this, 'id', { value: _object3DId ++ } );
  10121. /**
  10122. * The UUID of the 3D object.
  10123. *
  10124. * @type {string}
  10125. * @readonly
  10126. */
  10127. this.uuid = generateUUID();
  10128. /**
  10129. * The name of the 3D object.
  10130. *
  10131. * @type {string}
  10132. */
  10133. this.name = '';
  10134. /**
  10135. * The type property is used for detecting the object type
  10136. * in context of serialization/deserialization.
  10137. *
  10138. * @type {string}
  10139. * @readonly
  10140. */
  10141. this.type = 'Object3D';
  10142. /**
  10143. * A reference to the parent object.
  10144. *
  10145. * @type {?Object3D}
  10146. * @default null
  10147. */
  10148. this.parent = null;
  10149. /**
  10150. * An array holding the child 3D objects of this instance.
  10151. *
  10152. * @type {Array<Object3D>}
  10153. */
  10154. this.children = [];
  10155. /**
  10156. * Defines the `up` direction of the 3D object which influences
  10157. * the orientation via methods like {@link Object3D#lookAt}.
  10158. *
  10159. * The default values for all 3D objects is defined by `Object3D.DEFAULT_UP`.
  10160. *
  10161. * @type {Vector3}
  10162. */
  10163. this.up = Object3D.DEFAULT_UP.clone();
  10164. const position = new Vector3();
  10165. const rotation = new Euler();
  10166. const quaternion = new Quaternion();
  10167. const scale = new Vector3( 1, 1, 1 );
  10168. function onRotationChange() {
  10169. quaternion.setFromEuler( rotation, false );
  10170. }
  10171. function onQuaternionChange() {
  10172. rotation.setFromQuaternion( quaternion, undefined, false );
  10173. }
  10174. rotation._onChange( onRotationChange );
  10175. quaternion._onChange( onQuaternionChange );
  10176. Object.defineProperties( this, {
  10177. /**
  10178. * Represents the object's local position.
  10179. *
  10180. * @name Object3D#position
  10181. * @type {Vector3}
  10182. * @default (0,0,0)
  10183. */
  10184. position: {
  10185. configurable: true,
  10186. enumerable: true,
  10187. value: position
  10188. },
  10189. /**
  10190. * Represents the object's local rotation as Euler angles, in radians.
  10191. *
  10192. * @name Object3D#rotation
  10193. * @type {Euler}
  10194. * @default (0,0,0)
  10195. */
  10196. rotation: {
  10197. configurable: true,
  10198. enumerable: true,
  10199. value: rotation
  10200. },
  10201. /**
  10202. * Represents the object's local rotation as Quaternions.
  10203. *
  10204. * @name Object3D#quaternion
  10205. * @type {Quaternion}
  10206. */
  10207. quaternion: {
  10208. configurable: true,
  10209. enumerable: true,
  10210. value: quaternion
  10211. },
  10212. /**
  10213. * Represents the object's local scale.
  10214. *
  10215. * @name Object3D#scale
  10216. * @type {Vector3}
  10217. * @default (1,1,1)
  10218. */
  10219. scale: {
  10220. configurable: true,
  10221. enumerable: true,
  10222. value: scale
  10223. },
  10224. /**
  10225. * Represents the object's model-view matrix.
  10226. *
  10227. * @name Object3D#modelViewMatrix
  10228. * @type {Matrix4}
  10229. */
  10230. modelViewMatrix: {
  10231. value: new Matrix4()
  10232. },
  10233. /**
  10234. * Represents the object's normal matrix.
  10235. *
  10236. * @name Object3D#normalMatrix
  10237. * @type {Matrix3}
  10238. */
  10239. normalMatrix: {
  10240. value: new Matrix3()
  10241. }
  10242. } );
  10243. /**
  10244. * Represents the object's transformation matrix in local space.
  10245. *
  10246. * @type {Matrix4}
  10247. */
  10248. this.matrix = new Matrix4();
  10249. /**
  10250. * Represents the object's transformation matrix in world space.
  10251. * If the 3D object has no parent, then it's identical to the local transformation matrix
  10252. *
  10253. * @type {Matrix4}
  10254. */
  10255. this.matrixWorld = new Matrix4();
  10256. /**
  10257. * When set to `true`, the engine automatically computes the local matrix from position,
  10258. * rotation and scale every frame.
  10259. *
  10260. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_AUTO_UPDATE`.
  10261. *
  10262. * @type {boolean}
  10263. * @default true
  10264. */
  10265. this.matrixAutoUpdate = Object3D.DEFAULT_MATRIX_AUTO_UPDATE;
  10266. /**
  10267. * When set to `true`, the engine automatically computes the world matrix from the current local
  10268. * matrix and the object's transformation hierarchy.
  10269. *
  10270. * The default values for all 3D objects is defined by `Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE`.
  10271. *
  10272. * @type {boolean}
  10273. * @default true
  10274. */
  10275. this.matrixWorldAutoUpdate = Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE; // checked by the renderer
  10276. /**
  10277. * When set to `true`, it calculates the world matrix in that frame and resets this property
  10278. * to `false`.
  10279. *
  10280. * @type {boolean}
  10281. * @default false
  10282. */
  10283. this.matrixWorldNeedsUpdate = false;
  10284. /**
  10285. * The layer membership of the 3D object. The 3D object is only visible if it has
  10286. * at least one layer in common with the camera in use. This property can also be
  10287. * used to filter out unwanted objects in ray-intersection tests when using {@link Raycaster}.
  10288. *
  10289. * @type {Layers}
  10290. */
  10291. this.layers = new Layers();
  10292. /**
  10293. * When set to `true`, the 3D object gets rendered.
  10294. *
  10295. * @type {boolean}
  10296. * @default true
  10297. */
  10298. this.visible = true;
  10299. /**
  10300. * When set to `true`, the 3D object gets rendered into shadow maps.
  10301. *
  10302. * @type {boolean}
  10303. * @default false
  10304. */
  10305. this.castShadow = false;
  10306. /**
  10307. * When set to `true`, the 3D object is affected by shadows in the scene.
  10308. *
  10309. * @type {boolean}
  10310. * @default false
  10311. */
  10312. this.receiveShadow = false;
  10313. /**
  10314. * When set to `true`, the 3D object is honored by view frustum culling.
  10315. *
  10316. * @type {boolean}
  10317. * @default true
  10318. */
  10319. this.frustumCulled = true;
  10320. /**
  10321. * This value allows the default rendering order of scene graph objects to be
  10322. * overridden although opaque and transparent objects remain sorted independently.
  10323. * When this property is set for an instance of {@link Group},all descendants
  10324. * objects will be sorted and rendered together. Sorting is from lowest to highest
  10325. * render order.
  10326. *
  10327. * @type {number}
  10328. * @default 0
  10329. */
  10330. this.renderOrder = 0;
  10331. /**
  10332. * An array holding the animation clips of the 3D object.
  10333. *
  10334. * @type {Array<AnimationClip>}
  10335. */
  10336. this.animations = [];
  10337. /**
  10338. * Custom depth material to be used when rendering to the depth map. Can only be used
  10339. * in context of meshes. When shadow-casting with a {@link DirectionalLight} or {@link SpotLight},
  10340. * if you are modifying vertex positions in the vertex shader you must specify a custom depth
  10341. * material for proper shadows.
  10342. *
  10343. * Only relevant in context of {@link WebGLRenderer}.
  10344. *
  10345. * @type {(Material|undefined)}
  10346. * @default undefined
  10347. */
  10348. this.customDepthMaterial = undefined;
  10349. /**
  10350. * Same as {@link Object3D#customDepthMaterial}, but used with {@link PointLight}.
  10351. *
  10352. * Only relevant in context of {@link WebGLRenderer}.
  10353. *
  10354. * @type {(Material|undefined)}
  10355. * @default undefined
  10356. */
  10357. this.customDistanceMaterial = undefined;
  10358. /**
  10359. * An object that can be used to store custom data about the 3D object. It
  10360. * should not hold references to functions as these will not be cloned.
  10361. *
  10362. * @type {Object}
  10363. */
  10364. this.userData = {};
  10365. }
  10366. /**
  10367. * A callback that is executed immediately before a 3D object is rendered to a shadow map.
  10368. *
  10369. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10370. * @param {Object3D} object - The 3D object.
  10371. * @param {Camera} camera - The camera that is used to render the scene.
  10372. * @param {Camera} shadowCamera - The shadow camera.
  10373. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10374. * @param {Material} depthMaterial - The depth material.
  10375. * @param {Object} group - The geometry group data.
  10376. */
  10377. onBeforeShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10378. /**
  10379. * A callback that is executed immediately after a 3D object is rendered to a shadow map.
  10380. *
  10381. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10382. * @param {Object3D} object - The 3D object.
  10383. * @param {Camera} camera - The camera that is used to render the scene.
  10384. * @param {Camera} shadowCamera - The shadow camera.
  10385. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10386. * @param {Material} depthMaterial - The depth material.
  10387. * @param {Object} group - The geometry group data.
  10388. */
  10389. onAfterShadow( /* renderer, object, camera, shadowCamera, geometry, depthMaterial, group */ ) {}
  10390. /**
  10391. * A callback that is executed immediately before a 3D object is rendered.
  10392. *
  10393. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10394. * @param {Object3D} object - The 3D object.
  10395. * @param {Camera} camera - The camera that is used to render the scene.
  10396. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10397. * @param {Material} material - The 3D object's material.
  10398. * @param {Object} group - The geometry group data.
  10399. */
  10400. onBeforeRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10401. /**
  10402. * A callback that is executed immediately after a 3D object is rendered.
  10403. *
  10404. * @param {Renderer|WebGLRenderer} renderer - The renderer.
  10405. * @param {Object3D} object - The 3D object.
  10406. * @param {Camera} camera - The camera that is used to render the scene.
  10407. * @param {BufferGeometry} geometry - The 3D object's geometry.
  10408. * @param {Material} material - The 3D object's material.
  10409. * @param {Object} group - The geometry group data.
  10410. */
  10411. onAfterRender( /* renderer, scene, camera, geometry, material, group */ ) {}
  10412. /**
  10413. * Applies the given transformation matrix to the object and updates the object's position,
  10414. * rotation and scale.
  10415. *
  10416. * @param {Matrix4} matrix - The transformation matrix.
  10417. */
  10418. applyMatrix4( matrix ) {
  10419. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10420. this.matrix.premultiply( matrix );
  10421. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10422. }
  10423. /**
  10424. * Applies a rotation represented by given the quaternion to the 3D object.
  10425. *
  10426. * @param {Quaternion} q - The quaternion.
  10427. * @return {Object3D} A reference to this instance.
  10428. */
  10429. applyQuaternion( q ) {
  10430. this.quaternion.premultiply( q );
  10431. return this;
  10432. }
  10433. /**
  10434. * Sets the given rotation represented as an axis/angle couple to the 3D object.
  10435. *
  10436. * @param {Vector3} axis - The (normalized) axis vector.
  10437. * @param {number} angle - The angle in radians.
  10438. */
  10439. setRotationFromAxisAngle( axis, angle ) {
  10440. // assumes axis is normalized
  10441. this.quaternion.setFromAxisAngle( axis, angle );
  10442. }
  10443. /**
  10444. * Sets the given rotation represented as Euler angles to the 3D object.
  10445. *
  10446. * @param {Euler} euler - The Euler angles.
  10447. */
  10448. setRotationFromEuler( euler ) {
  10449. this.quaternion.setFromEuler( euler, true );
  10450. }
  10451. /**
  10452. * Sets the given rotation represented as rotation matrix to the 3D object.
  10453. *
  10454. * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be
  10455. * a pure rotation matrix (i.e, unscaled).
  10456. */
  10457. setRotationFromMatrix( m ) {
  10458. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10459. this.quaternion.setFromRotationMatrix( m );
  10460. }
  10461. /**
  10462. * Sets the given rotation represented as a Quaternion to the 3D object.
  10463. *
  10464. * @param {Quaternion} q - The Quaternion
  10465. */
  10466. setRotationFromQuaternion( q ) {
  10467. // assumes q is normalized
  10468. this.quaternion.copy( q );
  10469. }
  10470. /**
  10471. * Rotates the 3D object along an axis in local space.
  10472. *
  10473. * @param {Vector3} axis - The (normalized) axis vector.
  10474. * @param {number} angle - The angle in radians.
  10475. * @return {Object3D} A reference to this instance.
  10476. */
  10477. rotateOnAxis( axis, angle ) {
  10478. // rotate object on axis in object space
  10479. // axis is assumed to be normalized
  10480. _q1.setFromAxisAngle( axis, angle );
  10481. this.quaternion.multiply( _q1 );
  10482. return this;
  10483. }
  10484. /**
  10485. * Rotates the 3D object along an axis in world space.
  10486. *
  10487. * @param {Vector3} axis - The (normalized) axis vector.
  10488. * @param {number} angle - The angle in radians.
  10489. * @return {Object3D} A reference to this instance.
  10490. */
  10491. rotateOnWorldAxis( axis, angle ) {
  10492. // rotate object on axis in world space
  10493. // axis is assumed to be normalized
  10494. // method assumes no rotated parent
  10495. _q1.setFromAxisAngle( axis, angle );
  10496. this.quaternion.premultiply( _q1 );
  10497. return this;
  10498. }
  10499. /**
  10500. * Rotates the 3D object around its X axis in local space.
  10501. *
  10502. * @param {number} angle - The angle in radians.
  10503. * @return {Object3D} A reference to this instance.
  10504. */
  10505. rotateX( angle ) {
  10506. return this.rotateOnAxis( _xAxis, angle );
  10507. }
  10508. /**
  10509. * Rotates the 3D object around its Y axis in local space.
  10510. *
  10511. * @param {number} angle - The angle in radians.
  10512. * @return {Object3D} A reference to this instance.
  10513. */
  10514. rotateY( angle ) {
  10515. return this.rotateOnAxis( _yAxis, angle );
  10516. }
  10517. /**
  10518. * Rotates the 3D object around its Z axis in local space.
  10519. *
  10520. * @param {number} angle - The angle in radians.
  10521. * @return {Object3D} A reference to this instance.
  10522. */
  10523. rotateZ( angle ) {
  10524. return this.rotateOnAxis( _zAxis, angle );
  10525. }
  10526. /**
  10527. * Translate the 3D object by a distance along the given axis in local space.
  10528. *
  10529. * @param {Vector3} axis - The (normalized) axis vector.
  10530. * @param {number} distance - The distance in world units.
  10531. * @return {Object3D} A reference to this instance.
  10532. */
  10533. translateOnAxis( axis, distance ) {
  10534. // translate object by distance along axis in object space
  10535. // axis is assumed to be normalized
  10536. _v1$4.copy( axis ).applyQuaternion( this.quaternion );
  10537. this.position.add( _v1$4.multiplyScalar( distance ) );
  10538. return this;
  10539. }
  10540. /**
  10541. * Translate the 3D object by a distance along its X-axis in local space.
  10542. *
  10543. * @param {number} distance - The distance in world units.
  10544. * @return {Object3D} A reference to this instance.
  10545. */
  10546. translateX( distance ) {
  10547. return this.translateOnAxis( _xAxis, distance );
  10548. }
  10549. /**
  10550. * Translate the 3D object by a distance along its Y-axis in local space.
  10551. *
  10552. * @param {number} distance - The distance in world units.
  10553. * @return {Object3D} A reference to this instance.
  10554. */
  10555. translateY( distance ) {
  10556. return this.translateOnAxis( _yAxis, distance );
  10557. }
  10558. /**
  10559. * Translate the 3D object by a distance along its Z-axis in local space.
  10560. *
  10561. * @param {number} distance - The distance in world units.
  10562. * @return {Object3D} A reference to this instance.
  10563. */
  10564. translateZ( distance ) {
  10565. return this.translateOnAxis( _zAxis, distance );
  10566. }
  10567. /**
  10568. * Converts the given vector from this 3D object's local space to world space.
  10569. *
  10570. * @param {Vector3} vector - The vector to convert.
  10571. * @return {Vector3} The converted vector.
  10572. */
  10573. localToWorld( vector ) {
  10574. this.updateWorldMatrix( true, false );
  10575. return vector.applyMatrix4( this.matrixWorld );
  10576. }
  10577. /**
  10578. * Converts the given vector from this 3D object's word space to local space.
  10579. *
  10580. * @param {Vector3} vector - The vector to convert.
  10581. * @return {Vector3} The converted vector.
  10582. */
  10583. worldToLocal( vector ) {
  10584. this.updateWorldMatrix( true, false );
  10585. return vector.applyMatrix4( _m1$3.copy( this.matrixWorld ).invert() );
  10586. }
  10587. /**
  10588. * Rotates the object to face a point in world space.
  10589. *
  10590. * This method does not support objects having non-uniformly-scaled parent(s).
  10591. *
  10592. * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space
  10593. * @param {number} [y] - The y coordinate in world space.
  10594. * @param {number} [z] - The z coordinate in world space.
  10595. */
  10596. lookAt( x, y, z ) {
  10597. // This method does not support objects having non-uniformly-scaled parent(s)
  10598. if ( x.isVector3 ) {
  10599. _target.copy( x );
  10600. } else {
  10601. _target.set( x, y, z );
  10602. }
  10603. const parent = this.parent;
  10604. this.updateWorldMatrix( true, false );
  10605. _position$3.setFromMatrixPosition( this.matrixWorld );
  10606. if ( this.isCamera || this.isLight ) {
  10607. _m1$3.lookAt( _position$3, _target, this.up );
  10608. } else {
  10609. _m1$3.lookAt( _target, _position$3, this.up );
  10610. }
  10611. this.quaternion.setFromRotationMatrix( _m1$3 );
  10612. if ( parent ) {
  10613. _m1$3.extractRotation( parent.matrixWorld );
  10614. _q1.setFromRotationMatrix( _m1$3 );
  10615. this.quaternion.premultiply( _q1.invert() );
  10616. }
  10617. }
  10618. /**
  10619. * Adds the given 3D object as a child to this 3D object. An arbitrary number of
  10620. * objects may be added. Any current parent on an object passed in here will be
  10621. * removed, since an object can have at most one parent.
  10622. *
  10623. * @fires Object3D#added
  10624. * @fires Object3D#childadded
  10625. * @param {Object3D} object - The 3D object to add.
  10626. * @return {Object3D} A reference to this instance.
  10627. */
  10628. add( object ) {
  10629. if ( arguments.length > 1 ) {
  10630. for ( let i = 0; i < arguments.length; i ++ ) {
  10631. this.add( arguments[ i ] );
  10632. }
  10633. return this;
  10634. }
  10635. if ( object === this ) {
  10636. error( 'Object3D.add: object can\'t be added as a child of itself.', object );
  10637. return this;
  10638. }
  10639. if ( object && object.isObject3D ) {
  10640. object.removeFromParent();
  10641. object.parent = this;
  10642. this.children.push( object );
  10643. object.dispatchEvent( _addedEvent );
  10644. _childaddedEvent.child = object;
  10645. this.dispatchEvent( _childaddedEvent );
  10646. _childaddedEvent.child = null;
  10647. } else {
  10648. error( 'Object3D.add: object not an instance of THREE.Object3D.', object );
  10649. }
  10650. return this;
  10651. }
  10652. /**
  10653. * Removes the given 3D object as child from this 3D object.
  10654. * An arbitrary number of objects may be removed.
  10655. *
  10656. * @fires Object3D#removed
  10657. * @fires Object3D#childremoved
  10658. * @param {Object3D} object - The 3D object to remove.
  10659. * @return {Object3D} A reference to this instance.
  10660. */
  10661. remove( object ) {
  10662. if ( arguments.length > 1 ) {
  10663. for ( let i = 0; i < arguments.length; i ++ ) {
  10664. this.remove( arguments[ i ] );
  10665. }
  10666. return this;
  10667. }
  10668. const index = this.children.indexOf( object );
  10669. if ( index !== -1 ) {
  10670. object.parent = null;
  10671. this.children.splice( index, 1 );
  10672. object.dispatchEvent( _removedEvent );
  10673. _childremovedEvent.child = object;
  10674. this.dispatchEvent( _childremovedEvent );
  10675. _childremovedEvent.child = null;
  10676. }
  10677. return this;
  10678. }
  10679. /**
  10680. * Removes this 3D object from its current parent.
  10681. *
  10682. * @fires Object3D#removed
  10683. * @fires Object3D#childremoved
  10684. * @return {Object3D} A reference to this instance.
  10685. */
  10686. removeFromParent() {
  10687. const parent = this.parent;
  10688. if ( parent !== null ) {
  10689. parent.remove( this );
  10690. }
  10691. return this;
  10692. }
  10693. /**
  10694. * Removes all child objects.
  10695. *
  10696. * @fires Object3D#removed
  10697. * @fires Object3D#childremoved
  10698. * @return {Object3D} A reference to this instance.
  10699. */
  10700. clear() {
  10701. return this.remove( ... this.children );
  10702. }
  10703. /**
  10704. * Adds the given 3D object as a child of this 3D object, while maintaining the object's world
  10705. * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s).
  10706. *
  10707. * @fires Object3D#added
  10708. * @fires Object3D#childadded
  10709. * @param {Object3D} object - The 3D object to attach.
  10710. * @return {Object3D} A reference to this instance.
  10711. */
  10712. attach( object ) {
  10713. // adds object as a child of this, while maintaining the object's world transform
  10714. // Note: This method does not support scene graphs having non-uniformly-scaled nodes(s)
  10715. this.updateWorldMatrix( true, false );
  10716. _m1$3.copy( this.matrixWorld ).invert();
  10717. if ( object.parent !== null ) {
  10718. object.parent.updateWorldMatrix( true, false );
  10719. _m1$3.multiply( object.parent.matrixWorld );
  10720. }
  10721. object.applyMatrix4( _m1$3 );
  10722. object.removeFromParent();
  10723. object.parent = this;
  10724. this.children.push( object );
  10725. object.updateWorldMatrix( false, true );
  10726. object.dispatchEvent( _addedEvent );
  10727. _childaddedEvent.child = object;
  10728. this.dispatchEvent( _childaddedEvent );
  10729. _childaddedEvent.child = null;
  10730. return this;
  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 ID.
  10735. *
  10736. * @param {number} id - The id.
  10737. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10738. */
  10739. getObjectById( id ) {
  10740. return this.getObjectByProperty( 'id', id );
  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 name.
  10745. *
  10746. * @param {string} name - The name.
  10747. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10748. */
  10749. getObjectByName( name ) {
  10750. return this.getObjectByProperty( 'name', name );
  10751. }
  10752. /**
  10753. * Searches through the 3D object and its children, starting with the 3D object
  10754. * itself, and returns the first with a matching property value.
  10755. *
  10756. * @param {string} name - The name of the property.
  10757. * @param {any} value - The value.
  10758. * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found.
  10759. */
  10760. getObjectByProperty( name, value ) {
  10761. if ( this[ name ] === value ) return this;
  10762. for ( let i = 0, l = this.children.length; i < l; i ++ ) {
  10763. const child = this.children[ i ];
  10764. const object = child.getObjectByProperty( name, value );
  10765. if ( object !== undefined ) {
  10766. return object;
  10767. }
  10768. }
  10769. return undefined;
  10770. }
  10771. /**
  10772. * Searches through the 3D object and its children, starting with the 3D object
  10773. * itself, and returns all 3D objects with a matching property value.
  10774. *
  10775. * @param {string} name - The name of the property.
  10776. * @param {any} value - The value.
  10777. * @param {Array<Object3D>} result - The method stores the result in this array.
  10778. * @return {Array<Object3D>} The found 3D objects.
  10779. */
  10780. getObjectsByProperty( name, value, result = [] ) {
  10781. if ( this[ name ] === value ) result.push( this );
  10782. const children = this.children;
  10783. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10784. children[ i ].getObjectsByProperty( name, value, result );
  10785. }
  10786. return result;
  10787. }
  10788. /**
  10789. * Returns a vector representing the position of the 3D object in world space.
  10790. *
  10791. * @param {Vector3} target - The target vector the result is stored to.
  10792. * @return {Vector3} The 3D object's position in world space.
  10793. */
  10794. getWorldPosition( target ) {
  10795. this.updateWorldMatrix( true, false );
  10796. return target.setFromMatrixPosition( this.matrixWorld );
  10797. }
  10798. /**
  10799. * Returns a Quaternion representing the position of the 3D object in world space.
  10800. *
  10801. * @param {Quaternion} target - The target Quaternion the result is stored to.
  10802. * @return {Quaternion} The 3D object's rotation in world space.
  10803. */
  10804. getWorldQuaternion( target ) {
  10805. this.updateWorldMatrix( true, false );
  10806. this.matrixWorld.decompose( _position$3, target, _scale$2 );
  10807. return target;
  10808. }
  10809. /**
  10810. * Returns a vector representing the scale of the 3D object in world space.
  10811. *
  10812. * @param {Vector3} target - The target vector the result is stored to.
  10813. * @return {Vector3} The 3D object's scale in world space.
  10814. */
  10815. getWorldScale( target ) {
  10816. this.updateWorldMatrix( true, false );
  10817. this.matrixWorld.decompose( _position$3, _quaternion$2, target );
  10818. return target;
  10819. }
  10820. /**
  10821. * Returns a vector representing the ("look") direction of the 3D object in world space.
  10822. *
  10823. * @param {Vector3} target - The target vector the result is stored to.
  10824. * @return {Vector3} The 3D object's direction in world space.
  10825. */
  10826. getWorldDirection( target ) {
  10827. this.updateWorldMatrix( true, false );
  10828. const e = this.matrixWorld.elements;
  10829. return target.set( e[ 8 ], e[ 9 ], e[ 10 ] ).normalize();
  10830. }
  10831. /**
  10832. * Abstract method to get intersections between a casted ray and this
  10833. * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points}
  10834. * implement this method in order to use raycasting.
  10835. *
  10836. * @abstract
  10837. * @param {Raycaster} raycaster - The raycaster.
  10838. * @param {Array<Object>} intersects - An array holding the result of the method.
  10839. */
  10840. raycast( /* raycaster, intersects */ ) {}
  10841. /**
  10842. * Executes the callback on this 3D object and all descendants.
  10843. *
  10844. * Note: Modifying the scene graph inside the callback is discouraged.
  10845. *
  10846. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10847. */
  10848. traverse( callback ) {
  10849. callback( this );
  10850. const children = this.children;
  10851. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10852. children[ i ].traverse( callback );
  10853. }
  10854. }
  10855. /**
  10856. * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects.
  10857. * Descendants of invisible 3D objects are not traversed.
  10858. *
  10859. * Note: Modifying the scene graph inside the callback is discouraged.
  10860. *
  10861. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10862. */
  10863. traverseVisible( callback ) {
  10864. if ( this.visible === false ) return;
  10865. callback( this );
  10866. const children = this.children;
  10867. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10868. children[ i ].traverseVisible( callback );
  10869. }
  10870. }
  10871. /**
  10872. * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors.
  10873. *
  10874. * Note: Modifying the scene graph inside the callback is discouraged.
  10875. *
  10876. * @param {Function} callback - A callback function that allows to process the current 3D object.
  10877. */
  10878. traverseAncestors( callback ) {
  10879. const parent = this.parent;
  10880. if ( parent !== null ) {
  10881. callback( parent );
  10882. parent.traverseAncestors( callback );
  10883. }
  10884. }
  10885. /**
  10886. * Updates the transformation matrix in local space by computing it from the current
  10887. * position, rotation and scale values.
  10888. */
  10889. updateMatrix() {
  10890. this.matrix.compose( this.position, this.quaternion, this.scale );
  10891. this.matrixWorldNeedsUpdate = true;
  10892. }
  10893. /**
  10894. * Updates the transformation matrix in world space of this 3D objects and its descendants.
  10895. *
  10896. * To ensure correct results, this method also recomputes the 3D object's transformation matrix in
  10897. * local space. The computation of the local and world matrix can be controlled with the
  10898. * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both
  10899. * `true` by default. Set these flags to `false` if you need more control over the update matrix process.
  10900. *
  10901. * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even
  10902. * when {@link Object3D#matrixWorldAutoUpdate} is set to `false`.
  10903. */
  10904. updateMatrixWorld( force ) {
  10905. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10906. if ( this.matrixWorldNeedsUpdate || force ) {
  10907. if ( this.matrixWorldAutoUpdate === true ) {
  10908. if ( this.parent === null ) {
  10909. this.matrixWorld.copy( this.matrix );
  10910. } else {
  10911. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10912. }
  10913. }
  10914. this.matrixWorldNeedsUpdate = false;
  10915. force = true;
  10916. }
  10917. // make sure descendants are updated if required
  10918. const children = this.children;
  10919. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10920. const child = children[ i ];
  10921. child.updateMatrixWorld( force );
  10922. }
  10923. }
  10924. /**
  10925. * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the
  10926. * update of ancestor and descendant nodes.
  10927. *
  10928. * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not.
  10929. * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not.
  10930. */
  10931. updateWorldMatrix( updateParents, updateChildren ) {
  10932. const parent = this.parent;
  10933. if ( updateParents === true && parent !== null ) {
  10934. parent.updateWorldMatrix( true, false );
  10935. }
  10936. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10937. if ( this.matrixWorldAutoUpdate === true ) {
  10938. if ( this.parent === null ) {
  10939. this.matrixWorld.copy( this.matrix );
  10940. } else {
  10941. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10942. }
  10943. }
  10944. // make sure descendants are updated
  10945. if ( updateChildren === true ) {
  10946. const children = this.children;
  10947. for ( let i = 0, l = children.length; i < l; i ++ ) {
  10948. const child = children[ i ];
  10949. child.updateWorldMatrix( false, true );
  10950. }
  10951. }
  10952. }
  10953. /**
  10954. * Serializes the 3D object into JSON.
  10955. *
  10956. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  10957. * @return {Object} A JSON object representing the serialized 3D object.
  10958. * @see {@link ObjectLoader#parse}
  10959. */
  10960. toJSON( meta ) {
  10961. // meta is a string when called from JSON.stringify
  10962. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  10963. const output = {};
  10964. // meta is a hash used to collect geometries, materials.
  10965. // not providing it implies that this is the root object
  10966. // being serialized.
  10967. if ( isRootObject ) {
  10968. // initialize meta obj
  10969. meta = {
  10970. geometries: {},
  10971. materials: {},
  10972. textures: {},
  10973. images: {},
  10974. shapes: {},
  10975. skeletons: {},
  10976. animations: {},
  10977. nodes: {}
  10978. };
  10979. output.metadata = {
  10980. version: 4.7,
  10981. type: 'Object',
  10982. generator: 'Object3D.toJSON'
  10983. };
  10984. }
  10985. // standard Object3D serialization
  10986. const object = {};
  10987. object.uuid = this.uuid;
  10988. object.type = this.type;
  10989. if ( this.name !== '' ) object.name = this.name;
  10990. if ( this.castShadow === true ) object.castShadow = true;
  10991. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10992. if ( this.visible === false ) object.visible = false;
  10993. if ( this.frustumCulled === false ) object.frustumCulled = false;
  10994. if ( this.renderOrder !== 0 ) object.renderOrder = this.renderOrder;
  10995. if ( Object.keys( this.userData ).length > 0 ) object.userData = this.userData;
  10996. object.layers = this.layers.mask;
  10997. object.matrix = this.matrix.toArray();
  10998. object.up = this.up.toArray();
  10999. if ( this.matrixAutoUpdate === false ) object.matrixAutoUpdate = false;
  11000. // object specific properties
  11001. if ( this.isInstancedMesh ) {
  11002. object.type = 'InstancedMesh';
  11003. object.count = this.count;
  11004. object.instanceMatrix = this.instanceMatrix.toJSON();
  11005. if ( this.instanceColor !== null ) object.instanceColor = this.instanceColor.toJSON();
  11006. }
  11007. if ( this.isBatchedMesh ) {
  11008. object.type = 'BatchedMesh';
  11009. object.perObjectFrustumCulled = this.perObjectFrustumCulled;
  11010. object.sortObjects = this.sortObjects;
  11011. object.drawRanges = this._drawRanges;
  11012. object.reservedRanges = this._reservedRanges;
  11013. object.geometryInfo = this._geometryInfo.map( info => ( {
  11014. ...info,
  11015. boundingBox: info.boundingBox ? info.boundingBox.toJSON() : undefined,
  11016. boundingSphere: info.boundingSphere ? info.boundingSphere.toJSON() : undefined
  11017. } ) );
  11018. object.instanceInfo = this._instanceInfo.map( info => ( { ...info } ) );
  11019. object.availableInstanceIds = this._availableInstanceIds.slice();
  11020. object.availableGeometryIds = this._availableGeometryIds.slice();
  11021. object.nextIndexStart = this._nextIndexStart;
  11022. object.nextVertexStart = this._nextVertexStart;
  11023. object.geometryCount = this._geometryCount;
  11024. object.maxInstanceCount = this._maxInstanceCount;
  11025. object.maxVertexCount = this._maxVertexCount;
  11026. object.maxIndexCount = this._maxIndexCount;
  11027. object.geometryInitialized = this._geometryInitialized;
  11028. object.matricesTexture = this._matricesTexture.toJSON( meta );
  11029. object.indirectTexture = this._indirectTexture.toJSON( meta );
  11030. if ( this._colorsTexture !== null ) {
  11031. object.colorsTexture = this._colorsTexture.toJSON( meta );
  11032. }
  11033. if ( this.boundingSphere !== null ) {
  11034. object.boundingSphere = this.boundingSphere.toJSON();
  11035. }
  11036. if ( this.boundingBox !== null ) {
  11037. object.boundingBox = this.boundingBox.toJSON();
  11038. }
  11039. }
  11040. //
  11041. function serialize( library, element ) {
  11042. if ( library[ element.uuid ] === undefined ) {
  11043. library[ element.uuid ] = element.toJSON( meta );
  11044. }
  11045. return element.uuid;
  11046. }
  11047. if ( this.isScene ) {
  11048. if ( this.background ) {
  11049. if ( this.background.isColor ) {
  11050. object.background = this.background.toJSON();
  11051. } else if ( this.background.isTexture ) {
  11052. object.background = this.background.toJSON( meta ).uuid;
  11053. }
  11054. }
  11055. if ( this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== true ) {
  11056. object.environment = this.environment.toJSON( meta ).uuid;
  11057. }
  11058. } else if ( this.isMesh || this.isLine || this.isPoints ) {
  11059. object.geometry = serialize( meta.geometries, this.geometry );
  11060. const parameters = this.geometry.parameters;
  11061. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  11062. const shapes = parameters.shapes;
  11063. if ( Array.isArray( shapes ) ) {
  11064. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  11065. const shape = shapes[ i ];
  11066. serialize( meta.shapes, shape );
  11067. }
  11068. } else {
  11069. serialize( meta.shapes, shapes );
  11070. }
  11071. }
  11072. }
  11073. if ( this.isSkinnedMesh ) {
  11074. object.bindMode = this.bindMode;
  11075. object.bindMatrix = this.bindMatrix.toArray();
  11076. if ( this.skeleton !== undefined ) {
  11077. serialize( meta.skeletons, this.skeleton );
  11078. object.skeleton = this.skeleton.uuid;
  11079. }
  11080. }
  11081. if ( this.material !== undefined ) {
  11082. if ( Array.isArray( this.material ) ) {
  11083. const uuids = [];
  11084. for ( let i = 0, l = this.material.length; i < l; i ++ ) {
  11085. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  11086. }
  11087. object.material = uuids;
  11088. } else {
  11089. object.material = serialize( meta.materials, this.material );
  11090. }
  11091. }
  11092. //
  11093. if ( this.children.length > 0 ) {
  11094. object.children = [];
  11095. for ( let i = 0; i < this.children.length; i ++ ) {
  11096. object.children.push( this.children[ i ].toJSON( meta ).object );
  11097. }
  11098. }
  11099. //
  11100. if ( this.animations.length > 0 ) {
  11101. object.animations = [];
  11102. for ( let i = 0; i < this.animations.length; i ++ ) {
  11103. const animation = this.animations[ i ];
  11104. object.animations.push( serialize( meta.animations, animation ) );
  11105. }
  11106. }
  11107. if ( isRootObject ) {
  11108. const geometries = extractFromCache( meta.geometries );
  11109. const materials = extractFromCache( meta.materials );
  11110. const textures = extractFromCache( meta.textures );
  11111. const images = extractFromCache( meta.images );
  11112. const shapes = extractFromCache( meta.shapes );
  11113. const skeletons = extractFromCache( meta.skeletons );
  11114. const animations = extractFromCache( meta.animations );
  11115. const nodes = extractFromCache( meta.nodes );
  11116. if ( geometries.length > 0 ) output.geometries = geometries;
  11117. if ( materials.length > 0 ) output.materials = materials;
  11118. if ( textures.length > 0 ) output.textures = textures;
  11119. if ( images.length > 0 ) output.images = images;
  11120. if ( shapes.length > 0 ) output.shapes = shapes;
  11121. if ( skeletons.length > 0 ) output.skeletons = skeletons;
  11122. if ( animations.length > 0 ) output.animations = animations;
  11123. if ( nodes.length > 0 ) output.nodes = nodes;
  11124. }
  11125. output.object = object;
  11126. return output;
  11127. // extract data from the cache hash
  11128. // remove metadata on each item
  11129. // and return as array
  11130. function extractFromCache( cache ) {
  11131. const values = [];
  11132. for ( const key in cache ) {
  11133. const data = cache[ key ];
  11134. delete data.metadata;
  11135. values.push( data );
  11136. }
  11137. return values;
  11138. }
  11139. }
  11140. /**
  11141. * Returns a new 3D object with copied values from this instance.
  11142. *
  11143. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned.
  11144. * @return {Object3D} A clone of this instance.
  11145. */
  11146. clone( recursive ) {
  11147. return new this.constructor().copy( this, recursive );
  11148. }
  11149. /**
  11150. * Copies the values of the given 3D object to this instance.
  11151. *
  11152. * @param {Object3D} source - The 3D object to copy.
  11153. * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned.
  11154. * @return {Object3D} A reference to this instance.
  11155. */
  11156. copy( source, recursive = true ) {
  11157. this.name = source.name;
  11158. this.up.copy( source.up );
  11159. this.position.copy( source.position );
  11160. this.rotation.order = source.rotation.order;
  11161. this.quaternion.copy( source.quaternion );
  11162. this.scale.copy( source.scale );
  11163. this.matrix.copy( source.matrix );
  11164. this.matrixWorld.copy( source.matrixWorld );
  11165. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11166. this.matrixWorldAutoUpdate = source.matrixWorldAutoUpdate;
  11167. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11168. this.layers.mask = source.layers.mask;
  11169. this.visible = source.visible;
  11170. this.castShadow = source.castShadow;
  11171. this.receiveShadow = source.receiveShadow;
  11172. this.frustumCulled = source.frustumCulled;
  11173. this.renderOrder = source.renderOrder;
  11174. this.animations = source.animations.slice();
  11175. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11176. if ( recursive === true ) {
  11177. for ( let i = 0; i < source.children.length; i ++ ) {
  11178. const child = source.children[ i ];
  11179. this.add( child.clone() );
  11180. }
  11181. }
  11182. return this;
  11183. }
  11184. }
  11185. /**
  11186. * The default up direction for objects, also used as the default
  11187. * position for {@link DirectionalLight} and {@link HemisphereLight}.
  11188. *
  11189. * @static
  11190. * @type {Vector3}
  11191. * @default (0,1,0)
  11192. */
  11193. Object3D.DEFAULT_UP = /*@__PURE__*/ new Vector3( 0, 1, 0 );
  11194. /**
  11195. * The default setting for {@link Object3D#matrixAutoUpdate} for
  11196. * newly created 3D objects.
  11197. *
  11198. * @static
  11199. * @type {boolean}
  11200. * @default true
  11201. */
  11202. Object3D.DEFAULT_MATRIX_AUTO_UPDATE = true;
  11203. /**
  11204. * The default setting for {@link Object3D#matrixWorldAutoUpdate} for
  11205. * newly created 3D objects.
  11206. *
  11207. * @static
  11208. * @type {boolean}
  11209. * @default true
  11210. */
  11211. Object3D.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = true;
  11212. const _v0$2 = /*@__PURE__*/ new Vector3();
  11213. const _v1$3 = /*@__PURE__*/ new Vector3();
  11214. const _v2$2 = /*@__PURE__*/ new Vector3();
  11215. const _v3$2 = /*@__PURE__*/ new Vector3();
  11216. const _vab = /*@__PURE__*/ new Vector3();
  11217. const _vac = /*@__PURE__*/ new Vector3();
  11218. const _vbc = /*@__PURE__*/ new Vector3();
  11219. const _vap = /*@__PURE__*/ new Vector3();
  11220. const _vbp = /*@__PURE__*/ new Vector3();
  11221. const _vcp = /*@__PURE__*/ new Vector3();
  11222. const _v40 = /*@__PURE__*/ new Vector4();
  11223. const _v41 = /*@__PURE__*/ new Vector4();
  11224. const _v42 = /*@__PURE__*/ new Vector4();
  11225. /**
  11226. * A geometric triangle as defined by three vectors representing its three corners.
  11227. */
  11228. class Triangle {
  11229. /**
  11230. * Constructs a new triangle.
  11231. *
  11232. * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle.
  11233. * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle.
  11234. * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle.
  11235. */
  11236. constructor( a = new Vector3(), b = new Vector3(), c = new Vector3() ) {
  11237. /**
  11238. * The first corner of the triangle.
  11239. *
  11240. * @type {Vector3}
  11241. */
  11242. this.a = a;
  11243. /**
  11244. * The second corner of the triangle.
  11245. *
  11246. * @type {Vector3}
  11247. */
  11248. this.b = b;
  11249. /**
  11250. * The third corner of the triangle.
  11251. *
  11252. * @type {Vector3}
  11253. */
  11254. this.c = c;
  11255. }
  11256. /**
  11257. * Computes the normal vector of a triangle.
  11258. *
  11259. * @param {Vector3} a - The first corner of the triangle.
  11260. * @param {Vector3} b - The second corner of the triangle.
  11261. * @param {Vector3} c - The third corner of the triangle.
  11262. * @param {Vector3} target - The target vector that is used to store the method's result.
  11263. * @return {Vector3} The triangle's normal.
  11264. */
  11265. static getNormal( a, b, c, target ) {
  11266. target.subVectors( c, b );
  11267. _v0$2.subVectors( a, b );
  11268. target.cross( _v0$2 );
  11269. const targetLengthSq = target.lengthSq();
  11270. if ( targetLengthSq > 0 ) {
  11271. return target.multiplyScalar( 1 / Math.sqrt( targetLengthSq ) );
  11272. }
  11273. return target.set( 0, 0, 0 );
  11274. }
  11275. /**
  11276. * Computes a barycentric coordinates from the given vector.
  11277. * Returns `null` if the triangle is degenerate.
  11278. *
  11279. * @param {Vector3} point - A point in 3D space.
  11280. * @param {Vector3} a - The first corner of the triangle.
  11281. * @param {Vector3} b - The second corner of the triangle.
  11282. * @param {Vector3} c - The third corner of the triangle.
  11283. * @param {Vector3} target - The target vector that is used to store the method's result.
  11284. * @return {?Vector3} The barycentric coordinates for the given point
  11285. */
  11286. static getBarycoord( point, a, b, c, target ) {
  11287. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11288. _v0$2.subVectors( c, a );
  11289. _v1$3.subVectors( b, a );
  11290. _v2$2.subVectors( point, a );
  11291. const dot00 = _v0$2.dot( _v0$2 );
  11292. const dot01 = _v0$2.dot( _v1$3 );
  11293. const dot02 = _v0$2.dot( _v2$2 );
  11294. const dot11 = _v1$3.dot( _v1$3 );
  11295. const dot12 = _v1$3.dot( _v2$2 );
  11296. const denom = ( dot00 * dot11 - dot01 * dot01 );
  11297. // collinear or singular triangle
  11298. if ( denom === 0 ) {
  11299. target.set( 0, 0, 0 );
  11300. return null;
  11301. }
  11302. const invDenom = 1 / denom;
  11303. const u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11304. const v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11305. // barycentric coordinates must always sum to 1
  11306. return target.set( 1 - u - v, v, u );
  11307. }
  11308. /**
  11309. * Returns `true` if the given point, when projected onto the plane of the
  11310. * triangle, lies within the triangle.
  11311. *
  11312. * @param {Vector3} point - The point in 3D space to test.
  11313. * @param {Vector3} a - The first corner of the triangle.
  11314. * @param {Vector3} b - The second corner of the triangle.
  11315. * @param {Vector3} c - The third corner of the triangle.
  11316. * @return {boolean} Whether the given point, when projected onto the plane of the
  11317. * triangle, lies within the triangle or not.
  11318. */
  11319. static containsPoint( point, a, b, c ) {
  11320. // if the triangle is degenerate then we can't contain a point
  11321. if ( this.getBarycoord( point, a, b, c, _v3$2 ) === null ) {
  11322. return false;
  11323. }
  11324. return ( _v3$2.x >= 0 ) && ( _v3$2.y >= 0 ) && ( ( _v3$2.x + _v3$2.y ) <= 1 );
  11325. }
  11326. /**
  11327. * Computes the value barycentrically interpolated for the given point on the
  11328. * triangle. Returns `null` if the triangle is degenerate.
  11329. *
  11330. * @param {Vector3} point - Position of interpolated point.
  11331. * @param {Vector3} p1 - The first corner of the triangle.
  11332. * @param {Vector3} p2 - The second corner of the triangle.
  11333. * @param {Vector3} p3 - The third corner of the triangle.
  11334. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11335. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11336. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11337. * @param {Vector3} target - The target vector that is used to store the method's result.
  11338. * @return {?Vector3} The interpolated value.
  11339. */
  11340. static getInterpolation( point, p1, p2, p3, v1, v2, v3, target ) {
  11341. if ( this.getBarycoord( point, p1, p2, p3, _v3$2 ) === null ) {
  11342. target.x = 0;
  11343. target.y = 0;
  11344. if ( 'z' in target ) target.z = 0;
  11345. if ( 'w' in target ) target.w = 0;
  11346. return null;
  11347. }
  11348. target.setScalar( 0 );
  11349. target.addScaledVector( v1, _v3$2.x );
  11350. target.addScaledVector( v2, _v3$2.y );
  11351. target.addScaledVector( v3, _v3$2.z );
  11352. return target;
  11353. }
  11354. /**
  11355. * Computes the value barycentrically interpolated for the given attribute and indices.
  11356. *
  11357. * @param {BufferAttribute} attr - The attribute to interpolate.
  11358. * @param {number} i1 - Index of first vertex.
  11359. * @param {number} i2 - Index of second vertex.
  11360. * @param {number} i3 - Index of third vertex.
  11361. * @param {Vector3} barycoord - The barycoordinate value to use to interpolate.
  11362. * @param {Vector3} target - The target vector that is used to store the method's result.
  11363. * @return {Vector3} The interpolated attribute value.
  11364. */
  11365. static getInterpolatedAttribute( attr, i1, i2, i3, barycoord, target ) {
  11366. _v40.setScalar( 0 );
  11367. _v41.setScalar( 0 );
  11368. _v42.setScalar( 0 );
  11369. _v40.fromBufferAttribute( attr, i1 );
  11370. _v41.fromBufferAttribute( attr, i2 );
  11371. _v42.fromBufferAttribute( attr, i3 );
  11372. target.setScalar( 0 );
  11373. target.addScaledVector( _v40, barycoord.x );
  11374. target.addScaledVector( _v41, barycoord.y );
  11375. target.addScaledVector( _v42, barycoord.z );
  11376. return target;
  11377. }
  11378. /**
  11379. * Returns `true` if the triangle is oriented towards the given direction.
  11380. *
  11381. * @param {Vector3} a - The first corner of the triangle.
  11382. * @param {Vector3} b - The second corner of the triangle.
  11383. * @param {Vector3} c - The third corner of the triangle.
  11384. * @param {Vector3} direction - The (normalized) direction vector.
  11385. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11386. */
  11387. static isFrontFacing( a, b, c, direction ) {
  11388. _v0$2.subVectors( c, b );
  11389. _v1$3.subVectors( a, b );
  11390. // strictly front facing
  11391. return ( _v0$2.cross( _v1$3 ).dot( direction ) < 0 ) ? true : false;
  11392. }
  11393. /**
  11394. * Sets the triangle's vertices by copying the given values.
  11395. *
  11396. * @param {Vector3} a - The first corner of the triangle.
  11397. * @param {Vector3} b - The second corner of the triangle.
  11398. * @param {Vector3} c - The third corner of the triangle.
  11399. * @return {Triangle} A reference to this triangle.
  11400. */
  11401. set( a, b, c ) {
  11402. this.a.copy( a );
  11403. this.b.copy( b );
  11404. this.c.copy( c );
  11405. return this;
  11406. }
  11407. /**
  11408. * Sets the triangle's vertices by copying the given array values.
  11409. *
  11410. * @param {Array<Vector3>} points - An array with 3D points.
  11411. * @param {number} i0 - The array index representing the first corner of the triangle.
  11412. * @param {number} i1 - The array index representing the second corner of the triangle.
  11413. * @param {number} i2 - The array index representing the third corner of the triangle.
  11414. * @return {Triangle} A reference to this triangle.
  11415. */
  11416. setFromPointsAndIndices( points, i0, i1, i2 ) {
  11417. this.a.copy( points[ i0 ] );
  11418. this.b.copy( points[ i1 ] );
  11419. this.c.copy( points[ i2 ] );
  11420. return this;
  11421. }
  11422. /**
  11423. * Sets the triangle's vertices by copying the given attribute values.
  11424. *
  11425. * @param {BufferAttribute} attribute - A buffer attribute with 3D points data.
  11426. * @param {number} i0 - The attribute index representing the first corner of the triangle.
  11427. * @param {number} i1 - The attribute index representing the second corner of the triangle.
  11428. * @param {number} i2 - The attribute index representing the third corner of the triangle.
  11429. * @return {Triangle} A reference to this triangle.
  11430. */
  11431. setFromAttributeAndIndices( attribute, i0, i1, i2 ) {
  11432. this.a.fromBufferAttribute( attribute, i0 );
  11433. this.b.fromBufferAttribute( attribute, i1 );
  11434. this.c.fromBufferAttribute( attribute, i2 );
  11435. return this;
  11436. }
  11437. /**
  11438. * Returns a new triangle with copied values from this instance.
  11439. *
  11440. * @return {Triangle} A clone of this instance.
  11441. */
  11442. clone() {
  11443. return new this.constructor().copy( this );
  11444. }
  11445. /**
  11446. * Copies the values of the given triangle to this instance.
  11447. *
  11448. * @param {Triangle} triangle - The triangle to copy.
  11449. * @return {Triangle} A reference to this triangle.
  11450. */
  11451. copy( triangle ) {
  11452. this.a.copy( triangle.a );
  11453. this.b.copy( triangle.b );
  11454. this.c.copy( triangle.c );
  11455. return this;
  11456. }
  11457. /**
  11458. * Computes the area of the triangle.
  11459. *
  11460. * @return {number} The triangle's area.
  11461. */
  11462. getArea() {
  11463. _v0$2.subVectors( this.c, this.b );
  11464. _v1$3.subVectors( this.a, this.b );
  11465. return _v0$2.cross( _v1$3 ).length() * 0.5;
  11466. }
  11467. /**
  11468. * Computes the midpoint of the triangle.
  11469. *
  11470. * @param {Vector3} target - The target vector that is used to store the method's result.
  11471. * @return {Vector3} The triangle's midpoint.
  11472. */
  11473. getMidpoint( target ) {
  11474. return target.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11475. }
  11476. /**
  11477. * Computes the normal of the triangle.
  11478. *
  11479. * @param {Vector3} target - The target vector that is used to store the method's result.
  11480. * @return {Vector3} The triangle's normal.
  11481. */
  11482. getNormal( target ) {
  11483. return Triangle.getNormal( this.a, this.b, this.c, target );
  11484. }
  11485. /**
  11486. * Computes a plane the triangle lies within.
  11487. *
  11488. * @param {Plane} target - The target vector that is used to store the method's result.
  11489. * @return {Plane} The plane the triangle lies within.
  11490. */
  11491. getPlane( target ) {
  11492. return target.setFromCoplanarPoints( this.a, this.b, this.c );
  11493. }
  11494. /**
  11495. * Computes a barycentric coordinates from the given vector.
  11496. * Returns `null` if the triangle is degenerate.
  11497. *
  11498. * @param {Vector3} point - A point in 3D space.
  11499. * @param {Vector3} target - The target vector that is used to store the method's result.
  11500. * @return {?Vector3} The barycentric coordinates for the given point
  11501. */
  11502. getBarycoord( point, target ) {
  11503. return Triangle.getBarycoord( point, this.a, this.b, this.c, target );
  11504. }
  11505. /**
  11506. * Computes the value barycentrically interpolated for the given point on the
  11507. * triangle. Returns `null` if the triangle is degenerate.
  11508. *
  11509. * @param {Vector3} point - Position of interpolated point.
  11510. * @param {Vector3} v1 - Value to interpolate of first vertex.
  11511. * @param {Vector3} v2 - Value to interpolate of second vertex.
  11512. * @param {Vector3} v3 - Value to interpolate of third vertex.
  11513. * @param {Vector3} target - The target vector that is used to store the method's result.
  11514. * @return {?Vector3} The interpolated value.
  11515. */
  11516. getInterpolation( point, v1, v2, v3, target ) {
  11517. return Triangle.getInterpolation( point, this.a, this.b, this.c, v1, v2, v3, target );
  11518. }
  11519. /**
  11520. * Returns `true` if the given point, when projected onto the plane of the
  11521. * triangle, lies within the triangle.
  11522. *
  11523. * @param {Vector3} point - The point in 3D space to test.
  11524. * @return {boolean} Whether the given point, when projected onto the plane of the
  11525. * triangle, lies within the triangle or not.
  11526. */
  11527. containsPoint( point ) {
  11528. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11529. }
  11530. /**
  11531. * Returns `true` if the triangle is oriented towards the given direction.
  11532. *
  11533. * @param {Vector3} direction - The (normalized) direction vector.
  11534. * @return {boolean} Whether the triangle is oriented towards the given direction or not.
  11535. */
  11536. isFrontFacing( direction ) {
  11537. return Triangle.isFrontFacing( this.a, this.b, this.c, direction );
  11538. }
  11539. /**
  11540. * Returns `true` if this triangle intersects with the given box.
  11541. *
  11542. * @param {Box3} box - The box to intersect.
  11543. * @return {boolean} Whether this triangle intersects with the given box or not.
  11544. */
  11545. intersectsBox( box ) {
  11546. return box.intersectsTriangle( this );
  11547. }
  11548. /**
  11549. * Returns the closest point on the triangle to the given point.
  11550. *
  11551. * @param {Vector3} p - The point to compute the closest point for.
  11552. * @param {Vector3} target - The target vector that is used to store the method's result.
  11553. * @return {Vector3} The closest point on the triangle.
  11554. */
  11555. closestPointToPoint( p, target ) {
  11556. const a = this.a, b = this.b, c = this.c;
  11557. let v, w;
  11558. // algorithm thanks to Real-Time Collision Detection by Christer Ericson,
  11559. // published by Morgan Kaufmann Publishers, (c) 2005 Elsevier Inc.,
  11560. // under the accompanying license; see chapter 5.1.5 for detailed explanation.
  11561. // basically, we're distinguishing which of the voronoi regions of the triangle
  11562. // the point lies in with the minimum amount of redundant computation.
  11563. _vab.subVectors( b, a );
  11564. _vac.subVectors( c, a );
  11565. _vap.subVectors( p, a );
  11566. const d1 = _vab.dot( _vap );
  11567. const d2 = _vac.dot( _vap );
  11568. if ( d1 <= 0 && d2 <= 0 ) {
  11569. // vertex region of A; barycentric coords (1, 0, 0)
  11570. return target.copy( a );
  11571. }
  11572. _vbp.subVectors( p, b );
  11573. const d3 = _vab.dot( _vbp );
  11574. const d4 = _vac.dot( _vbp );
  11575. if ( d3 >= 0 && d4 <= d3 ) {
  11576. // vertex region of B; barycentric coords (0, 1, 0)
  11577. return target.copy( b );
  11578. }
  11579. const vc = d1 * d4 - d3 * d2;
  11580. if ( vc <= 0 && d1 >= 0 && d3 <= 0 ) {
  11581. v = d1 / ( d1 - d3 );
  11582. // edge region of AB; barycentric coords (1-v, v, 0)
  11583. return target.copy( a ).addScaledVector( _vab, v );
  11584. }
  11585. _vcp.subVectors( p, c );
  11586. const d5 = _vab.dot( _vcp );
  11587. const d6 = _vac.dot( _vcp );
  11588. if ( d6 >= 0 && d5 <= d6 ) {
  11589. // vertex region of C; barycentric coords (0, 0, 1)
  11590. return target.copy( c );
  11591. }
  11592. const vb = d5 * d2 - d1 * d6;
  11593. if ( vb <= 0 && d2 >= 0 && d6 <= 0 ) {
  11594. w = d2 / ( d2 - d6 );
  11595. // edge region of AC; barycentric coords (1-w, 0, w)
  11596. return target.copy( a ).addScaledVector( _vac, w );
  11597. }
  11598. const va = d3 * d6 - d5 * d4;
  11599. if ( va <= 0 && ( d4 - d3 ) >= 0 && ( d5 - d6 ) >= 0 ) {
  11600. _vbc.subVectors( c, b );
  11601. w = ( d4 - d3 ) / ( ( d4 - d3 ) + ( d5 - d6 ) );
  11602. // edge region of BC; barycentric coords (0, 1-w, w)
  11603. return target.copy( b ).addScaledVector( _vbc, w ); // edge region of BC
  11604. }
  11605. // face region
  11606. const denom = 1 / ( va + vb + vc );
  11607. // u = va * denom
  11608. v = vb * denom;
  11609. w = vc * denom;
  11610. return target.copy( a ).addScaledVector( _vab, v ).addScaledVector( _vac, w );
  11611. }
  11612. /**
  11613. * Returns `true` if this triangle is equal with the given one.
  11614. *
  11615. * @param {Triangle} triangle - The triangle to test for equality.
  11616. * @return {boolean} Whether this triangle is equal with the given one.
  11617. */
  11618. equals( triangle ) {
  11619. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11620. }
  11621. }
  11622. const _colorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  11623. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  11624. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  11625. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  11626. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  11627. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  11628. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  11629. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  11630. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  11631. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  11632. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  11633. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  11634. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  11635. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  11636. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  11637. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  11638. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  11639. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  11640. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  11641. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  11642. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  11643. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  11644. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  11645. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  11646. const _hslA = { h: 0, s: 0, l: 0 };
  11647. const _hslB = { h: 0, s: 0, l: 0 };
  11648. function hue2rgb( p, q, t ) {
  11649. if ( t < 0 ) t += 1;
  11650. if ( t > 1 ) t -= 1;
  11651. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  11652. if ( t < 1 / 2 ) return q;
  11653. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  11654. return p;
  11655. }
  11656. /**
  11657. * A Color instance is represented by RGB components in the linear <i>working
  11658. * color space</i>, which defaults to `LinearSRGBColorSpace`. Inputs
  11659. * conventionally using `SRGBColorSpace` (such as hexadecimals and CSS
  11660. * strings) are converted to the working color space automatically.
  11661. *
  11662. * ```js
  11663. * // converted automatically from SRGBColorSpace to LinearSRGBColorSpace
  11664. * const color = new THREE.Color().setHex( 0x112233 );
  11665. * ```
  11666. * Source color spaces may be specified explicitly, to ensure correct conversions.
  11667. * ```js
  11668. * // assumed already LinearSRGBColorSpace; no conversion
  11669. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5 );
  11670. *
  11671. * // converted explicitly from SRGBColorSpace to LinearSRGBColorSpace
  11672. * const color = new THREE.Color().setRGB( 0.5, 0.5, 0.5, SRGBColorSpace );
  11673. * ```
  11674. * If THREE.ColorManagement is disabled, no conversions occur. For details,
  11675. * see <i>Color management</i>. Iterating through a Color instance will yield
  11676. * its components (r, g, b) in the corresponding order. A Color can be initialised
  11677. * in any of the following ways:
  11678. * ```js
  11679. * //empty constructor - will default white
  11680. * const color1 = new THREE.Color();
  11681. *
  11682. * //Hexadecimal color (recommended)
  11683. * const color2 = new THREE.Color( 0xff0000 );
  11684. *
  11685. * //RGB string
  11686. * const color3 = new THREE.Color("rgb(255, 0, 0)");
  11687. * const color4 = new THREE.Color("rgb(100%, 0%, 0%)");
  11688. *
  11689. * //X11 color name - all 140 color names are supported.
  11690. * //Note the lack of CamelCase in the name
  11691. * const color5 = new THREE.Color( 'skyblue' );
  11692. * //HSL string
  11693. * const color6 = new THREE.Color("hsl(0, 100%, 50%)");
  11694. *
  11695. * //Separate RGB values between 0 and 1
  11696. * const color7 = new THREE.Color( 1, 0, 0 );
  11697. * ```
  11698. */
  11699. class Color {
  11700. /**
  11701. * Constructs a new color.
  11702. *
  11703. * Note that standard method of specifying color in three.js is with a hexadecimal triplet,
  11704. * and that method is used throughout the rest of the documentation.
  11705. *
  11706. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11707. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11708. * @param {number} [g] - The green component.
  11709. * @param {number} [b] - The blue component.
  11710. */
  11711. constructor( r, g, b ) {
  11712. /**
  11713. * This flag can be used for type testing.
  11714. *
  11715. * @type {boolean}
  11716. * @readonly
  11717. * @default true
  11718. */
  11719. this.isColor = true;
  11720. /**
  11721. * The red component.
  11722. *
  11723. * @type {number}
  11724. * @default 1
  11725. */
  11726. this.r = 1;
  11727. /**
  11728. * The green component.
  11729. *
  11730. * @type {number}
  11731. * @default 1
  11732. */
  11733. this.g = 1;
  11734. /**
  11735. * The blue component.
  11736. *
  11737. * @type {number}
  11738. * @default 1
  11739. */
  11740. this.b = 1;
  11741. return this.set( r, g, b );
  11742. }
  11743. /**
  11744. * Sets the colors's components from the given values.
  11745. *
  11746. * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are
  11747. * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance.
  11748. * @param {number} [g] - The green component.
  11749. * @param {number} [b] - The blue component.
  11750. * @return {Color} A reference to this color.
  11751. */
  11752. set( r, g, b ) {
  11753. if ( g === undefined && b === undefined ) {
  11754. // r is THREE.Color, hex or string
  11755. const value = r;
  11756. if ( value && value.isColor ) {
  11757. this.copy( value );
  11758. } else if ( typeof value === 'number' ) {
  11759. this.setHex( value );
  11760. } else if ( typeof value === 'string' ) {
  11761. this.setStyle( value );
  11762. }
  11763. } else {
  11764. this.setRGB( r, g, b );
  11765. }
  11766. return this;
  11767. }
  11768. /**
  11769. * Sets the colors's components to the given scalar value.
  11770. *
  11771. * @param {number} scalar - The scalar value.
  11772. * @return {Color} A reference to this color.
  11773. */
  11774. setScalar( scalar ) {
  11775. this.r = scalar;
  11776. this.g = scalar;
  11777. this.b = scalar;
  11778. return this;
  11779. }
  11780. /**
  11781. * Sets this color from a hexadecimal value.
  11782. *
  11783. * @param {number} hex - The hexadecimal value.
  11784. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11785. * @return {Color} A reference to this color.
  11786. */
  11787. setHex( hex, colorSpace = SRGBColorSpace ) {
  11788. hex = Math.floor( hex );
  11789. this.r = ( hex >> 16 & 255 ) / 255;
  11790. this.g = ( hex >> 8 & 255 ) / 255;
  11791. this.b = ( hex & 255 ) / 255;
  11792. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11793. return this;
  11794. }
  11795. /**
  11796. * Sets this color from RGB values.
  11797. *
  11798. * @param {number} r - Red channel value between `0.0` and `1.0`.
  11799. * @param {number} g - Green channel value between `0.0` and `1.0`.
  11800. * @param {number} b - Blue channel value between `0.0` and `1.0`.
  11801. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11802. * @return {Color} A reference to this color.
  11803. */
  11804. setRGB( r, g, b, colorSpace = ColorManagement.workingColorSpace ) {
  11805. this.r = r;
  11806. this.g = g;
  11807. this.b = b;
  11808. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11809. return this;
  11810. }
  11811. /**
  11812. * Sets this color from RGB values.
  11813. *
  11814. * @param {number} h - Hue value between `0.0` and `1.0`.
  11815. * @param {number} s - Saturation value between `0.0` and `1.0`.
  11816. * @param {number} l - Lightness value between `0.0` and `1.0`.
  11817. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  11818. * @return {Color} A reference to this color.
  11819. */
  11820. setHSL( h, s, l, colorSpace = ColorManagement.workingColorSpace ) {
  11821. // h,s,l ranges are in 0.0 - 1.0
  11822. h = euclideanModulo( h, 1 );
  11823. s = clamp( s, 0, 1 );
  11824. l = clamp( l, 0, 1 );
  11825. if ( s === 0 ) {
  11826. this.r = this.g = this.b = l;
  11827. } else {
  11828. const p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  11829. const q = ( 2 * l ) - p;
  11830. this.r = hue2rgb( q, p, h + 1 / 3 );
  11831. this.g = hue2rgb( q, p, h );
  11832. this.b = hue2rgb( q, p, h - 1 / 3 );
  11833. }
  11834. ColorManagement.colorSpaceToWorking( this, colorSpace );
  11835. return this;
  11836. }
  11837. /**
  11838. * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`,
  11839. * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or
  11840. * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) -
  11841. * all 140 color names are supported).
  11842. *
  11843. * @param {string} style - Color as a CSS-style string.
  11844. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11845. * @return {Color} A reference to this color.
  11846. */
  11847. setStyle( style, colorSpace = SRGBColorSpace ) {
  11848. function handleAlpha( string ) {
  11849. if ( string === undefined ) return;
  11850. if ( parseFloat( string ) < 1 ) {
  11851. warn( 'Color: Alpha component of ' + style + ' will be ignored.' );
  11852. }
  11853. }
  11854. let m;
  11855. if ( m = /^(\w+)\(([^\)]*)\)/.exec( style ) ) {
  11856. // rgb / hsl
  11857. let color;
  11858. const name = m[ 1 ];
  11859. const components = m[ 2 ];
  11860. switch ( name ) {
  11861. case 'rgb':
  11862. case 'rgba':
  11863. if ( color = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11864. // rgb(255,0,0) rgba(255,0,0,0.5)
  11865. handleAlpha( color[ 4 ] );
  11866. return this.setRGB(
  11867. Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255,
  11868. Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255,
  11869. Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255,
  11870. colorSpace
  11871. );
  11872. }
  11873. if ( color = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11874. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  11875. handleAlpha( color[ 4 ] );
  11876. return this.setRGB(
  11877. Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100,
  11878. Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100,
  11879. Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100,
  11880. colorSpace
  11881. );
  11882. }
  11883. break;
  11884. case 'hsl':
  11885. case 'hsla':
  11886. if ( color = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec( components ) ) {
  11887. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  11888. handleAlpha( color[ 4 ] );
  11889. return this.setHSL(
  11890. parseFloat( color[ 1 ] ) / 360,
  11891. parseFloat( color[ 2 ] ) / 100,
  11892. parseFloat( color[ 3 ] ) / 100,
  11893. colorSpace
  11894. );
  11895. }
  11896. break;
  11897. default:
  11898. warn( 'Color: Unknown color model ' + style );
  11899. }
  11900. } else if ( m = /^\#([A-Fa-f\d]+)$/.exec( style ) ) {
  11901. // hex color
  11902. const hex = m[ 1 ];
  11903. const size = hex.length;
  11904. if ( size === 3 ) {
  11905. // #ff0
  11906. return this.setRGB(
  11907. parseInt( hex.charAt( 0 ), 16 ) / 15,
  11908. parseInt( hex.charAt( 1 ), 16 ) / 15,
  11909. parseInt( hex.charAt( 2 ), 16 ) / 15,
  11910. colorSpace
  11911. );
  11912. } else if ( size === 6 ) {
  11913. // #ff0000
  11914. return this.setHex( parseInt( hex, 16 ), colorSpace );
  11915. } else {
  11916. warn( 'Color: Invalid hex color ' + style );
  11917. }
  11918. } else if ( style && style.length > 0 ) {
  11919. return this.setColorName( style, colorSpace );
  11920. }
  11921. return this;
  11922. }
  11923. /**
  11924. * Sets this color from a color name. Faster than {@link Color#setStyle} if
  11925. * you don't need the other CSS-style formats.
  11926. *
  11927. * For convenience, the list of names is exposed in `Color.NAMES` as a hash.
  11928. * ```js
  11929. * Color.NAMES.aliceblue // returns 0xF0F8FF
  11930. * ```
  11931. *
  11932. * @param {string} style - The color name.
  11933. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  11934. * @return {Color} A reference to this color.
  11935. */
  11936. setColorName( style, colorSpace = SRGBColorSpace ) {
  11937. // color keywords
  11938. const hex = _colorKeywords[ style.toLowerCase() ];
  11939. if ( hex !== undefined ) {
  11940. // red
  11941. this.setHex( hex, colorSpace );
  11942. } else {
  11943. // unknown color
  11944. warn( 'Color: Unknown color ' + style );
  11945. }
  11946. return this;
  11947. }
  11948. /**
  11949. * Returns a new color with copied values from this instance.
  11950. *
  11951. * @return {Color} A clone of this instance.
  11952. */
  11953. clone() {
  11954. return new this.constructor( this.r, this.g, this.b );
  11955. }
  11956. /**
  11957. * Copies the values of the given color to this instance.
  11958. *
  11959. * @param {Color} color - The color to copy.
  11960. * @return {Color} A reference to this color.
  11961. */
  11962. copy( color ) {
  11963. this.r = color.r;
  11964. this.g = color.g;
  11965. this.b = color.b;
  11966. return this;
  11967. }
  11968. /**
  11969. * Copies the given color into this color, and then converts this color from
  11970. * `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11971. *
  11972. * @param {Color} color - The color to copy/convert.
  11973. * @return {Color} A reference to this color.
  11974. */
  11975. copySRGBToLinear( color ) {
  11976. this.r = SRGBToLinear( color.r );
  11977. this.g = SRGBToLinear( color.g );
  11978. this.b = SRGBToLinear( color.b );
  11979. return this;
  11980. }
  11981. /**
  11982. * Copies the given color into this color, and then converts this color from
  11983. * `LinearSRGBColorSpace` to `SRGBColorSpace`.
  11984. *
  11985. * @param {Color} color - The color to copy/convert.
  11986. * @return {Color} A reference to this color.
  11987. */
  11988. copyLinearToSRGB( color ) {
  11989. this.r = LinearToSRGB( color.r );
  11990. this.g = LinearToSRGB( color.g );
  11991. this.b = LinearToSRGB( color.b );
  11992. return this;
  11993. }
  11994. /**
  11995. * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`.
  11996. *
  11997. * @return {Color} A reference to this color.
  11998. */
  11999. convertSRGBToLinear() {
  12000. this.copySRGBToLinear( this );
  12001. return this;
  12002. }
  12003. /**
  12004. * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`.
  12005. *
  12006. * @return {Color} A reference to this color.
  12007. */
  12008. convertLinearToSRGB() {
  12009. this.copyLinearToSRGB( this );
  12010. return this;
  12011. }
  12012. /**
  12013. * Returns the hexadecimal value of this color.
  12014. *
  12015. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12016. * @return {number} The hexadecimal value.
  12017. */
  12018. getHex( colorSpace = SRGBColorSpace ) {
  12019. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12020. 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 ) );
  12021. }
  12022. /**
  12023. * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF').
  12024. *
  12025. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12026. * @return {string} The hexadecimal value as a string.
  12027. */
  12028. getHexString( colorSpace = SRGBColorSpace ) {
  12029. return ( '000000' + this.getHex( colorSpace ).toString( 16 ) ).slice( -6 );
  12030. }
  12031. /**
  12032. * Converts the colors RGB values into the HSL format and stores them into the
  12033. * given target object.
  12034. *
  12035. * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result.
  12036. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12037. * @return {{h:number,s:number,l:number}} The HSL representation of this color.
  12038. */
  12039. getHSL( target, colorSpace = ColorManagement.workingColorSpace ) {
  12040. // h,s,l ranges are in 0.0 - 1.0
  12041. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12042. const r = _color.r, g = _color.g, b = _color.b;
  12043. const max = Math.max( r, g, b );
  12044. const min = Math.min( r, g, b );
  12045. let hue, saturation;
  12046. const lightness = ( min + max ) / 2.0;
  12047. if ( min === max ) {
  12048. hue = 0;
  12049. saturation = 0;
  12050. } else {
  12051. const delta = max - min;
  12052. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  12053. switch ( max ) {
  12054. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  12055. case g: hue = ( b - r ) / delta + 2; break;
  12056. case b: hue = ( r - g ) / delta + 4; break;
  12057. }
  12058. hue /= 6;
  12059. }
  12060. target.h = hue;
  12061. target.s = saturation;
  12062. target.l = lightness;
  12063. return target;
  12064. }
  12065. /**
  12066. * Returns the RGB values of this color and stores them into the given target object.
  12067. *
  12068. * @param {Color} target - The target color that is used to store the method's result.
  12069. * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space.
  12070. * @return {Color} The RGB representation of this color.
  12071. */
  12072. getRGB( target, colorSpace = ColorManagement.workingColorSpace ) {
  12073. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12074. target.r = _color.r;
  12075. target.g = _color.g;
  12076. target.b = _color.b;
  12077. return target;
  12078. }
  12079. /**
  12080. * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`.
  12081. *
  12082. * @param {string} [colorSpace=SRGBColorSpace] - The color space.
  12083. * @return {string} The CSS representation of this color.
  12084. */
  12085. getStyle( colorSpace = SRGBColorSpace ) {
  12086. ColorManagement.workingToColorSpace( _color.copy( this ), colorSpace );
  12087. const r = _color.r, g = _color.g, b = _color.b;
  12088. if ( colorSpace !== SRGBColorSpace ) {
  12089. // Requires CSS Color Module Level 4 (https://www.w3.org/TR/css-color-4/).
  12090. return `color(${ colorSpace } ${ r.toFixed( 3 ) } ${ g.toFixed( 3 ) } ${ b.toFixed( 3 ) })`;
  12091. }
  12092. return `rgb(${ Math.round( r * 255 ) },${ Math.round( g * 255 ) },${ Math.round( b * 255 ) })`;
  12093. }
  12094. /**
  12095. * Adds the given HSL values to this color's values.
  12096. * Internally, this converts the color's RGB values to HSL, adds HSL
  12097. * and then converts the color back to RGB.
  12098. *
  12099. * @param {number} h - Hue value between `0.0` and `1.0`.
  12100. * @param {number} s - Saturation value between `0.0` and `1.0`.
  12101. * @param {number} l - Lightness value between `0.0` and `1.0`.
  12102. * @return {Color} A reference to this color.
  12103. */
  12104. offsetHSL( h, s, l ) {
  12105. this.getHSL( _hslA );
  12106. return this.setHSL( _hslA.h + h, _hslA.s + s, _hslA.l + l );
  12107. }
  12108. /**
  12109. * Adds the RGB values of the given color to the RGB values of this color.
  12110. *
  12111. * @param {Color} color - The color to add.
  12112. * @return {Color} A reference to this color.
  12113. */
  12114. add( color ) {
  12115. this.r += color.r;
  12116. this.g += color.g;
  12117. this.b += color.b;
  12118. return this;
  12119. }
  12120. /**
  12121. * Adds the RGB values of the given colors and stores the result in this instance.
  12122. *
  12123. * @param {Color} color1 - The first color.
  12124. * @param {Color} color2 - The second color.
  12125. * @return {Color} A reference to this color.
  12126. */
  12127. addColors( color1, color2 ) {
  12128. this.r = color1.r + color2.r;
  12129. this.g = color1.g + color2.g;
  12130. this.b = color1.b + color2.b;
  12131. return this;
  12132. }
  12133. /**
  12134. * Adds the given scalar value to the RGB values of this color.
  12135. *
  12136. * @param {number} s - The scalar to add.
  12137. * @return {Color} A reference to this color.
  12138. */
  12139. addScalar( s ) {
  12140. this.r += s;
  12141. this.g += s;
  12142. this.b += s;
  12143. return this;
  12144. }
  12145. /**
  12146. * Subtracts the RGB values of the given color from the RGB values of this color.
  12147. *
  12148. * @param {Color} color - The color to subtract.
  12149. * @return {Color} A reference to this color.
  12150. */
  12151. sub( color ) {
  12152. this.r = Math.max( 0, this.r - color.r );
  12153. this.g = Math.max( 0, this.g - color.g );
  12154. this.b = Math.max( 0, this.b - color.b );
  12155. return this;
  12156. }
  12157. /**
  12158. * Multiplies the RGB values of the given color with the RGB values of this color.
  12159. *
  12160. * @param {Color} color - The color to multiply.
  12161. * @return {Color} A reference to this color.
  12162. */
  12163. multiply( color ) {
  12164. this.r *= color.r;
  12165. this.g *= color.g;
  12166. this.b *= color.b;
  12167. return this;
  12168. }
  12169. /**
  12170. * Multiplies the given scalar value with the RGB values of this color.
  12171. *
  12172. * @param {number} s - The scalar to multiply.
  12173. * @return {Color} A reference to this color.
  12174. */
  12175. multiplyScalar( s ) {
  12176. this.r *= s;
  12177. this.g *= s;
  12178. this.b *= s;
  12179. return this;
  12180. }
  12181. /**
  12182. * Linearly interpolates this color's RGB values toward the RGB values of the
  12183. * given color. The alpha argument can be thought of as the ratio between
  12184. * the two colors, where `0.0` is this color and `1.0` is the first argument.
  12185. *
  12186. * @param {Color} color - The color to converge on.
  12187. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12188. * @return {Color} A reference to this color.
  12189. */
  12190. lerp( color, alpha ) {
  12191. this.r += ( color.r - this.r ) * alpha;
  12192. this.g += ( color.g - this.g ) * alpha;
  12193. this.b += ( color.b - this.b ) * alpha;
  12194. return this;
  12195. }
  12196. /**
  12197. * Linearly interpolates between the given colors and stores the result in this instance.
  12198. * The alpha argument can be thought of as the ratio between the two colors, where `0.0`
  12199. * is the first and `1.0` is the second color.
  12200. *
  12201. * @param {Color} color1 - The first color.
  12202. * @param {Color} color2 - The second color.
  12203. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12204. * @return {Color} A reference to this color.
  12205. */
  12206. lerpColors( color1, color2, alpha ) {
  12207. this.r = color1.r + ( color2.r - color1.r ) * alpha;
  12208. this.g = color1.g + ( color2.g - color1.g ) * alpha;
  12209. this.b = color1.b + ( color2.b - color1.b ) * alpha;
  12210. return this;
  12211. }
  12212. /**
  12213. * Linearly interpolates this color's HSL values toward the HSL values of the
  12214. * given color. It differs from {@link Color#lerp} by not interpolating straight
  12215. * from one color to the other, but instead going through all the hues in between
  12216. * those two colors. The alpha argument can be thought of as the ratio between
  12217. * the two colors, where 0.0 is this color and 1.0 is the first argument.
  12218. *
  12219. * @param {Color} color - The color to converge on.
  12220. * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`.
  12221. * @return {Color} A reference to this color.
  12222. */
  12223. lerpHSL( color, alpha ) {
  12224. this.getHSL( _hslA );
  12225. color.getHSL( _hslB );
  12226. const h = lerp( _hslA.h, _hslB.h, alpha );
  12227. const s = lerp( _hslA.s, _hslB.s, alpha );
  12228. const l = lerp( _hslA.l, _hslB.l, alpha );
  12229. this.setHSL( h, s, l );
  12230. return this;
  12231. }
  12232. /**
  12233. * Sets the color's RGB components from the given 3D vector.
  12234. *
  12235. * @param {Vector3} v - The vector to set.
  12236. * @return {Color} A reference to this color.
  12237. */
  12238. setFromVector3( v ) {
  12239. this.r = v.x;
  12240. this.g = v.y;
  12241. this.b = v.z;
  12242. return this;
  12243. }
  12244. /**
  12245. * Transforms this color with the given 3x3 matrix.
  12246. *
  12247. * @param {Matrix3} m - The matrix.
  12248. * @return {Color} A reference to this color.
  12249. */
  12250. applyMatrix3( m ) {
  12251. const r = this.r, g = this.g, b = this.b;
  12252. const e = m.elements;
  12253. this.r = e[ 0 ] * r + e[ 3 ] * g + e[ 6 ] * b;
  12254. this.g = e[ 1 ] * r + e[ 4 ] * g + e[ 7 ] * b;
  12255. this.b = e[ 2 ] * r + e[ 5 ] * g + e[ 8 ] * b;
  12256. return this;
  12257. }
  12258. /**
  12259. * Returns `true` if this color is equal with the given one.
  12260. *
  12261. * @param {Color} c - The color to test for equality.
  12262. * @return {boolean} Whether this bounding color is equal with the given one.
  12263. */
  12264. equals( c ) {
  12265. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  12266. }
  12267. /**
  12268. * Sets this color's RGB components from the given array.
  12269. *
  12270. * @param {Array<number>} array - An array holding the RGB values.
  12271. * @param {number} [offset=0] - The offset into the array.
  12272. * @return {Color} A reference to this color.
  12273. */
  12274. fromArray( array, offset = 0 ) {
  12275. this.r = array[ offset ];
  12276. this.g = array[ offset + 1 ];
  12277. this.b = array[ offset + 2 ];
  12278. return this;
  12279. }
  12280. /**
  12281. * Writes the RGB components of this color to the given array. If no array is provided,
  12282. * the method returns a new instance.
  12283. *
  12284. * @param {Array<number>} [array=[]] - The target array holding the color components.
  12285. * @param {number} [offset=0] - Index of the first element in the array.
  12286. * @return {Array<number>} The color components.
  12287. */
  12288. toArray( array = [], offset = 0 ) {
  12289. array[ offset ] = this.r;
  12290. array[ offset + 1 ] = this.g;
  12291. array[ offset + 2 ] = this.b;
  12292. return array;
  12293. }
  12294. /**
  12295. * Sets the components of this color from the given buffer attribute.
  12296. *
  12297. * @param {BufferAttribute} attribute - The buffer attribute holding color data.
  12298. * @param {number} index - The index into the attribute.
  12299. * @return {Color} A reference to this color.
  12300. */
  12301. fromBufferAttribute( attribute, index ) {
  12302. this.r = attribute.getX( index );
  12303. this.g = attribute.getY( index );
  12304. this.b = attribute.getZ( index );
  12305. return this;
  12306. }
  12307. /**
  12308. * This methods defines the serialization result of this class. Returns the color
  12309. * as a hexadecimal value.
  12310. *
  12311. * @return {number} The hexadecimal value.
  12312. */
  12313. toJSON() {
  12314. return this.getHex();
  12315. }
  12316. *[ Symbol.iterator ]() {
  12317. yield this.r;
  12318. yield this.g;
  12319. yield this.b;
  12320. }
  12321. }
  12322. const _color = /*@__PURE__*/ new Color();
  12323. /**
  12324. * A dictionary with X11 color names.
  12325. *
  12326. * Note that multiple words such as Dark Orange become the string 'darkorange'.
  12327. *
  12328. * @static
  12329. * @type {Object}
  12330. */
  12331. Color.NAMES = _colorKeywords;
  12332. let _materialId = 0;
  12333. /**
  12334. * Abstract base class for materials.
  12335. *
  12336. * Materials define the appearance of renderable 3D objects.
  12337. *
  12338. * @abstract
  12339. * @augments EventDispatcher
  12340. */
  12341. class Material extends EventDispatcher {
  12342. /**
  12343. * Constructs a new material.
  12344. */
  12345. constructor() {
  12346. super();
  12347. /**
  12348. * This flag can be used for type testing.
  12349. *
  12350. * @type {boolean}
  12351. * @readonly
  12352. * @default true
  12353. */
  12354. this.isMaterial = true;
  12355. /**
  12356. * The ID of the material.
  12357. *
  12358. * @name Material#id
  12359. * @type {number}
  12360. * @readonly
  12361. */
  12362. Object.defineProperty( this, 'id', { value: _materialId ++ } );
  12363. /**
  12364. * The UUID of the material.
  12365. *
  12366. * @type {string}
  12367. * @readonly
  12368. */
  12369. this.uuid = generateUUID();
  12370. /**
  12371. * The name of the material.
  12372. *
  12373. * @type {string}
  12374. */
  12375. this.name = '';
  12376. /**
  12377. * The type property is used for detecting the object type
  12378. * in context of serialization/deserialization.
  12379. *
  12380. * @type {string}
  12381. * @readonly
  12382. */
  12383. this.type = 'Material';
  12384. /**
  12385. * Defines the blending type of the material.
  12386. *
  12387. * It must be set to `CustomBlending` if custom blending properties like
  12388. * {@link Material#blendSrc}, {@link Material#blendDst} or {@link Material#blendEquation}
  12389. * should have any effect.
  12390. *
  12391. * @type {(NoBlending|NormalBlending|AdditiveBlending|SubtractiveBlending|MultiplyBlending|CustomBlending)}
  12392. * @default NormalBlending
  12393. */
  12394. this.blending = NormalBlending;
  12395. /**
  12396. * Defines which side of faces will be rendered - front, back or both.
  12397. *
  12398. * @type {(FrontSide|BackSide|DoubleSide)}
  12399. * @default FrontSide
  12400. */
  12401. this.side = FrontSide;
  12402. /**
  12403. * If set to `true`, vertex colors should be used.
  12404. *
  12405. * The engine supports RGB and RGBA vertex colors depending on whether a three (RGB) or
  12406. * four (RGBA) component color buffer attribute is used.
  12407. *
  12408. * @type {boolean}
  12409. * @default false
  12410. */
  12411. this.vertexColors = false;
  12412. /**
  12413. * Defines how transparent the material is.
  12414. * A value of `0.0` indicates fully transparent, `1.0` is fully opaque.
  12415. *
  12416. * If the {@link Material#transparent} is not set to `true`,
  12417. * the material will remain fully opaque and this value will only affect its color.
  12418. *
  12419. * @type {number}
  12420. * @default 1
  12421. */
  12422. this.opacity = 1;
  12423. /**
  12424. * Defines whether this material is transparent. This has an effect on
  12425. * rendering as transparent objects need special treatment and are rendered
  12426. * after non-transparent objects.
  12427. *
  12428. * When set to true, the extent to which the material is transparent is
  12429. * controlled by {@link Material#opacity}.
  12430. *
  12431. * @type {boolean}
  12432. * @default false
  12433. */
  12434. this.transparent = false;
  12435. /**
  12436. * Enables alpha hashed transparency, an alternative to {@link Material#transparent} or
  12437. * {@link Material#alphaTest}. The material will not be rendered if opacity is lower than
  12438. * a random threshold. Randomization introduces some grain or noise, but approximates alpha
  12439. * blending without the associated problems of sorting. Using TAA can reduce the resulting noise.
  12440. *
  12441. * @type {boolean}
  12442. * @default false
  12443. */
  12444. this.alphaHash = false;
  12445. /**
  12446. * Defines the blending source factor.
  12447. *
  12448. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12449. * @default SrcAlphaFactor
  12450. */
  12451. this.blendSrc = SrcAlphaFactor;
  12452. /**
  12453. * Defines the blending destination factor.
  12454. *
  12455. * @type {(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12456. * @default OneMinusSrcAlphaFactor
  12457. */
  12458. this.blendDst = OneMinusSrcAlphaFactor;
  12459. /**
  12460. * Defines the blending equation.
  12461. *
  12462. * @type {(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12463. * @default AddEquation
  12464. */
  12465. this.blendEquation = AddEquation;
  12466. /**
  12467. * Defines the blending source alpha factor.
  12468. *
  12469. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12470. * @default null
  12471. */
  12472. this.blendSrcAlpha = null;
  12473. /**
  12474. * Defines the blending destination alpha factor.
  12475. *
  12476. * @type {?(ZeroFactor|OneFactor|SrcColorFactor|OneMinusSrcColorFactor|SrcAlphaFactor|OneMinusSrcAlphaFactor|DstAlphaFactor|OneMinusDstAlphaFactor|DstColorFactor|OneMinusDstColorFactor|SrcAlphaSaturateFactor|ConstantColorFactor|OneMinusConstantColorFactor|ConstantAlphaFactor|OneMinusConstantAlphaFactor)}
  12477. * @default null
  12478. */
  12479. this.blendDstAlpha = null;
  12480. /**
  12481. * Defines the blending equation of the alpha channel.
  12482. *
  12483. * @type {?(AddEquation|SubtractEquation|ReverseSubtractEquation|MinEquation|MaxEquation)}
  12484. * @default null
  12485. */
  12486. this.blendEquationAlpha = null;
  12487. /**
  12488. * Represents the RGB values of the constant blend color.
  12489. *
  12490. * This property has only an effect when using custom blending with `ConstantColor` or `OneMinusConstantColor`.
  12491. *
  12492. * @type {Color}
  12493. * @default (0,0,0)
  12494. */
  12495. this.blendColor = new Color( 0, 0, 0 );
  12496. /**
  12497. * Represents the alpha value of the constant blend color.
  12498. *
  12499. * This property has only an effect when using custom blending with `ConstantAlpha` or `OneMinusConstantAlpha`.
  12500. *
  12501. * @type {number}
  12502. * @default 0
  12503. */
  12504. this.blendAlpha = 0;
  12505. /**
  12506. * Defines the depth function.
  12507. *
  12508. * @type {(NeverDepth|AlwaysDepth|LessDepth|LessEqualDepth|EqualDepth|GreaterEqualDepth|GreaterDepth|NotEqualDepth)}
  12509. * @default LessEqualDepth
  12510. */
  12511. this.depthFunc = LessEqualDepth;
  12512. /**
  12513. * Whether to have depth test enabled when rendering this material.
  12514. * When the depth test is disabled, the depth write will also be implicitly disabled.
  12515. *
  12516. * @type {boolean}
  12517. * @default true
  12518. */
  12519. this.depthTest = true;
  12520. /**
  12521. * Whether rendering this material has any effect on the depth buffer.
  12522. *
  12523. * When drawing 2D overlays it can be useful to disable the depth writing in
  12524. * order to layer several things together without creating z-index artifacts.
  12525. *
  12526. * @type {boolean}
  12527. * @default true
  12528. */
  12529. this.depthWrite = true;
  12530. /**
  12531. * The bit mask to use when writing to the stencil buffer.
  12532. *
  12533. * @type {number}
  12534. * @default 0xff
  12535. */
  12536. this.stencilWriteMask = 0xff;
  12537. /**
  12538. * The stencil comparison function to use.
  12539. *
  12540. * @type {NeverStencilFunc|LessStencilFunc|EqualStencilFunc|LessEqualStencilFunc|GreaterStencilFunc|NotEqualStencilFunc|GreaterEqualStencilFunc|AlwaysStencilFunc}
  12541. * @default AlwaysStencilFunc
  12542. */
  12543. this.stencilFunc = AlwaysStencilFunc;
  12544. /**
  12545. * The value to use when performing stencil comparisons or stencil operations.
  12546. *
  12547. * @type {number}
  12548. * @default 0
  12549. */
  12550. this.stencilRef = 0;
  12551. /**
  12552. * The bit mask to use when comparing against the stencil buffer.
  12553. *
  12554. * @type {number}
  12555. * @default 0xff
  12556. */
  12557. this.stencilFuncMask = 0xff;
  12558. /**
  12559. * Which stencil operation to perform when the comparison function returns `false`.
  12560. *
  12561. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12562. * @default KeepStencilOp
  12563. */
  12564. this.stencilFail = KeepStencilOp;
  12565. /**
  12566. * Which stencil operation to perform when the comparison function returns
  12567. * `true` but the depth test fails.
  12568. *
  12569. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12570. * @default KeepStencilOp
  12571. */
  12572. this.stencilZFail = KeepStencilOp;
  12573. /**
  12574. * Which stencil operation to perform when the comparison function returns
  12575. * `true` and the depth test passes.
  12576. *
  12577. * @type {ZeroStencilOp|KeepStencilOp|ReplaceStencilOp|IncrementStencilOp|DecrementStencilOp|IncrementWrapStencilOp|DecrementWrapStencilOp|InvertStencilOp}
  12578. * @default KeepStencilOp
  12579. */
  12580. this.stencilZPass = KeepStencilOp;
  12581. /**
  12582. * Whether stencil operations are performed against the stencil buffer. In
  12583. * order to perform writes or comparisons against the stencil buffer this
  12584. * value must be `true`.
  12585. *
  12586. * @type {boolean}
  12587. * @default false
  12588. */
  12589. this.stencilWrite = false;
  12590. /**
  12591. * User-defined clipping planes specified as THREE.Plane objects in world
  12592. * space. These planes apply to the objects this material is attached to.
  12593. * Points in space whose signed distance to the plane is negative are clipped
  12594. * (not rendered). This requires {@link WebGLRenderer#localClippingEnabled} to
  12595. * be `true`.
  12596. *
  12597. * @type {?Array<Plane>}
  12598. * @default null
  12599. */
  12600. this.clippingPlanes = null;
  12601. /**
  12602. * Changes the behavior of clipping planes so that only their intersection is
  12603. * clipped, rather than their union.
  12604. *
  12605. * @type {boolean}
  12606. * @default false
  12607. */
  12608. this.clipIntersection = false;
  12609. /**
  12610. * Defines whether to clip shadows according to the clipping planes specified
  12611. * on this material.
  12612. *
  12613. * @type {boolean}
  12614. * @default false
  12615. */
  12616. this.clipShadows = false;
  12617. /**
  12618. * Defines which side of faces cast shadows. If `null`, the side casting shadows
  12619. * is determined as follows:
  12620. *
  12621. * - When {@link Material#side} is set to `FrontSide`, the back side cast shadows.
  12622. * - When {@link Material#side} is set to `BackSide`, the front side cast shadows.
  12623. * - When {@link Material#side} is set to `DoubleSide`, both sides cast shadows.
  12624. *
  12625. * @type {?(FrontSide|BackSide|DoubleSide)}
  12626. * @default null
  12627. */
  12628. this.shadowSide = null;
  12629. /**
  12630. * Whether to render the material's color.
  12631. *
  12632. * This can be used in conjunction with {@link Object3D#renderOder} to create invisible
  12633. * objects that occlude other objects.
  12634. *
  12635. * @type {boolean}
  12636. * @default true
  12637. */
  12638. this.colorWrite = true;
  12639. /**
  12640. * Override the renderer's default precision for this material.
  12641. *
  12642. * @type {?('highp'|'mediump'|'lowp')}
  12643. * @default null
  12644. */
  12645. this.precision = null;
  12646. /**
  12647. * Whether to use polygon offset or not. When enabled, each fragment's depth value will
  12648. * be offset after it is interpolated from the depth values of the appropriate vertices.
  12649. * The offset is added before the depth test is performed and before the value is written
  12650. * into the depth buffer.
  12651. *
  12652. * Can be useful for rendering hidden-line images, for applying decals to surfaces, and for
  12653. * rendering solids with highlighted edges.
  12654. *
  12655. * @type {boolean}
  12656. * @default false
  12657. */
  12658. this.polygonOffset = false;
  12659. /**
  12660. * Specifies a scale factor that is used to create a variable depth offset for each polygon.
  12661. *
  12662. * @type {number}
  12663. * @default 0
  12664. */
  12665. this.polygonOffsetFactor = 0;
  12666. /**
  12667. * Is multiplied by an implementation-specific value to create a constant depth offset.
  12668. *
  12669. * @type {number}
  12670. * @default 0
  12671. */
  12672. this.polygonOffsetUnits = 0;
  12673. /**
  12674. * Whether to apply dithering to the color to remove the appearance of banding.
  12675. *
  12676. * @type {boolean}
  12677. * @default false
  12678. */
  12679. this.dithering = false;
  12680. /**
  12681. * Whether alpha to coverage should be enabled or not. Can only be used with MSAA-enabled contexts
  12682. * (meaning when the renderer was created with *antialias* parameter set to `true`). Enabling this
  12683. * will smooth aliasing on clip plane edges and alphaTest-clipped edges.
  12684. *
  12685. * @type {boolean}
  12686. * @default false
  12687. */
  12688. this.alphaToCoverage = false;
  12689. /**
  12690. * Whether to premultiply the alpha (transparency) value.
  12691. *
  12692. * @type {boolean}
  12693. * @default false
  12694. */
  12695. this.premultipliedAlpha = false;
  12696. /**
  12697. * Whether double-sided, transparent objects should be rendered with a single pass or not.
  12698. *
  12699. * The engine renders double-sided, transparent objects with two draw calls (back faces first,
  12700. * then front faces) to mitigate transparency artifacts. There are scenarios however where this
  12701. * approach produces no quality gains but still doubles draw calls e.g. when rendering flat
  12702. * vegetation like grass sprites. In these cases, set the `forceSinglePass` flag to `true` to
  12703. * disable the two pass rendering to avoid performance issues.
  12704. *
  12705. * @type {boolean}
  12706. * @default false
  12707. */
  12708. this.forceSinglePass = false;
  12709. /**
  12710. * Whether it's possible to override the material with {@link Scene#overrideMaterial} or not.
  12711. *
  12712. * @type {boolean}
  12713. * @default true
  12714. */
  12715. this.allowOverride = true;
  12716. /**
  12717. * Defines whether 3D objects using this material are visible.
  12718. *
  12719. * @type {boolean}
  12720. * @default true
  12721. */
  12722. this.visible = true;
  12723. /**
  12724. * Defines whether this material is tone mapped according to the renderer's tone mapping setting.
  12725. *
  12726. * It is ignored when rendering to a render target or using post processing or when using
  12727. * `WebGPURenderer`. In all these cases, all materials are honored by tone mapping.
  12728. *
  12729. * @type {boolean}
  12730. * @default true
  12731. */
  12732. this.toneMapped = true;
  12733. /**
  12734. * An object that can be used to store custom data about the Material. It
  12735. * should not hold references to functions as these will not be cloned.
  12736. *
  12737. * @type {Object}
  12738. */
  12739. this.userData = {};
  12740. /**
  12741. * This starts at `0` and counts how many times {@link Material#needsUpdate} is set to `true`.
  12742. *
  12743. * @type {number}
  12744. * @readonly
  12745. * @default 0
  12746. */
  12747. this.version = 0;
  12748. this._alphaTest = 0;
  12749. }
  12750. /**
  12751. * Sets the alpha value to be used when running an alpha test. The material
  12752. * will not be rendered if the opacity is lower than this value.
  12753. *
  12754. * @type {number}
  12755. * @readonly
  12756. * @default 0
  12757. */
  12758. get alphaTest() {
  12759. return this._alphaTest;
  12760. }
  12761. set alphaTest( value ) {
  12762. if ( this._alphaTest > 0 !== value > 0 ) {
  12763. this.version ++;
  12764. }
  12765. this._alphaTest = value;
  12766. }
  12767. /**
  12768. * An optional callback that is executed immediately before the material is used to render a 3D object.
  12769. *
  12770. * This method can only be used when rendering with {@link WebGLRenderer}.
  12771. *
  12772. * @param {WebGLRenderer} renderer - The renderer.
  12773. * @param {Scene} scene - The scene.
  12774. * @param {Camera} camera - The camera that is used to render the scene.
  12775. * @param {BufferGeometry} geometry - The 3D object's geometry.
  12776. * @param {Object3D} object - The 3D object.
  12777. * @param {Object} group - The geometry group data.
  12778. */
  12779. onBeforeRender( /* renderer, scene, camera, geometry, object, group */ ) {}
  12780. /**
  12781. * An optional callback that is executed immediately before the shader
  12782. * program is compiled. This function is called with the shader source code
  12783. * as a parameter. Useful for the modification of built-in materials.
  12784. *
  12785. * This method can only be used when rendering with {@link WebGLRenderer}. The
  12786. * recommended approach when customizing materials is to use `WebGPURenderer` with the new
  12787. * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language).
  12788. *
  12789. * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source.
  12790. * @param {WebGLRenderer} renderer - A reference to the renderer.
  12791. */
  12792. onBeforeCompile( /* shaderobject, renderer */ ) {}
  12793. /**
  12794. * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify
  12795. * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached
  12796. * shader or recompile the shader for this material as needed.
  12797. *
  12798. * This method can only be used when rendering with {@link WebGLRenderer}.
  12799. *
  12800. * @return {string} The custom program cache key.
  12801. */
  12802. customProgramCacheKey() {
  12803. return this.onBeforeCompile.toString();
  12804. }
  12805. /**
  12806. * This method can be used to set default values from parameter objects.
  12807. * It is a generic implementation so it can be used with different types
  12808. * of materials.
  12809. *
  12810. * @param {Object} [values] - The material values to set.
  12811. */
  12812. setValues( values ) {
  12813. if ( values === undefined ) return;
  12814. for ( const key in values ) {
  12815. const newValue = values[ key ];
  12816. if ( newValue === undefined ) {
  12817. warn( `Material: parameter '${ key }' has value of undefined.` );
  12818. continue;
  12819. }
  12820. const currentValue = this[ key ];
  12821. if ( currentValue === undefined ) {
  12822. warn( `Material: '${ key }' is not a property of THREE.${ this.type }.` );
  12823. continue;
  12824. }
  12825. if ( currentValue && currentValue.isColor ) {
  12826. currentValue.set( newValue );
  12827. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  12828. currentValue.copy( newValue );
  12829. } else {
  12830. this[ key ] = newValue;
  12831. }
  12832. }
  12833. }
  12834. /**
  12835. * Serializes the material into JSON.
  12836. *
  12837. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  12838. * @return {Object} A JSON object representing the serialized material.
  12839. * @see {@link ObjectLoader#parse}
  12840. */
  12841. toJSON( meta ) {
  12842. const isRootObject = ( meta === undefined || typeof meta === 'string' );
  12843. if ( isRootObject ) {
  12844. meta = {
  12845. textures: {},
  12846. images: {}
  12847. };
  12848. }
  12849. const data = {
  12850. metadata: {
  12851. version: 4.7,
  12852. type: 'Material',
  12853. generator: 'Material.toJSON'
  12854. }
  12855. };
  12856. // standard Material serialization
  12857. data.uuid = this.uuid;
  12858. data.type = this.type;
  12859. if ( this.name !== '' ) data.name = this.name;
  12860. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  12861. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  12862. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  12863. if ( this.sheen !== undefined ) data.sheen = this.sheen;
  12864. if ( this.sheenColor && this.sheenColor.isColor ) data.sheenColor = this.sheenColor.getHex();
  12865. if ( this.sheenRoughness !== undefined ) data.sheenRoughness = this.sheenRoughness;
  12866. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  12867. if ( this.emissiveIntensity !== undefined && this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  12868. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  12869. if ( this.specularIntensity !== undefined ) data.specularIntensity = this.specularIntensity;
  12870. if ( this.specularColor && this.specularColor.isColor ) data.specularColor = this.specularColor.getHex();
  12871. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  12872. if ( this.clearcoat !== undefined ) data.clearcoat = this.clearcoat;
  12873. if ( this.clearcoatRoughness !== undefined ) data.clearcoatRoughness = this.clearcoatRoughness;
  12874. if ( this.clearcoatMap && this.clearcoatMap.isTexture ) {
  12875. data.clearcoatMap = this.clearcoatMap.toJSON( meta ).uuid;
  12876. }
  12877. if ( this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture ) {
  12878. data.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON( meta ).uuid;
  12879. }
  12880. if ( this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture ) {
  12881. data.clearcoatNormalMap = this.clearcoatNormalMap.toJSON( meta ).uuid;
  12882. data.clearcoatNormalScale = this.clearcoatNormalScale.toArray();
  12883. }
  12884. if ( this.sheenColorMap && this.sheenColorMap.isTexture ) {
  12885. data.sheenColorMap = this.sheenColorMap.toJSON( meta ).uuid;
  12886. }
  12887. if ( this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture ) {
  12888. data.sheenRoughnessMap = this.sheenRoughnessMap.toJSON( meta ).uuid;
  12889. }
  12890. if ( this.dispersion !== undefined ) data.dispersion = this.dispersion;
  12891. if ( this.iridescence !== undefined ) data.iridescence = this.iridescence;
  12892. if ( this.iridescenceIOR !== undefined ) data.iridescenceIOR = this.iridescenceIOR;
  12893. if ( this.iridescenceThicknessRange !== undefined ) data.iridescenceThicknessRange = this.iridescenceThicknessRange;
  12894. if ( this.iridescenceMap && this.iridescenceMap.isTexture ) {
  12895. data.iridescenceMap = this.iridescenceMap.toJSON( meta ).uuid;
  12896. }
  12897. if ( this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture ) {
  12898. data.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON( meta ).uuid;
  12899. }
  12900. if ( this.anisotropy !== undefined ) data.anisotropy = this.anisotropy;
  12901. if ( this.anisotropyRotation !== undefined ) data.anisotropyRotation = this.anisotropyRotation;
  12902. if ( this.anisotropyMap && this.anisotropyMap.isTexture ) {
  12903. data.anisotropyMap = this.anisotropyMap.toJSON( meta ).uuid;
  12904. }
  12905. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  12906. if ( this.matcap && this.matcap.isTexture ) data.matcap = this.matcap.toJSON( meta ).uuid;
  12907. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  12908. if ( this.lightMap && this.lightMap.isTexture ) {
  12909. data.lightMap = this.lightMap.toJSON( meta ).uuid;
  12910. data.lightMapIntensity = this.lightMapIntensity;
  12911. }
  12912. if ( this.aoMap && this.aoMap.isTexture ) {
  12913. data.aoMap = this.aoMap.toJSON( meta ).uuid;
  12914. data.aoMapIntensity = this.aoMapIntensity;
  12915. }
  12916. if ( this.bumpMap && this.bumpMap.isTexture ) {
  12917. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  12918. data.bumpScale = this.bumpScale;
  12919. }
  12920. if ( this.normalMap && this.normalMap.isTexture ) {
  12921. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  12922. data.normalMapType = this.normalMapType;
  12923. data.normalScale = this.normalScale.toArray();
  12924. }
  12925. if ( this.displacementMap && this.displacementMap.isTexture ) {
  12926. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  12927. data.displacementScale = this.displacementScale;
  12928. data.displacementBias = this.displacementBias;
  12929. }
  12930. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  12931. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  12932. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  12933. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  12934. if ( this.specularIntensityMap && this.specularIntensityMap.isTexture ) data.specularIntensityMap = this.specularIntensityMap.toJSON( meta ).uuid;
  12935. if ( this.specularColorMap && this.specularColorMap.isTexture ) data.specularColorMap = this.specularColorMap.toJSON( meta ).uuid;
  12936. if ( this.envMap && this.envMap.isTexture ) {
  12937. data.envMap = this.envMap.toJSON( meta ).uuid;
  12938. if ( this.combine !== undefined ) data.combine = this.combine;
  12939. }
  12940. if ( this.envMapRotation !== undefined ) data.envMapRotation = this.envMapRotation.toArray();
  12941. if ( this.envMapIntensity !== undefined ) data.envMapIntensity = this.envMapIntensity;
  12942. if ( this.reflectivity !== undefined ) data.reflectivity = this.reflectivity;
  12943. if ( this.refractionRatio !== undefined ) data.refractionRatio = this.refractionRatio;
  12944. if ( this.gradientMap && this.gradientMap.isTexture ) {
  12945. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  12946. }
  12947. if ( this.transmission !== undefined ) data.transmission = this.transmission;
  12948. if ( this.transmissionMap && this.transmissionMap.isTexture ) data.transmissionMap = this.transmissionMap.toJSON( meta ).uuid;
  12949. if ( this.thickness !== undefined ) data.thickness = this.thickness;
  12950. if ( this.thicknessMap && this.thicknessMap.isTexture ) data.thicknessMap = this.thicknessMap.toJSON( meta ).uuid;
  12951. if ( this.attenuationDistance !== undefined && this.attenuationDistance !== Infinity ) data.attenuationDistance = this.attenuationDistance;
  12952. if ( this.attenuationColor !== undefined ) data.attenuationColor = this.attenuationColor.getHex();
  12953. if ( this.size !== undefined ) data.size = this.size;
  12954. if ( this.shadowSide !== null ) data.shadowSide = this.shadowSide;
  12955. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  12956. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  12957. if ( this.side !== FrontSide ) data.side = this.side;
  12958. if ( this.vertexColors === true ) data.vertexColors = true;
  12959. if ( this.opacity < 1 ) data.opacity = this.opacity;
  12960. if ( this.transparent === true ) data.transparent = true;
  12961. if ( this.blendSrc !== SrcAlphaFactor ) data.blendSrc = this.blendSrc;
  12962. if ( this.blendDst !== OneMinusSrcAlphaFactor ) data.blendDst = this.blendDst;
  12963. if ( this.blendEquation !== AddEquation ) data.blendEquation = this.blendEquation;
  12964. if ( this.blendSrcAlpha !== null ) data.blendSrcAlpha = this.blendSrcAlpha;
  12965. if ( this.blendDstAlpha !== null ) data.blendDstAlpha = this.blendDstAlpha;
  12966. if ( this.blendEquationAlpha !== null ) data.blendEquationAlpha = this.blendEquationAlpha;
  12967. if ( this.blendColor && this.blendColor.isColor ) data.blendColor = this.blendColor.getHex();
  12968. if ( this.blendAlpha !== 0 ) data.blendAlpha = this.blendAlpha;
  12969. if ( this.depthFunc !== LessEqualDepth ) data.depthFunc = this.depthFunc;
  12970. if ( this.depthTest === false ) data.depthTest = this.depthTest;
  12971. if ( this.depthWrite === false ) data.depthWrite = this.depthWrite;
  12972. if ( this.colorWrite === false ) data.colorWrite = this.colorWrite;
  12973. if ( this.stencilWriteMask !== 0xff ) data.stencilWriteMask = this.stencilWriteMask;
  12974. if ( this.stencilFunc !== AlwaysStencilFunc ) data.stencilFunc = this.stencilFunc;
  12975. if ( this.stencilRef !== 0 ) data.stencilRef = this.stencilRef;
  12976. if ( this.stencilFuncMask !== 0xff ) data.stencilFuncMask = this.stencilFuncMask;
  12977. if ( this.stencilFail !== KeepStencilOp ) data.stencilFail = this.stencilFail;
  12978. if ( this.stencilZFail !== KeepStencilOp ) data.stencilZFail = this.stencilZFail;
  12979. if ( this.stencilZPass !== KeepStencilOp ) data.stencilZPass = this.stencilZPass;
  12980. if ( this.stencilWrite === true ) data.stencilWrite = this.stencilWrite;
  12981. // rotation (SpriteMaterial)
  12982. if ( this.rotation !== undefined && this.rotation !== 0 ) data.rotation = this.rotation;
  12983. if ( this.polygonOffset === true ) data.polygonOffset = true;
  12984. if ( this.polygonOffsetFactor !== 0 ) data.polygonOffsetFactor = this.polygonOffsetFactor;
  12985. if ( this.polygonOffsetUnits !== 0 ) data.polygonOffsetUnits = this.polygonOffsetUnits;
  12986. if ( this.linewidth !== undefined && this.linewidth !== 1 ) data.linewidth = this.linewidth;
  12987. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  12988. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  12989. if ( this.scale !== undefined ) data.scale = this.scale;
  12990. if ( this.dithering === true ) data.dithering = true;
  12991. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  12992. if ( this.alphaHash === true ) data.alphaHash = true;
  12993. if ( this.alphaToCoverage === true ) data.alphaToCoverage = true;
  12994. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = true;
  12995. if ( this.forceSinglePass === true ) data.forceSinglePass = true;
  12996. if ( this.allowOverride === false ) data.allowOverride = false;
  12997. if ( this.wireframe === true ) data.wireframe = true;
  12998. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  12999. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  13000. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  13001. if ( this.flatShading === true ) data.flatShading = true;
  13002. if ( this.visible === false ) data.visible = false;
  13003. if ( this.toneMapped === false ) data.toneMapped = false;
  13004. if ( this.fog === false ) data.fog = false;
  13005. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  13006. // TODO: Copied from Object3D.toJSON
  13007. function extractFromCache( cache ) {
  13008. const values = [];
  13009. for ( const key in cache ) {
  13010. const data = cache[ key ];
  13011. delete data.metadata;
  13012. values.push( data );
  13013. }
  13014. return values;
  13015. }
  13016. if ( isRootObject ) {
  13017. const textures = extractFromCache( meta.textures );
  13018. const images = extractFromCache( meta.images );
  13019. if ( textures.length > 0 ) data.textures = textures;
  13020. if ( images.length > 0 ) data.images = images;
  13021. }
  13022. return data;
  13023. }
  13024. /**
  13025. * Returns a new material with copied values from this instance.
  13026. *
  13027. * @return {Material} A clone of this instance.
  13028. */
  13029. clone() {
  13030. return new this.constructor().copy( this );
  13031. }
  13032. /**
  13033. * Copies the values of the given material to this instance.
  13034. *
  13035. * @param {Material} source - The material to copy.
  13036. * @return {Material} A reference to this instance.
  13037. */
  13038. copy( source ) {
  13039. this.name = source.name;
  13040. this.blending = source.blending;
  13041. this.side = source.side;
  13042. this.vertexColors = source.vertexColors;
  13043. this.opacity = source.opacity;
  13044. this.transparent = source.transparent;
  13045. this.blendSrc = source.blendSrc;
  13046. this.blendDst = source.blendDst;
  13047. this.blendEquation = source.blendEquation;
  13048. this.blendSrcAlpha = source.blendSrcAlpha;
  13049. this.blendDstAlpha = source.blendDstAlpha;
  13050. this.blendEquationAlpha = source.blendEquationAlpha;
  13051. this.blendColor.copy( source.blendColor );
  13052. this.blendAlpha = source.blendAlpha;
  13053. this.depthFunc = source.depthFunc;
  13054. this.depthTest = source.depthTest;
  13055. this.depthWrite = source.depthWrite;
  13056. this.stencilWriteMask = source.stencilWriteMask;
  13057. this.stencilFunc = source.stencilFunc;
  13058. this.stencilRef = source.stencilRef;
  13059. this.stencilFuncMask = source.stencilFuncMask;
  13060. this.stencilFail = source.stencilFail;
  13061. this.stencilZFail = source.stencilZFail;
  13062. this.stencilZPass = source.stencilZPass;
  13063. this.stencilWrite = source.stencilWrite;
  13064. const srcPlanes = source.clippingPlanes;
  13065. let dstPlanes = null;
  13066. if ( srcPlanes !== null ) {
  13067. const n = srcPlanes.length;
  13068. dstPlanes = new Array( n );
  13069. for ( let i = 0; i !== n; ++ i ) {
  13070. dstPlanes[ i ] = srcPlanes[ i ].clone();
  13071. }
  13072. }
  13073. this.clippingPlanes = dstPlanes;
  13074. this.clipIntersection = source.clipIntersection;
  13075. this.clipShadows = source.clipShadows;
  13076. this.shadowSide = source.shadowSide;
  13077. this.colorWrite = source.colorWrite;
  13078. this.precision = source.precision;
  13079. this.polygonOffset = source.polygonOffset;
  13080. this.polygonOffsetFactor = source.polygonOffsetFactor;
  13081. this.polygonOffsetUnits = source.polygonOffsetUnits;
  13082. this.dithering = source.dithering;
  13083. this.alphaTest = source.alphaTest;
  13084. this.alphaHash = source.alphaHash;
  13085. this.alphaToCoverage = source.alphaToCoverage;
  13086. this.premultipliedAlpha = source.premultipliedAlpha;
  13087. this.forceSinglePass = source.forceSinglePass;
  13088. this.allowOverride = source.allowOverride;
  13089. this.visible = source.visible;
  13090. this.toneMapped = source.toneMapped;
  13091. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  13092. return this;
  13093. }
  13094. /**
  13095. * Frees the GPU-related resources allocated by this instance. Call this
  13096. * method whenever this instance is no longer used in your app.
  13097. *
  13098. * @fires Material#dispose
  13099. */
  13100. dispose() {
  13101. /**
  13102. * Fires when the material has been disposed of.
  13103. *
  13104. * @event Material#dispose
  13105. * @type {Object}
  13106. */
  13107. this.dispatchEvent( { type: 'dispose' } );
  13108. }
  13109. /**
  13110. * Setting this property to `true` indicates the engine the material
  13111. * needs to be recompiled.
  13112. *
  13113. * @type {boolean}
  13114. * @default false
  13115. * @param {boolean} value
  13116. */
  13117. set needsUpdate( value ) {
  13118. if ( value === true ) this.version ++;
  13119. }
  13120. }
  13121. /**
  13122. * A material for drawing geometries in a simple shaded (flat or wireframe) way.
  13123. *
  13124. * This material is not affected by lights.
  13125. *
  13126. * @augments Material
  13127. * @demo scenes/material-browser.html#MeshBasicMaterial
  13128. */
  13129. class MeshBasicMaterial extends Material {
  13130. /**
  13131. * Constructs a new mesh basic material.
  13132. *
  13133. * @param {Object} [parameters] - An object with one or more properties
  13134. * defining the material's appearance. Any property of the material
  13135. * (including any property from inherited materials) can be passed
  13136. * in here. Color values can be passed any type of value accepted
  13137. * by {@link Color#set}.
  13138. */
  13139. constructor( parameters ) {
  13140. super();
  13141. /**
  13142. * This flag can be used for type testing.
  13143. *
  13144. * @type {boolean}
  13145. * @readonly
  13146. * @default true
  13147. */
  13148. this.isMeshBasicMaterial = true;
  13149. this.type = 'MeshBasicMaterial';
  13150. /**
  13151. * Color of the material.
  13152. *
  13153. * @type {Color}
  13154. * @default (1,1,1)
  13155. */
  13156. this.color = new Color( 0xffffff ); // diffuse
  13157. /**
  13158. * The color map. May optionally include an alpha channel, typically combined
  13159. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  13160. * color is modulated by the diffuse `color`.
  13161. *
  13162. * @type {?Texture}
  13163. * @default null
  13164. */
  13165. this.map = null;
  13166. /**
  13167. * The light map. Requires a second set of UVs.
  13168. *
  13169. * @type {?Texture}
  13170. * @default null
  13171. */
  13172. this.lightMap = null;
  13173. /**
  13174. * Intensity of the baked light.
  13175. *
  13176. * @type {number}
  13177. * @default 1
  13178. */
  13179. this.lightMapIntensity = 1.0;
  13180. /**
  13181. * The red channel of this texture is used as the ambient occlusion map.
  13182. * Requires a second set of UVs.
  13183. *
  13184. * @type {?Texture}
  13185. * @default null
  13186. */
  13187. this.aoMap = null;
  13188. /**
  13189. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  13190. * disables ambient occlusion. Where intensity is `1` and the AO map's
  13191. * red channel is also `1`, ambient light is fully occluded on a surface.
  13192. *
  13193. * @type {number}
  13194. * @default 1
  13195. */
  13196. this.aoMapIntensity = 1.0;
  13197. /**
  13198. * Specular map used by the material.
  13199. *
  13200. * @type {?Texture}
  13201. * @default null
  13202. */
  13203. this.specularMap = null;
  13204. /**
  13205. * The alpha map is a grayscale texture that controls the opacity across the
  13206. * surface (black: fully transparent; white: fully opaque).
  13207. *
  13208. * Only the color of the texture is used, ignoring the alpha channel if one
  13209. * exists. For RGB and RGBA textures, the renderer will use the green channel
  13210. * when sampling this texture due to the extra bit of precision provided for
  13211. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  13212. * luminance/alpha textures will also still work as expected.
  13213. *
  13214. * @type {?Texture}
  13215. * @default null
  13216. */
  13217. this.alphaMap = null;
  13218. /**
  13219. * The environment map.
  13220. *
  13221. * @type {?Texture}
  13222. * @default null
  13223. */
  13224. this.envMap = null;
  13225. /**
  13226. * The rotation of the environment map in radians.
  13227. *
  13228. * @type {Euler}
  13229. * @default (0,0,0)
  13230. */
  13231. this.envMapRotation = new Euler();
  13232. /**
  13233. * How to combine the result of the surface's color with the environment map, if any.
  13234. *
  13235. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  13236. * blend between the two colors.
  13237. *
  13238. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  13239. * @default MultiplyOperation
  13240. */
  13241. this.combine = MultiplyOperation;
  13242. /**
  13243. * How much the environment map affects the surface.
  13244. * The valid range is between `0` (no reflections) and `1` (full reflections).
  13245. *
  13246. * @type {number}
  13247. * @default 1
  13248. */
  13249. this.reflectivity = 1;
  13250. /**
  13251. * The index of refraction (IOR) of air (approximately 1) divided by the
  13252. * index of refraction of the material. It is used with environment mapping
  13253. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  13254. * The refraction ratio should not exceed `1`.
  13255. *
  13256. * @type {number}
  13257. * @default 0.98
  13258. */
  13259. this.refractionRatio = 0.98;
  13260. /**
  13261. * Renders the geometry as a wireframe.
  13262. *
  13263. * @type {boolean}
  13264. * @default false
  13265. */
  13266. this.wireframe = false;
  13267. /**
  13268. * Controls the thickness of the wireframe.
  13269. *
  13270. * Can only be used with {@link SVGRenderer}.
  13271. *
  13272. * @type {number}
  13273. * @default 1
  13274. */
  13275. this.wireframeLinewidth = 1;
  13276. /**
  13277. * Defines appearance of wireframe ends.
  13278. *
  13279. * Can only be used with {@link SVGRenderer}.
  13280. *
  13281. * @type {('round'|'bevel'|'miter')}
  13282. * @default 'round'
  13283. */
  13284. this.wireframeLinecap = 'round';
  13285. /**
  13286. * Defines appearance of wireframe joints.
  13287. *
  13288. * Can only be used with {@link SVGRenderer}.
  13289. *
  13290. * @type {('round'|'bevel'|'miter')}
  13291. * @default 'round'
  13292. */
  13293. this.wireframeLinejoin = 'round';
  13294. /**
  13295. * Whether the material is affected by fog or not.
  13296. *
  13297. * @type {boolean}
  13298. * @default true
  13299. */
  13300. this.fog = true;
  13301. this.setValues( parameters );
  13302. }
  13303. copy( source ) {
  13304. super.copy( source );
  13305. this.color.copy( source.color );
  13306. this.map = source.map;
  13307. this.lightMap = source.lightMap;
  13308. this.lightMapIntensity = source.lightMapIntensity;
  13309. this.aoMap = source.aoMap;
  13310. this.aoMapIntensity = source.aoMapIntensity;
  13311. this.specularMap = source.specularMap;
  13312. this.alphaMap = source.alphaMap;
  13313. this.envMap = source.envMap;
  13314. this.envMapRotation.copy( source.envMapRotation );
  13315. this.combine = source.combine;
  13316. this.reflectivity = source.reflectivity;
  13317. this.refractionRatio = source.refractionRatio;
  13318. this.wireframe = source.wireframe;
  13319. this.wireframeLinewidth = source.wireframeLinewidth;
  13320. this.wireframeLinecap = source.wireframeLinecap;
  13321. this.wireframeLinejoin = source.wireframeLinejoin;
  13322. this.fog = source.fog;
  13323. return this;
  13324. }
  13325. }
  13326. // Fast Half Float Conversions, http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf
  13327. const _tables = /*@__PURE__*/ _generateTables();
  13328. function _generateTables() {
  13329. // float32 to float16 helpers
  13330. const buffer = new ArrayBuffer( 4 );
  13331. const floatView = new Float32Array( buffer );
  13332. const uint32View = new Uint32Array( buffer );
  13333. const baseTable = new Uint32Array( 512 );
  13334. const shiftTable = new Uint32Array( 512 );
  13335. for ( let i = 0; i < 256; ++ i ) {
  13336. const e = i - 127;
  13337. // very small number (0, -0)
  13338. if ( e < -27 ) {
  13339. baseTable[ i ] = 0x0000;
  13340. baseTable[ i | 0x100 ] = 0x8000;
  13341. shiftTable[ i ] = 24;
  13342. shiftTable[ i | 0x100 ] = 24;
  13343. // small number (denorm)
  13344. } else if ( e < -14 ) {
  13345. baseTable[ i ] = 0x0400 >> ( - e - 14 );
  13346. baseTable[ i | 0x100 ] = ( 0x0400 >> ( - e - 14 ) ) | 0x8000;
  13347. shiftTable[ i ] = - e - 1;
  13348. shiftTable[ i | 0x100 ] = - e - 1;
  13349. // normal number
  13350. } else if ( e <= 15 ) {
  13351. baseTable[ i ] = ( e + 15 ) << 10;
  13352. baseTable[ i | 0x100 ] = ( ( e + 15 ) << 10 ) | 0x8000;
  13353. shiftTable[ i ] = 13;
  13354. shiftTable[ i | 0x100 ] = 13;
  13355. // large number (Infinity, -Infinity)
  13356. } else if ( e < 128 ) {
  13357. baseTable[ i ] = 0x7c00;
  13358. baseTable[ i | 0x100 ] = 0xfc00;
  13359. shiftTable[ i ] = 24;
  13360. shiftTable[ i | 0x100 ] = 24;
  13361. // stay (NaN, Infinity, -Infinity)
  13362. } else {
  13363. baseTable[ i ] = 0x7c00;
  13364. baseTable[ i | 0x100 ] = 0xfc00;
  13365. shiftTable[ i ] = 13;
  13366. shiftTable[ i | 0x100 ] = 13;
  13367. }
  13368. }
  13369. // float16 to float32 helpers
  13370. const mantissaTable = new Uint32Array( 2048 );
  13371. const exponentTable = new Uint32Array( 64 );
  13372. const offsetTable = new Uint32Array( 64 );
  13373. for ( let i = 1; i < 1024; ++ i ) {
  13374. let m = i << 13; // zero pad mantissa bits
  13375. let e = 0; // zero exponent
  13376. // normalized
  13377. while ( ( m & 0x00800000 ) === 0 ) {
  13378. m <<= 1;
  13379. e -= 0x00800000; // decrement exponent
  13380. }
  13381. m &= -8388609; // clear leading 1 bit
  13382. e += 0x38800000; // adjust bias
  13383. mantissaTable[ i ] = m | e;
  13384. }
  13385. for ( let i = 1024; i < 2048; ++ i ) {
  13386. mantissaTable[ i ] = 0x38000000 + ( ( i - 1024 ) << 13 );
  13387. }
  13388. for ( let i = 1; i < 31; ++ i ) {
  13389. exponentTable[ i ] = i << 23;
  13390. }
  13391. exponentTable[ 31 ] = 0x47800000;
  13392. exponentTable[ 32 ] = 0x80000000;
  13393. for ( let i = 33; i < 63; ++ i ) {
  13394. exponentTable[ i ] = 0x80000000 + ( ( i - 32 ) << 23 );
  13395. }
  13396. exponentTable[ 63 ] = 0xc7800000;
  13397. for ( let i = 1; i < 64; ++ i ) {
  13398. if ( i !== 32 ) {
  13399. offsetTable[ i ] = 1024;
  13400. }
  13401. }
  13402. return {
  13403. floatView: floatView,
  13404. uint32View: uint32View,
  13405. baseTable: baseTable,
  13406. shiftTable: shiftTable,
  13407. mantissaTable: mantissaTable,
  13408. exponentTable: exponentTable,
  13409. offsetTable: offsetTable
  13410. };
  13411. }
  13412. /**
  13413. * Returns a half precision floating point value (FP16) from the given single
  13414. * precision floating point value (FP32).
  13415. *
  13416. * @param {number} val - A single precision floating point value.
  13417. * @return {number} The FP16 value.
  13418. */
  13419. function toHalfFloat( val ) {
  13420. if ( Math.abs( val ) > 65504 ) warn( 'DataUtils.toHalfFloat(): Value out of range.' );
  13421. val = clamp( val, -65504, 65504 );
  13422. _tables.floatView[ 0 ] = val;
  13423. const f = _tables.uint32View[ 0 ];
  13424. const e = ( f >> 23 ) & 0x1ff;
  13425. return _tables.baseTable[ e ] + ( ( f & 0x007fffff ) >> _tables.shiftTable[ e ] );
  13426. }
  13427. /**
  13428. * Returns a single precision floating point value (FP32) from the given half
  13429. * precision floating point value (FP16).
  13430. *
  13431. * @param {number} val - A half precision floating point value.
  13432. * @return {number} The FP32 value.
  13433. */
  13434. function fromHalfFloat( val ) {
  13435. const m = val >> 10;
  13436. _tables.uint32View[ 0 ] = _tables.mantissaTable[ _tables.offsetTable[ m ] + ( val & 0x3ff ) ] + _tables.exponentTable[ m ];
  13437. return _tables.floatView[ 0 ];
  13438. }
  13439. /**
  13440. * A class containing utility functions for data.
  13441. *
  13442. * @hideconstructor
  13443. */
  13444. class DataUtils {
  13445. /**
  13446. * Returns a half precision floating point value (FP16) from the given single
  13447. * precision floating point value (FP32).
  13448. *
  13449. * @param {number} val - A single precision floating point value.
  13450. * @return {number} The FP16 value.
  13451. */
  13452. static toHalfFloat( val ) {
  13453. return toHalfFloat( val );
  13454. }
  13455. /**
  13456. * Returns a single precision floating point value (FP32) from the given half
  13457. * precision floating point value (FP16).
  13458. *
  13459. * @param {number} val - A half precision floating point value.
  13460. * @return {number} The FP32 value.
  13461. */
  13462. static fromHalfFloat( val ) {
  13463. return fromHalfFloat( val );
  13464. }
  13465. }
  13466. const _vector$9 = /*@__PURE__*/ new Vector3();
  13467. const _vector2$1 = /*@__PURE__*/ new Vector2();
  13468. let _id$3 = 0;
  13469. /**
  13470. * This class stores data for an attribute (such as vertex positions, face
  13471. * indices, normals, colors, UVs, and any custom attributes ) associated with
  13472. * a geometry, which allows for more efficient passing of data to the GPU.
  13473. *
  13474. * When working with vector-like data, the `fromBufferAttribute( attribute, index )`
  13475. * helper methods on vector and color class might be helpful. E.g. {@link Vector3#fromBufferAttribute}.
  13476. */
  13477. class BufferAttribute {
  13478. /**
  13479. * Constructs a new buffer attribute.
  13480. *
  13481. * @param {TypedArray} array - The array holding the attribute data.
  13482. * @param {number} itemSize - The item size.
  13483. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13484. */
  13485. constructor( array, itemSize, normalized = false ) {
  13486. if ( Array.isArray( array ) ) {
  13487. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  13488. }
  13489. /**
  13490. * This flag can be used for type testing.
  13491. *
  13492. * @type {boolean}
  13493. * @readonly
  13494. * @default true
  13495. */
  13496. this.isBufferAttribute = true;
  13497. /**
  13498. * The ID of the buffer attribute.
  13499. *
  13500. * @name BufferAttribute#id
  13501. * @type {number}
  13502. * @readonly
  13503. */
  13504. Object.defineProperty( this, 'id', { value: _id$3 ++ } );
  13505. /**
  13506. * The name of the buffer attribute.
  13507. *
  13508. * @type {string}
  13509. */
  13510. this.name = '';
  13511. /**
  13512. * The array holding the attribute data. It should have `itemSize * numVertices`
  13513. * elements, where `numVertices` is the number of vertices in the associated geometry.
  13514. *
  13515. * @type {TypedArray}
  13516. */
  13517. this.array = array;
  13518. /**
  13519. * The number of values of the array that should be associated with a particular vertex.
  13520. * For instance, if this attribute is storing a 3-component vector (such as a position,
  13521. * normal, or color), then the value should be `3`.
  13522. *
  13523. * @type {number}
  13524. */
  13525. this.itemSize = itemSize;
  13526. /**
  13527. * Represents the number of items this buffer attribute stores. It is internally computed
  13528. * by dividing the `array` length by the `itemSize`.
  13529. *
  13530. * @type {number}
  13531. * @readonly
  13532. */
  13533. this.count = array !== undefined ? array.length / itemSize : 0;
  13534. /**
  13535. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  13536. * the values in the GLSL code. For instance, if `array` is an instance of `UInt16Array`,
  13537. * and `normalized` is `true`, the values `0 - +65535` in the array data will be mapped to
  13538. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  13539. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  13540. *
  13541. * @type {boolean}
  13542. */
  13543. this.normalized = normalized;
  13544. /**
  13545. * Defines the intended usage pattern of the data store for optimization purposes.
  13546. *
  13547. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  13548. * instantiate a new one and set the desired usage before the next render.
  13549. *
  13550. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  13551. * @default StaticDrawUsage
  13552. */
  13553. this.usage = StaticDrawUsage;
  13554. /**
  13555. * This can be used to only update some components of stored vectors (for example, just the
  13556. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  13557. *
  13558. * @type {Array<Object>}
  13559. */
  13560. this.updateRanges = [];
  13561. /**
  13562. * Configures the bound GPU type for use in shaders.
  13563. *
  13564. * Note: this only has an effect for integer arrays and is not configurable for float arrays.
  13565. * For lower precision float types, use `Float16BufferAttribute`.
  13566. *
  13567. * @type {(FloatType|IntType)}
  13568. * @default FloatType
  13569. */
  13570. this.gpuType = FloatType;
  13571. /**
  13572. * A version number, incremented every time the `needsUpdate` is set to `true`.
  13573. *
  13574. * @type {number}
  13575. */
  13576. this.version = 0;
  13577. }
  13578. /**
  13579. * A callback function that is executed after the renderer has transferred the attribute
  13580. * array data to the GPU.
  13581. */
  13582. onUploadCallback() {}
  13583. /**
  13584. * Flag to indicate that this attribute has changed and should be re-sent to
  13585. * the GPU. Set this to `true` when you modify the value of the array.
  13586. *
  13587. * @type {number}
  13588. * @default false
  13589. * @param {boolean} value
  13590. */
  13591. set needsUpdate( value ) {
  13592. if ( value === true ) this.version ++;
  13593. }
  13594. /**
  13595. * Sets the usage of this buffer attribute.
  13596. *
  13597. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  13598. * @return {BufferAttribute} A reference to this buffer attribute.
  13599. */
  13600. setUsage( value ) {
  13601. this.usage = value;
  13602. return this;
  13603. }
  13604. /**
  13605. * Adds a range of data in the data array to be updated on the GPU.
  13606. *
  13607. * @param {number} start - Position at which to start update.
  13608. * @param {number} count - The number of components to update.
  13609. */
  13610. addUpdateRange( start, count ) {
  13611. this.updateRanges.push( { start, count } );
  13612. }
  13613. /**
  13614. * Clears the update ranges.
  13615. */
  13616. clearUpdateRanges() {
  13617. this.updateRanges.length = 0;
  13618. }
  13619. /**
  13620. * Copies the values of the given buffer attribute to this instance.
  13621. *
  13622. * @param {BufferAttribute} source - The buffer attribute to copy.
  13623. * @return {BufferAttribute} A reference to this instance.
  13624. */
  13625. copy( source ) {
  13626. this.name = source.name;
  13627. this.array = new source.array.constructor( source.array );
  13628. this.itemSize = source.itemSize;
  13629. this.count = source.count;
  13630. this.normalized = source.normalized;
  13631. this.usage = source.usage;
  13632. this.gpuType = source.gpuType;
  13633. return this;
  13634. }
  13635. /**
  13636. * Copies a vector from the given buffer attribute to this one. The start
  13637. * and destination position in the attribute buffers are represented by the
  13638. * given indices.
  13639. *
  13640. * @param {number} index1 - The destination index into this buffer attribute.
  13641. * @param {BufferAttribute} attribute - The buffer attribute to copy from.
  13642. * @param {number} index2 - The source index into the given buffer attribute.
  13643. * @return {BufferAttribute} A reference to this instance.
  13644. */
  13645. copyAt( index1, attribute, index2 ) {
  13646. index1 *= this.itemSize;
  13647. index2 *= attribute.itemSize;
  13648. for ( let i = 0, l = this.itemSize; i < l; i ++ ) {
  13649. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  13650. }
  13651. return this;
  13652. }
  13653. /**
  13654. * Copies the given array data into this buffer attribute.
  13655. *
  13656. * @param {(TypedArray|Array)} array - The array to copy.
  13657. * @return {BufferAttribute} A reference to this instance.
  13658. */
  13659. copyArray( array ) {
  13660. this.array.set( array );
  13661. return this;
  13662. }
  13663. /**
  13664. * Applies the given 3x3 matrix to the given attribute. Works with
  13665. * item size `2` and `3`.
  13666. *
  13667. * @param {Matrix3} m - The matrix to apply.
  13668. * @return {BufferAttribute} A reference to this instance.
  13669. */
  13670. applyMatrix3( m ) {
  13671. if ( this.itemSize === 2 ) {
  13672. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13673. _vector2$1.fromBufferAttribute( this, i );
  13674. _vector2$1.applyMatrix3( m );
  13675. this.setXY( i, _vector2$1.x, _vector2$1.y );
  13676. }
  13677. } else if ( this.itemSize === 3 ) {
  13678. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13679. _vector$9.fromBufferAttribute( this, i );
  13680. _vector$9.applyMatrix3( m );
  13681. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13682. }
  13683. }
  13684. return this;
  13685. }
  13686. /**
  13687. * Applies the given 4x4 matrix to the given attribute. Only works with
  13688. * item size `3`.
  13689. *
  13690. * @param {Matrix4} m - The matrix to apply.
  13691. * @return {BufferAttribute} A reference to this instance.
  13692. */
  13693. applyMatrix4( m ) {
  13694. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13695. _vector$9.fromBufferAttribute( this, i );
  13696. _vector$9.applyMatrix4( m );
  13697. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13698. }
  13699. return this;
  13700. }
  13701. /**
  13702. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  13703. * item size `3`.
  13704. *
  13705. * @param {Matrix3} m - The normal matrix to apply.
  13706. * @return {BufferAttribute} A reference to this instance.
  13707. */
  13708. applyNormalMatrix( m ) {
  13709. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13710. _vector$9.fromBufferAttribute( this, i );
  13711. _vector$9.applyNormalMatrix( m );
  13712. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13713. }
  13714. return this;
  13715. }
  13716. /**
  13717. * Applies the given 4x4 matrix to the given attribute. Only works with
  13718. * item size `3` and with direction vectors.
  13719. *
  13720. * @param {Matrix4} m - The matrix to apply.
  13721. * @return {BufferAttribute} A reference to this instance.
  13722. */
  13723. transformDirection( m ) {
  13724. for ( let i = 0, l = this.count; i < l; i ++ ) {
  13725. _vector$9.fromBufferAttribute( this, i );
  13726. _vector$9.transformDirection( m );
  13727. this.setXYZ( i, _vector$9.x, _vector$9.y, _vector$9.z );
  13728. }
  13729. return this;
  13730. }
  13731. /**
  13732. * Sets the given array data in the buffer attribute.
  13733. *
  13734. * @param {(TypedArray|Array)} value - The array data to set.
  13735. * @param {number} [offset=0] - The offset in this buffer attribute's array.
  13736. * @return {BufferAttribute} A reference to this instance.
  13737. */
  13738. set( value, offset = 0 ) {
  13739. // Matching BufferAttribute constructor, do not normalize the array.
  13740. this.array.set( value, offset );
  13741. return this;
  13742. }
  13743. /**
  13744. * Returns the given component of the vector at the given index.
  13745. *
  13746. * @param {number} index - The index into the buffer attribute.
  13747. * @param {number} component - The component index.
  13748. * @return {number} The returned value.
  13749. */
  13750. getComponent( index, component ) {
  13751. let value = this.array[ index * this.itemSize + component ];
  13752. if ( this.normalized ) value = denormalize( value, this.array );
  13753. return value;
  13754. }
  13755. /**
  13756. * Sets the given value to the given component of the vector at the given index.
  13757. *
  13758. * @param {number} index - The index into the buffer attribute.
  13759. * @param {number} component - The component index.
  13760. * @param {number} value - The value to set.
  13761. * @return {BufferAttribute} A reference to this instance.
  13762. */
  13763. setComponent( index, component, value ) {
  13764. if ( this.normalized ) value = normalize( value, this.array );
  13765. this.array[ index * this.itemSize + component ] = value;
  13766. return this;
  13767. }
  13768. /**
  13769. * Returns the x component of the vector at the given index.
  13770. *
  13771. * @param {number} index - The index into the buffer attribute.
  13772. * @return {number} The x component.
  13773. */
  13774. getX( index ) {
  13775. let x = this.array[ index * this.itemSize ];
  13776. if ( this.normalized ) x = denormalize( x, this.array );
  13777. return x;
  13778. }
  13779. /**
  13780. * Sets the x component of the vector at the given index.
  13781. *
  13782. * @param {number} index - The index into the buffer attribute.
  13783. * @param {number} x - The value to set.
  13784. * @return {BufferAttribute} A reference to this instance.
  13785. */
  13786. setX( index, x ) {
  13787. if ( this.normalized ) x = normalize( x, this.array );
  13788. this.array[ index * this.itemSize ] = x;
  13789. return this;
  13790. }
  13791. /**
  13792. * Returns the y component of the vector at the given index.
  13793. *
  13794. * @param {number} index - The index into the buffer attribute.
  13795. * @return {number} The y component.
  13796. */
  13797. getY( index ) {
  13798. let y = this.array[ index * this.itemSize + 1 ];
  13799. if ( this.normalized ) y = denormalize( y, this.array );
  13800. return y;
  13801. }
  13802. /**
  13803. * Sets the y component of the vector at the given index.
  13804. *
  13805. * @param {number} index - The index into the buffer attribute.
  13806. * @param {number} y - The value to set.
  13807. * @return {BufferAttribute} A reference to this instance.
  13808. */
  13809. setY( index, y ) {
  13810. if ( this.normalized ) y = normalize( y, this.array );
  13811. this.array[ index * this.itemSize + 1 ] = y;
  13812. return this;
  13813. }
  13814. /**
  13815. * Returns the z component of the vector at the given index.
  13816. *
  13817. * @param {number} index - The index into the buffer attribute.
  13818. * @return {number} The z component.
  13819. */
  13820. getZ( index ) {
  13821. let z = this.array[ index * this.itemSize + 2 ];
  13822. if ( this.normalized ) z = denormalize( z, this.array );
  13823. return z;
  13824. }
  13825. /**
  13826. * Sets the z component of the vector at the given index.
  13827. *
  13828. * @param {number} index - The index into the buffer attribute.
  13829. * @param {number} z - The value to set.
  13830. * @return {BufferAttribute} A reference to this instance.
  13831. */
  13832. setZ( index, z ) {
  13833. if ( this.normalized ) z = normalize( z, this.array );
  13834. this.array[ index * this.itemSize + 2 ] = z;
  13835. return this;
  13836. }
  13837. /**
  13838. * Returns the w component of the vector at the given index.
  13839. *
  13840. * @param {number} index - The index into the buffer attribute.
  13841. * @return {number} The w component.
  13842. */
  13843. getW( index ) {
  13844. let w = this.array[ index * this.itemSize + 3 ];
  13845. if ( this.normalized ) w = denormalize( w, this.array );
  13846. return w;
  13847. }
  13848. /**
  13849. * Sets the w component of the vector at the given index.
  13850. *
  13851. * @param {number} index - The index into the buffer attribute.
  13852. * @param {number} w - The value to set.
  13853. * @return {BufferAttribute} A reference to this instance.
  13854. */
  13855. setW( index, w ) {
  13856. if ( this.normalized ) w = normalize( w, this.array );
  13857. this.array[ index * this.itemSize + 3 ] = w;
  13858. return this;
  13859. }
  13860. /**
  13861. * Sets the x and y component of the vector at the given index.
  13862. *
  13863. * @param {number} index - The index into the buffer attribute.
  13864. * @param {number} x - The value for the x component to set.
  13865. * @param {number} y - The value for the y component to set.
  13866. * @return {BufferAttribute} A reference to this instance.
  13867. */
  13868. setXY( index, x, y ) {
  13869. index *= this.itemSize;
  13870. if ( this.normalized ) {
  13871. x = normalize( x, this.array );
  13872. y = normalize( y, this.array );
  13873. }
  13874. this.array[ index + 0 ] = x;
  13875. this.array[ index + 1 ] = y;
  13876. return this;
  13877. }
  13878. /**
  13879. * Sets the x, y and z component of the vector at the given index.
  13880. *
  13881. * @param {number} index - The index into the buffer attribute.
  13882. * @param {number} x - The value for the x component to set.
  13883. * @param {number} y - The value for the y component to set.
  13884. * @param {number} z - The value for the z component to set.
  13885. * @return {BufferAttribute} A reference to this instance.
  13886. */
  13887. setXYZ( index, x, y, z ) {
  13888. index *= this.itemSize;
  13889. if ( this.normalized ) {
  13890. x = normalize( x, this.array );
  13891. y = normalize( y, this.array );
  13892. z = normalize( z, this.array );
  13893. }
  13894. this.array[ index + 0 ] = x;
  13895. this.array[ index + 1 ] = y;
  13896. this.array[ index + 2 ] = z;
  13897. return this;
  13898. }
  13899. /**
  13900. * Sets the x, y, z and w component of the vector at the given index.
  13901. *
  13902. * @param {number} index - The index into the buffer attribute.
  13903. * @param {number} x - The value for the x component to set.
  13904. * @param {number} y - The value for the y component to set.
  13905. * @param {number} z - The value for the z component to set.
  13906. * @param {number} w - The value for the w component to set.
  13907. * @return {BufferAttribute} A reference to this instance.
  13908. */
  13909. setXYZW( index, x, y, z, w ) {
  13910. index *= this.itemSize;
  13911. if ( this.normalized ) {
  13912. x = normalize( x, this.array );
  13913. y = normalize( y, this.array );
  13914. z = normalize( z, this.array );
  13915. w = normalize( w, this.array );
  13916. }
  13917. this.array[ index + 0 ] = x;
  13918. this.array[ index + 1 ] = y;
  13919. this.array[ index + 2 ] = z;
  13920. this.array[ index + 3 ] = w;
  13921. return this;
  13922. }
  13923. /**
  13924. * Sets the given callback function that is executed after the Renderer has transferred
  13925. * the attribute array data to the GPU. Can be used to perform clean-up operations after
  13926. * the upload when attribute data are not needed anymore on the CPU side.
  13927. *
  13928. * @param {Function} callback - The `onUpload()` callback.
  13929. * @return {BufferAttribute} A reference to this instance.
  13930. */
  13931. onUpload( callback ) {
  13932. this.onUploadCallback = callback;
  13933. return this;
  13934. }
  13935. /**
  13936. * Returns a new buffer attribute with copied values from this instance.
  13937. *
  13938. * @return {BufferAttribute} A clone of this instance.
  13939. */
  13940. clone() {
  13941. return new this.constructor( this.array, this.itemSize ).copy( this );
  13942. }
  13943. /**
  13944. * Serializes the buffer attribute into JSON.
  13945. *
  13946. * @return {Object} A JSON object representing the serialized buffer attribute.
  13947. */
  13948. toJSON() {
  13949. const data = {
  13950. itemSize: this.itemSize,
  13951. type: this.array.constructor.name,
  13952. array: Array.from( this.array ),
  13953. normalized: this.normalized
  13954. };
  13955. if ( this.name !== '' ) data.name = this.name;
  13956. if ( this.usage !== StaticDrawUsage ) data.usage = this.usage;
  13957. return data;
  13958. }
  13959. }
  13960. /**
  13961. * Convenient class that can be used when creating a `Int8` buffer attribute with
  13962. * a plain `Array` instance.
  13963. *
  13964. * @augments BufferAttribute
  13965. */
  13966. class Int8BufferAttribute extends BufferAttribute {
  13967. /**
  13968. * Constructs a new buffer attribute.
  13969. *
  13970. * @param {(Array<number>|Int8Array)} array - The array holding the attribute data.
  13971. * @param {number} itemSize - The item size.
  13972. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13973. */
  13974. constructor( array, itemSize, normalized ) {
  13975. super( new Int8Array( array ), itemSize, normalized );
  13976. }
  13977. }
  13978. /**
  13979. * Convenient class that can be used when creating a `UInt8` buffer attribute with
  13980. * a plain `Array` instance.
  13981. *
  13982. * @augments BufferAttribute
  13983. */
  13984. class Uint8BufferAttribute extends BufferAttribute {
  13985. /**
  13986. * Constructs a new buffer attribute.
  13987. *
  13988. * @param {(Array<number>|Uint8Array)} array - The array holding the attribute data.
  13989. * @param {number} itemSize - The item size.
  13990. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  13991. */
  13992. constructor( array, itemSize, normalized ) {
  13993. super( new Uint8Array( array ), itemSize, normalized );
  13994. }
  13995. }
  13996. /**
  13997. * Convenient class that can be used when creating a `UInt8Clamped` buffer attribute with
  13998. * a plain `Array` instance.
  13999. *
  14000. * @augments BufferAttribute
  14001. */
  14002. class Uint8ClampedBufferAttribute extends BufferAttribute {
  14003. /**
  14004. * Constructs a new buffer attribute.
  14005. *
  14006. * @param {(Array<number>|Uint8ClampedArray)} array - The array holding the attribute data.
  14007. * @param {number} itemSize - The item size.
  14008. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14009. */
  14010. constructor( array, itemSize, normalized ) {
  14011. super( new Uint8ClampedArray( array ), itemSize, normalized );
  14012. }
  14013. }
  14014. /**
  14015. * Convenient class that can be used when creating a `Int16` buffer attribute with
  14016. * a plain `Array` instance.
  14017. *
  14018. * @augments BufferAttribute
  14019. */
  14020. class Int16BufferAttribute extends BufferAttribute {
  14021. /**
  14022. * Constructs a new buffer attribute.
  14023. *
  14024. * @param {(Array<number>|Int16Array)} array - The array holding the attribute data.
  14025. * @param {number} itemSize - The item size.
  14026. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14027. */
  14028. constructor( array, itemSize, normalized ) {
  14029. super( new Int16Array( array ), itemSize, normalized );
  14030. }
  14031. }
  14032. /**
  14033. * Convenient class that can be used when creating a `UInt16` buffer attribute with
  14034. * a plain `Array` instance.
  14035. *
  14036. * @augments BufferAttribute
  14037. */
  14038. class Uint16BufferAttribute extends BufferAttribute {
  14039. /**
  14040. * Constructs a new buffer attribute.
  14041. *
  14042. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14043. * @param {number} itemSize - The item size.
  14044. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14045. */
  14046. constructor( array, itemSize, normalized ) {
  14047. super( new Uint16Array( array ), itemSize, normalized );
  14048. }
  14049. }
  14050. /**
  14051. * Convenient class that can be used when creating a `Int32` buffer attribute with
  14052. * a plain `Array` instance.
  14053. *
  14054. * @augments BufferAttribute
  14055. */
  14056. class Int32BufferAttribute extends BufferAttribute {
  14057. /**
  14058. * Constructs a new buffer attribute.
  14059. *
  14060. * @param {(Array<number>|Int32Array)} array - The array holding the attribute data.
  14061. * @param {number} itemSize - The item size.
  14062. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14063. */
  14064. constructor( array, itemSize, normalized ) {
  14065. super( new Int32Array( array ), itemSize, normalized );
  14066. }
  14067. }
  14068. /**
  14069. * Convenient class that can be used when creating a `UInt32` buffer attribute with
  14070. * a plain `Array` instance.
  14071. *
  14072. * @augments BufferAttribute
  14073. */
  14074. class Uint32BufferAttribute extends BufferAttribute {
  14075. /**
  14076. * Constructs a new buffer attribute.
  14077. *
  14078. * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data.
  14079. * @param {number} itemSize - The item size.
  14080. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14081. */
  14082. constructor( array, itemSize, normalized ) {
  14083. super( new Uint32Array( array ), itemSize, normalized );
  14084. }
  14085. }
  14086. /**
  14087. * Convenient class that can be used when creating a `Float16` buffer attribute with
  14088. * a plain `Array` instance.
  14089. *
  14090. * This class automatically converts to and from FP16 via `Uint16Array` since `Float16Array`
  14091. * browser support is still problematic.
  14092. *
  14093. * @augments BufferAttribute
  14094. */
  14095. class Float16BufferAttribute extends BufferAttribute {
  14096. /**
  14097. * Constructs a new buffer attribute.
  14098. *
  14099. * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data.
  14100. * @param {number} itemSize - The item size.
  14101. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14102. */
  14103. constructor( array, itemSize, normalized ) {
  14104. super( new Uint16Array( array ), itemSize, normalized );
  14105. this.isFloat16BufferAttribute = true;
  14106. }
  14107. getX( index ) {
  14108. let x = fromHalfFloat( this.array[ index * this.itemSize ] );
  14109. if ( this.normalized ) x = denormalize( x, this.array );
  14110. return x;
  14111. }
  14112. setX( index, x ) {
  14113. if ( this.normalized ) x = normalize( x, this.array );
  14114. this.array[ index * this.itemSize ] = toHalfFloat( x );
  14115. return this;
  14116. }
  14117. getY( index ) {
  14118. let y = fromHalfFloat( this.array[ index * this.itemSize + 1 ] );
  14119. if ( this.normalized ) y = denormalize( y, this.array );
  14120. return y;
  14121. }
  14122. setY( index, y ) {
  14123. if ( this.normalized ) y = normalize( y, this.array );
  14124. this.array[ index * this.itemSize + 1 ] = toHalfFloat( y );
  14125. return this;
  14126. }
  14127. getZ( index ) {
  14128. let z = fromHalfFloat( this.array[ index * this.itemSize + 2 ] );
  14129. if ( this.normalized ) z = denormalize( z, this.array );
  14130. return z;
  14131. }
  14132. setZ( index, z ) {
  14133. if ( this.normalized ) z = normalize( z, this.array );
  14134. this.array[ index * this.itemSize + 2 ] = toHalfFloat( z );
  14135. return this;
  14136. }
  14137. getW( index ) {
  14138. let w = fromHalfFloat( this.array[ index * this.itemSize + 3 ] );
  14139. if ( this.normalized ) w = denormalize( w, this.array );
  14140. return w;
  14141. }
  14142. setW( index, w ) {
  14143. if ( this.normalized ) w = normalize( w, this.array );
  14144. this.array[ index * this.itemSize + 3 ] = toHalfFloat( w );
  14145. return this;
  14146. }
  14147. setXY( index, x, y ) {
  14148. index *= this.itemSize;
  14149. if ( this.normalized ) {
  14150. x = normalize( x, this.array );
  14151. y = normalize( y, this.array );
  14152. }
  14153. this.array[ index + 0 ] = toHalfFloat( x );
  14154. this.array[ index + 1 ] = toHalfFloat( y );
  14155. return this;
  14156. }
  14157. setXYZ( index, x, y, z ) {
  14158. index *= this.itemSize;
  14159. if ( this.normalized ) {
  14160. x = normalize( x, this.array );
  14161. y = normalize( y, this.array );
  14162. z = normalize( z, this.array );
  14163. }
  14164. this.array[ index + 0 ] = toHalfFloat( x );
  14165. this.array[ index + 1 ] = toHalfFloat( y );
  14166. this.array[ index + 2 ] = toHalfFloat( z );
  14167. return this;
  14168. }
  14169. setXYZW( index, x, y, z, w ) {
  14170. index *= this.itemSize;
  14171. if ( this.normalized ) {
  14172. x = normalize( x, this.array );
  14173. y = normalize( y, this.array );
  14174. z = normalize( z, this.array );
  14175. w = normalize( w, this.array );
  14176. }
  14177. this.array[ index + 0 ] = toHalfFloat( x );
  14178. this.array[ index + 1 ] = toHalfFloat( y );
  14179. this.array[ index + 2 ] = toHalfFloat( z );
  14180. this.array[ index + 3 ] = toHalfFloat( w );
  14181. return this;
  14182. }
  14183. }
  14184. /**
  14185. * Convenient class that can be used when creating a `Float32` buffer attribute with
  14186. * a plain `Array` instance.
  14187. *
  14188. * @augments BufferAttribute
  14189. */
  14190. class Float32BufferAttribute extends BufferAttribute {
  14191. /**
  14192. * Constructs a new buffer attribute.
  14193. *
  14194. * @param {(Array<number>|Float32Array)} array - The array holding the attribute data.
  14195. * @param {number} itemSize - The item size.
  14196. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  14197. */
  14198. constructor( array, itemSize, normalized ) {
  14199. super( new Float32Array( array ), itemSize, normalized );
  14200. }
  14201. }
  14202. let _id$2 = 0;
  14203. const _m1$2 = /*@__PURE__*/ new Matrix4();
  14204. const _obj = /*@__PURE__*/ new Object3D();
  14205. const _offset = /*@__PURE__*/ new Vector3();
  14206. const _box$2 = /*@__PURE__*/ new Box3();
  14207. const _boxMorphTargets = /*@__PURE__*/ new Box3();
  14208. const _vector$8 = /*@__PURE__*/ new Vector3();
  14209. /**
  14210. * A representation of mesh, line, or point geometry. Includes vertex
  14211. * positions, face indices, normals, colors, UVs, and custom attributes
  14212. * within buffers, reducing the cost of passing all this data to the GPU.
  14213. *
  14214. * ```js
  14215. * const geometry = new THREE.BufferGeometry();
  14216. * // create a simple square shape. We duplicate the top left and bottom right
  14217. * // vertices because each vertex needs to appear once per triangle.
  14218. * const vertices = new Float32Array( [
  14219. * -1.0, -1.0, 1.0, // v0
  14220. * 1.0, -1.0, 1.0, // v1
  14221. * 1.0, 1.0, 1.0, // v2
  14222. *
  14223. * 1.0, 1.0, 1.0, // v3
  14224. * -1.0, 1.0, 1.0, // v4
  14225. * -1.0, -1.0, 1.0 // v5
  14226. * ] );
  14227. * // itemSize = 3 because there are 3 values (components) per vertex
  14228. * geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  14229. * const material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
  14230. * const mesh = new THREE.Mesh( geometry, material );
  14231. * ```
  14232. *
  14233. * @augments EventDispatcher
  14234. */
  14235. class BufferGeometry extends EventDispatcher {
  14236. /**
  14237. * Constructs a new geometry.
  14238. */
  14239. constructor() {
  14240. super();
  14241. /**
  14242. * This flag can be used for type testing.
  14243. *
  14244. * @type {boolean}
  14245. * @readonly
  14246. * @default true
  14247. */
  14248. this.isBufferGeometry = true;
  14249. /**
  14250. * The ID of the geometry.
  14251. *
  14252. * @name BufferGeometry#id
  14253. * @type {number}
  14254. * @readonly
  14255. */
  14256. Object.defineProperty( this, 'id', { value: _id$2 ++ } );
  14257. /**
  14258. * The UUID of the geometry.
  14259. *
  14260. * @type {string}
  14261. * @readonly
  14262. */
  14263. this.uuid = generateUUID();
  14264. /**
  14265. * The name of the geometry.
  14266. *
  14267. * @type {string}
  14268. */
  14269. this.name = '';
  14270. this.type = 'BufferGeometry';
  14271. /**
  14272. * Allows for vertices to be re-used across multiple triangles; this is
  14273. * called using "indexed triangles". Each triangle is associated with the
  14274. * indices of three vertices. This attribute therefore stores the index of
  14275. * each vertex for each triangular face. If this attribute is not set, the
  14276. * renderer assumes that each three contiguous positions represent a single triangle.
  14277. *
  14278. * @type {?BufferAttribute}
  14279. * @default null
  14280. */
  14281. this.index = null;
  14282. /**
  14283. * A (storage) buffer attribute which was generated with a compute shader and
  14284. * now defines indirect draw calls.
  14285. *
  14286. * Can only be used with {@link WebGPURenderer} and a WebGPU backend.
  14287. *
  14288. * @type {?BufferAttribute}
  14289. * @default null
  14290. */
  14291. this.indirect = null;
  14292. /**
  14293. * This dictionary has as id the name of the attribute to be set and as value
  14294. * the buffer attribute to set it to. Rather than accessing this property directly,
  14295. * use `setAttribute()` and `getAttribute()` to access attributes of this geometry.
  14296. *
  14297. * @type {Object<string,(BufferAttribute|InterleavedBufferAttribute)>}
  14298. */
  14299. this.attributes = {};
  14300. /**
  14301. * This dictionary holds the morph targets of the geometry.
  14302. *
  14303. * Note: Once the geometry has been rendered, the morph attribute data cannot
  14304. * be changed. You will have to call `dispose()?, and create a new geometry instance.
  14305. *
  14306. * @type {Object}
  14307. */
  14308. this.morphAttributes = {};
  14309. /**
  14310. * Used to control the morph target behavior; when set to `true`, the morph
  14311. * target data is treated as relative offsets, rather than as absolute
  14312. * positions/normals.
  14313. *
  14314. * @type {boolean}
  14315. * @default false
  14316. */
  14317. this.morphTargetsRelative = false;
  14318. /**
  14319. * Split the geometry into groups, each of which will be rendered in a
  14320. * separate draw call. This allows an array of materials to be used with the geometry.
  14321. *
  14322. * Use `addGroup()` and `clearGroups()` to edit groups, rather than modifying this array directly.
  14323. *
  14324. * Every vertex and index must belong to exactly one group — groups must not share vertices or
  14325. * indices, and must not leave vertices or indices unused.
  14326. *
  14327. * @type {Array<Object>}
  14328. */
  14329. this.groups = [];
  14330. /**
  14331. * Bounding box for the geometry which can be calculated with `computeBoundingBox()`.
  14332. *
  14333. * @type {?Box3}
  14334. * @default null
  14335. */
  14336. this.boundingBox = null;
  14337. /**
  14338. * Bounding sphere for the geometry which can be calculated with `computeBoundingSphere()`.
  14339. *
  14340. * @type {?Sphere}
  14341. * @default null
  14342. */
  14343. this.boundingSphere = null;
  14344. /**
  14345. * Determines the part of the geometry to render. This should not be set directly,
  14346. * instead use `setDrawRange()`.
  14347. *
  14348. * @type {{start:number,count:number}}
  14349. */
  14350. this.drawRange = { start: 0, count: Infinity };
  14351. /**
  14352. * An object that can be used to store custom data about the geometry.
  14353. * It should not hold references to functions as these will not be cloned.
  14354. *
  14355. * @type {Object}
  14356. */
  14357. this.userData = {};
  14358. }
  14359. /**
  14360. * Returns the index of this geometry.
  14361. *
  14362. * @return {?BufferAttribute} The index. Returns `null` if no index is defined.
  14363. */
  14364. getIndex() {
  14365. return this.index;
  14366. }
  14367. /**
  14368. * Sets the given index to this geometry.
  14369. *
  14370. * @param {Array<number>|BufferAttribute} index - The index to set.
  14371. * @return {BufferGeometry} A reference to this instance.
  14372. */
  14373. setIndex( index ) {
  14374. if ( Array.isArray( index ) ) {
  14375. this.index = new ( arrayNeedsUint32( index ) ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  14376. } else {
  14377. this.index = index;
  14378. }
  14379. return this;
  14380. }
  14381. /**
  14382. * Sets the given indirect attribute to this geometry.
  14383. *
  14384. * @param {BufferAttribute} indirect - The attribute holding indirect draw calls.
  14385. * @return {BufferGeometry} A reference to this instance.
  14386. */
  14387. setIndirect( indirect ) {
  14388. this.indirect = indirect;
  14389. return this;
  14390. }
  14391. /**
  14392. * Returns the indirect attribute of this geometry.
  14393. *
  14394. * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined.
  14395. */
  14396. getIndirect() {
  14397. return this.indirect;
  14398. }
  14399. /**
  14400. * Returns the buffer attribute for the given name.
  14401. *
  14402. * @param {string} name - The attribute name.
  14403. * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute.
  14404. * Returns `undefined` if not attribute has been found.
  14405. */
  14406. getAttribute( name ) {
  14407. return this.attributes[ name ];
  14408. }
  14409. /**
  14410. * Sets the given attribute for the given name.
  14411. *
  14412. * @param {string} name - The attribute name.
  14413. * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set.
  14414. * @return {BufferGeometry} A reference to this instance.
  14415. */
  14416. setAttribute( name, attribute ) {
  14417. this.attributes[ name ] = attribute;
  14418. return this;
  14419. }
  14420. /**
  14421. * Deletes the attribute for the given name.
  14422. *
  14423. * @param {string} name - The attribute name to delete.
  14424. * @return {BufferGeometry} A reference to this instance.
  14425. */
  14426. deleteAttribute( name ) {
  14427. delete this.attributes[ name ];
  14428. return this;
  14429. }
  14430. /**
  14431. * Returns `true` if this geometry has an attribute for the given name.
  14432. *
  14433. * @param {string} name - The attribute name.
  14434. * @return {boolean} Whether this geometry has an attribute for the given name or not.
  14435. */
  14436. hasAttribute( name ) {
  14437. return this.attributes[ name ] !== undefined;
  14438. }
  14439. /**
  14440. * Adds a group to this geometry.
  14441. *
  14442. * @param {number} start - The first element in this draw call. That is the first
  14443. * vertex for non-indexed geometry, otherwise the first triangle index.
  14444. * @param {number} count - Specifies how many vertices (or indices) are part of this group.
  14445. * @param {number} [materialIndex=0] - The material array index to use.
  14446. */
  14447. addGroup( start, count, materialIndex = 0 ) {
  14448. this.groups.push( {
  14449. start: start,
  14450. count: count,
  14451. materialIndex: materialIndex
  14452. } );
  14453. }
  14454. /**
  14455. * Clears all groups.
  14456. */
  14457. clearGroups() {
  14458. this.groups = [];
  14459. }
  14460. /**
  14461. * Sets the draw range for this geometry.
  14462. *
  14463. * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index.
  14464. * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render.
  14465. * For indexed BufferGeometry, `count` is the number of indices to render.
  14466. */
  14467. setDrawRange( start, count ) {
  14468. this.drawRange.start = start;
  14469. this.drawRange.count = count;
  14470. }
  14471. /**
  14472. * Applies the given 4x4 transformation matrix to the geometry.
  14473. *
  14474. * @param {Matrix4} matrix - The matrix to apply.
  14475. * @return {BufferGeometry} A reference to this instance.
  14476. */
  14477. applyMatrix4( matrix ) {
  14478. const position = this.attributes.position;
  14479. if ( position !== undefined ) {
  14480. position.applyMatrix4( matrix );
  14481. position.needsUpdate = true;
  14482. }
  14483. const normal = this.attributes.normal;
  14484. if ( normal !== undefined ) {
  14485. const normalMatrix = new Matrix3().getNormalMatrix( matrix );
  14486. normal.applyNormalMatrix( normalMatrix );
  14487. normal.needsUpdate = true;
  14488. }
  14489. const tangent = this.attributes.tangent;
  14490. if ( tangent !== undefined ) {
  14491. tangent.transformDirection( matrix );
  14492. tangent.needsUpdate = true;
  14493. }
  14494. if ( this.boundingBox !== null ) {
  14495. this.computeBoundingBox();
  14496. }
  14497. if ( this.boundingSphere !== null ) {
  14498. this.computeBoundingSphere();
  14499. }
  14500. return this;
  14501. }
  14502. /**
  14503. * Applies the rotation represented by the Quaternion to the geometry.
  14504. *
  14505. * @param {Quaternion} q - The Quaternion to apply.
  14506. * @return {BufferGeometry} A reference to this instance.
  14507. */
  14508. applyQuaternion( q ) {
  14509. _m1$2.makeRotationFromQuaternion( q );
  14510. this.applyMatrix4( _m1$2 );
  14511. return this;
  14512. }
  14513. /**
  14514. * Rotates the geometry about the X axis. This is typically done as a one time
  14515. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14516. * real-time mesh rotation.
  14517. *
  14518. * @param {number} angle - The angle in radians.
  14519. * @return {BufferGeometry} A reference to this instance.
  14520. */
  14521. rotateX( angle ) {
  14522. // rotate geometry around world x-axis
  14523. _m1$2.makeRotationX( angle );
  14524. this.applyMatrix4( _m1$2 );
  14525. return this;
  14526. }
  14527. /**
  14528. * Rotates the geometry about the Y axis. This is typically done as a one time
  14529. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14530. * real-time mesh rotation.
  14531. *
  14532. * @param {number} angle - The angle in radians.
  14533. * @return {BufferGeometry} A reference to this instance.
  14534. */
  14535. rotateY( angle ) {
  14536. // rotate geometry around world y-axis
  14537. _m1$2.makeRotationY( angle );
  14538. this.applyMatrix4( _m1$2 );
  14539. return this;
  14540. }
  14541. /**
  14542. * Rotates the geometry about the Z axis. This is typically done as a one time
  14543. * operation, and not during a loop. Use {@link Object3D#rotation} for typical
  14544. * real-time mesh rotation.
  14545. *
  14546. * @param {number} angle - The angle in radians.
  14547. * @return {BufferGeometry} A reference to this instance.
  14548. */
  14549. rotateZ( angle ) {
  14550. // rotate geometry around world z-axis
  14551. _m1$2.makeRotationZ( angle );
  14552. this.applyMatrix4( _m1$2 );
  14553. return this;
  14554. }
  14555. /**
  14556. * Translates the geometry. This is typically done as a one time
  14557. * operation, and not during a loop. Use {@link Object3D#position} for typical
  14558. * real-time mesh rotation.
  14559. *
  14560. * @param {number} x - The x offset.
  14561. * @param {number} y - The y offset.
  14562. * @param {number} z - The z offset.
  14563. * @return {BufferGeometry} A reference to this instance.
  14564. */
  14565. translate( x, y, z ) {
  14566. // translate geometry
  14567. _m1$2.makeTranslation( x, y, z );
  14568. this.applyMatrix4( _m1$2 );
  14569. return this;
  14570. }
  14571. /**
  14572. * Scales the geometry. This is typically done as a one time
  14573. * operation, and not during a loop. Use {@link Object3D#scale} for typical
  14574. * real-time mesh rotation.
  14575. *
  14576. * @param {number} x - The x scale.
  14577. * @param {number} y - The y scale.
  14578. * @param {number} z - The z scale.
  14579. * @return {BufferGeometry} A reference to this instance.
  14580. */
  14581. scale( x, y, z ) {
  14582. // scale geometry
  14583. _m1$2.makeScale( x, y, z );
  14584. this.applyMatrix4( _m1$2 );
  14585. return this;
  14586. }
  14587. /**
  14588. * Rotates the geometry to face a point in 3D space. This is typically done as a one time
  14589. * operation, and not during a loop. Use {@link Object3D#lookAt} for typical
  14590. * real-time mesh rotation.
  14591. *
  14592. * @param {Vector3} vector - The target point.
  14593. * @return {BufferGeometry} A reference to this instance.
  14594. */
  14595. lookAt( vector ) {
  14596. _obj.lookAt( vector );
  14597. _obj.updateMatrix();
  14598. this.applyMatrix4( _obj.matrix );
  14599. return this;
  14600. }
  14601. /**
  14602. * Center the geometry based on its bounding box.
  14603. *
  14604. * @return {BufferGeometry} A reference to this instance.
  14605. */
  14606. center() {
  14607. this.computeBoundingBox();
  14608. this.boundingBox.getCenter( _offset ).negate();
  14609. this.translate( _offset.x, _offset.y, _offset.z );
  14610. return this;
  14611. }
  14612. /**
  14613. * Defines a geometry by creating a `position` attribute based on the given array of points. The array
  14614. * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is
  14615. * set to `0`.
  14616. *
  14617. * If the method is used with an existing `position` attribute, the vertex data are overwritten with the
  14618. * data from the array. The length of the array must match the vertex count.
  14619. *
  14620. * @param {Array<Vector2>|Array<Vector3>} points - The points.
  14621. * @return {BufferGeometry} A reference to this instance.
  14622. */
  14623. setFromPoints( points ) {
  14624. const positionAttribute = this.getAttribute( 'position' );
  14625. if ( positionAttribute === undefined ) {
  14626. const position = [];
  14627. for ( let i = 0, l = points.length; i < l; i ++ ) {
  14628. const point = points[ i ];
  14629. position.push( point.x, point.y, point.z || 0 );
  14630. }
  14631. this.setAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  14632. } else {
  14633. const l = Math.min( points.length, positionAttribute.count ); // make sure data do not exceed buffer size
  14634. for ( let i = 0; i < l; i ++ ) {
  14635. const point = points[ i ];
  14636. positionAttribute.setXYZ( i, point.x, point.y, point.z || 0 );
  14637. }
  14638. if ( points.length > positionAttribute.count ) {
  14639. warn( 'BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.' );
  14640. }
  14641. positionAttribute.needsUpdate = true;
  14642. }
  14643. return this;
  14644. }
  14645. /**
  14646. * Computes the bounding box of the geometry, and updates the `boundingBox` member.
  14647. * The bounding box is not computed by the engine; it must be computed by your app.
  14648. * You may need to recompute the bounding box if the geometry vertices are modified.
  14649. */
  14650. computeBoundingBox() {
  14651. if ( this.boundingBox === null ) {
  14652. this.boundingBox = new Box3();
  14653. }
  14654. const position = this.attributes.position;
  14655. const morphAttributesPosition = this.morphAttributes.position;
  14656. if ( position && position.isGLBufferAttribute ) {
  14657. error( 'BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.', this );
  14658. this.boundingBox.set(
  14659. new Vector3( - Infinity, - Infinity, - Infinity ),
  14660. new Vector3( + Infinity, + Infinity, + Infinity )
  14661. );
  14662. return;
  14663. }
  14664. if ( position !== undefined ) {
  14665. this.boundingBox.setFromBufferAttribute( position );
  14666. // process morph attributes if present
  14667. if ( morphAttributesPosition ) {
  14668. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14669. const morphAttribute = morphAttributesPosition[ i ];
  14670. _box$2.setFromBufferAttribute( morphAttribute );
  14671. if ( this.morphTargetsRelative ) {
  14672. _vector$8.addVectors( this.boundingBox.min, _box$2.min );
  14673. this.boundingBox.expandByPoint( _vector$8 );
  14674. _vector$8.addVectors( this.boundingBox.max, _box$2.max );
  14675. this.boundingBox.expandByPoint( _vector$8 );
  14676. } else {
  14677. this.boundingBox.expandByPoint( _box$2.min );
  14678. this.boundingBox.expandByPoint( _box$2.max );
  14679. }
  14680. }
  14681. }
  14682. } else {
  14683. this.boundingBox.makeEmpty();
  14684. }
  14685. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  14686. error( 'BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  14687. }
  14688. }
  14689. /**
  14690. * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member.
  14691. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  14692. * You may need to recompute the bounding sphere if the geometry vertices are modified.
  14693. */
  14694. computeBoundingSphere() {
  14695. if ( this.boundingSphere === null ) {
  14696. this.boundingSphere = new Sphere();
  14697. }
  14698. const position = this.attributes.position;
  14699. const morphAttributesPosition = this.morphAttributes.position;
  14700. if ( position && position.isGLBufferAttribute ) {
  14701. error( 'BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.', this );
  14702. this.boundingSphere.set( new Vector3(), Infinity );
  14703. return;
  14704. }
  14705. if ( position ) {
  14706. // first, find the center of the bounding sphere
  14707. const center = this.boundingSphere.center;
  14708. _box$2.setFromBufferAttribute( position );
  14709. // process morph attributes if present
  14710. if ( morphAttributesPosition ) {
  14711. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14712. const morphAttribute = morphAttributesPosition[ i ];
  14713. _boxMorphTargets.setFromBufferAttribute( morphAttribute );
  14714. if ( this.morphTargetsRelative ) {
  14715. _vector$8.addVectors( _box$2.min, _boxMorphTargets.min );
  14716. _box$2.expandByPoint( _vector$8 );
  14717. _vector$8.addVectors( _box$2.max, _boxMorphTargets.max );
  14718. _box$2.expandByPoint( _vector$8 );
  14719. } else {
  14720. _box$2.expandByPoint( _boxMorphTargets.min );
  14721. _box$2.expandByPoint( _boxMorphTargets.max );
  14722. }
  14723. }
  14724. }
  14725. _box$2.getCenter( center );
  14726. // second, try to find a boundingSphere with a radius smaller than the
  14727. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  14728. let maxRadiusSq = 0;
  14729. for ( let i = 0, il = position.count; i < il; i ++ ) {
  14730. _vector$8.fromBufferAttribute( position, i );
  14731. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14732. }
  14733. // process morph attributes if present
  14734. if ( morphAttributesPosition ) {
  14735. for ( let i = 0, il = morphAttributesPosition.length; i < il; i ++ ) {
  14736. const morphAttribute = morphAttributesPosition[ i ];
  14737. const morphTargetsRelative = this.morphTargetsRelative;
  14738. for ( let j = 0, jl = morphAttribute.count; j < jl; j ++ ) {
  14739. _vector$8.fromBufferAttribute( morphAttribute, j );
  14740. if ( morphTargetsRelative ) {
  14741. _offset.fromBufferAttribute( position, j );
  14742. _vector$8.add( _offset );
  14743. }
  14744. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( _vector$8 ) );
  14745. }
  14746. }
  14747. }
  14748. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  14749. if ( isNaN( this.boundingSphere.radius ) ) {
  14750. error( 'BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  14751. }
  14752. }
  14753. }
  14754. /**
  14755. * Calculates and adds a tangent attribute to this geometry.
  14756. *
  14757. * The computation is only supported for indexed geometries and if position, normal, and uv attributes
  14758. * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by
  14759. * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead.
  14760. */
  14761. computeTangents() {
  14762. const index = this.index;
  14763. const attributes = this.attributes;
  14764. // based on http://www.terathon.com/code/tangent.html
  14765. // (per vertex tangents)
  14766. if ( index === null ||
  14767. attributes.position === undefined ||
  14768. attributes.normal === undefined ||
  14769. attributes.uv === undefined ) {
  14770. error( 'BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)' );
  14771. return;
  14772. }
  14773. const positionAttribute = attributes.position;
  14774. const normalAttribute = attributes.normal;
  14775. const uvAttribute = attributes.uv;
  14776. if ( this.hasAttribute( 'tangent' ) === false ) {
  14777. this.setAttribute( 'tangent', new BufferAttribute( new Float32Array( 4 * positionAttribute.count ), 4 ) );
  14778. }
  14779. const tangentAttribute = this.getAttribute( 'tangent' );
  14780. const tan1 = [], tan2 = [];
  14781. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  14782. tan1[ i ] = new Vector3();
  14783. tan2[ i ] = new Vector3();
  14784. }
  14785. const vA = new Vector3(),
  14786. vB = new Vector3(),
  14787. vC = new Vector3(),
  14788. uvA = new Vector2(),
  14789. uvB = new Vector2(),
  14790. uvC = new Vector2(),
  14791. sdir = new Vector3(),
  14792. tdir = new Vector3();
  14793. function handleTriangle( a, b, c ) {
  14794. vA.fromBufferAttribute( positionAttribute, a );
  14795. vB.fromBufferAttribute( positionAttribute, b );
  14796. vC.fromBufferAttribute( positionAttribute, c );
  14797. uvA.fromBufferAttribute( uvAttribute, a );
  14798. uvB.fromBufferAttribute( uvAttribute, b );
  14799. uvC.fromBufferAttribute( uvAttribute, c );
  14800. vB.sub( vA );
  14801. vC.sub( vA );
  14802. uvB.sub( uvA );
  14803. uvC.sub( uvA );
  14804. const r = 1.0 / ( uvB.x * uvC.y - uvC.x * uvB.y );
  14805. // silently ignore degenerate uv triangles having coincident or colinear vertices
  14806. if ( ! isFinite( r ) ) return;
  14807. sdir.copy( vB ).multiplyScalar( uvC.y ).addScaledVector( vC, - uvB.y ).multiplyScalar( r );
  14808. tdir.copy( vC ).multiplyScalar( uvB.x ).addScaledVector( vB, - uvC.x ).multiplyScalar( r );
  14809. tan1[ a ].add( sdir );
  14810. tan1[ b ].add( sdir );
  14811. tan1[ c ].add( sdir );
  14812. tan2[ a ].add( tdir );
  14813. tan2[ b ].add( tdir );
  14814. tan2[ c ].add( tdir );
  14815. }
  14816. let groups = this.groups;
  14817. if ( groups.length === 0 ) {
  14818. groups = [ {
  14819. start: 0,
  14820. count: index.count
  14821. } ];
  14822. }
  14823. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14824. const group = groups[ i ];
  14825. const start = group.start;
  14826. const count = group.count;
  14827. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14828. handleTriangle(
  14829. index.getX( j + 0 ),
  14830. index.getX( j + 1 ),
  14831. index.getX( j + 2 )
  14832. );
  14833. }
  14834. }
  14835. const tmp = new Vector3(), tmp2 = new Vector3();
  14836. const n = new Vector3(), n2 = new Vector3();
  14837. function handleVertex( v ) {
  14838. n.fromBufferAttribute( normalAttribute, v );
  14839. n2.copy( n );
  14840. const t = tan1[ v ];
  14841. // Gram-Schmidt orthogonalize
  14842. tmp.copy( t );
  14843. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  14844. // Calculate handedness
  14845. tmp2.crossVectors( n2, t );
  14846. const test = tmp2.dot( tan2[ v ] );
  14847. const w = ( test < 0.0 ) ? -1 : 1.0;
  14848. tangentAttribute.setXYZW( v, tmp.x, tmp.y, tmp.z, w );
  14849. }
  14850. for ( let i = 0, il = groups.length; i < il; ++ i ) {
  14851. const group = groups[ i ];
  14852. const start = group.start;
  14853. const count = group.count;
  14854. for ( let j = start, jl = start + count; j < jl; j += 3 ) {
  14855. handleVertex( index.getX( j + 0 ) );
  14856. handleVertex( index.getX( j + 1 ) );
  14857. handleVertex( index.getX( j + 2 ) );
  14858. }
  14859. }
  14860. }
  14861. /**
  14862. * Computes vertex normals for the given vertex data. For indexed geometries, the method sets
  14863. * each vertex normal to be the average of the face normals of the faces that share that vertex.
  14864. * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal
  14865. * to be the same as the face normal.
  14866. */
  14867. computeVertexNormals() {
  14868. const index = this.index;
  14869. const positionAttribute = this.getAttribute( 'position' );
  14870. if ( positionAttribute !== undefined ) {
  14871. let normalAttribute = this.getAttribute( 'normal' );
  14872. if ( normalAttribute === undefined ) {
  14873. normalAttribute = new BufferAttribute( new Float32Array( positionAttribute.count * 3 ), 3 );
  14874. this.setAttribute( 'normal', normalAttribute );
  14875. } else {
  14876. // reset existing normals to zero
  14877. for ( let i = 0, il = normalAttribute.count; i < il; i ++ ) {
  14878. normalAttribute.setXYZ( i, 0, 0, 0 );
  14879. }
  14880. }
  14881. const pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  14882. const nA = new Vector3(), nB = new Vector3(), nC = new Vector3();
  14883. const cb = new Vector3(), ab = new Vector3();
  14884. // indexed elements
  14885. if ( index ) {
  14886. for ( let i = 0, il = index.count; i < il; i += 3 ) {
  14887. const vA = index.getX( i + 0 );
  14888. const vB = index.getX( i + 1 );
  14889. const vC = index.getX( i + 2 );
  14890. pA.fromBufferAttribute( positionAttribute, vA );
  14891. pB.fromBufferAttribute( positionAttribute, vB );
  14892. pC.fromBufferAttribute( positionAttribute, vC );
  14893. cb.subVectors( pC, pB );
  14894. ab.subVectors( pA, pB );
  14895. cb.cross( ab );
  14896. nA.fromBufferAttribute( normalAttribute, vA );
  14897. nB.fromBufferAttribute( normalAttribute, vB );
  14898. nC.fromBufferAttribute( normalAttribute, vC );
  14899. nA.add( cb );
  14900. nB.add( cb );
  14901. nC.add( cb );
  14902. normalAttribute.setXYZ( vA, nA.x, nA.y, nA.z );
  14903. normalAttribute.setXYZ( vB, nB.x, nB.y, nB.z );
  14904. normalAttribute.setXYZ( vC, nC.x, nC.y, nC.z );
  14905. }
  14906. } else {
  14907. // non-indexed elements (unconnected triangle soup)
  14908. for ( let i = 0, il = positionAttribute.count; i < il; i += 3 ) {
  14909. pA.fromBufferAttribute( positionAttribute, i + 0 );
  14910. pB.fromBufferAttribute( positionAttribute, i + 1 );
  14911. pC.fromBufferAttribute( positionAttribute, i + 2 );
  14912. cb.subVectors( pC, pB );
  14913. ab.subVectors( pA, pB );
  14914. cb.cross( ab );
  14915. normalAttribute.setXYZ( i + 0, cb.x, cb.y, cb.z );
  14916. normalAttribute.setXYZ( i + 1, cb.x, cb.y, cb.z );
  14917. normalAttribute.setXYZ( i + 2, cb.x, cb.y, cb.z );
  14918. }
  14919. }
  14920. this.normalizeNormals();
  14921. normalAttribute.needsUpdate = true;
  14922. }
  14923. }
  14924. /**
  14925. * Ensures every normal vector in a geometry will have a magnitude of `1`. This will
  14926. * correct lighting on the geometry surfaces.
  14927. */
  14928. normalizeNormals() {
  14929. const normals = this.attributes.normal;
  14930. for ( let i = 0, il = normals.count; i < il; i ++ ) {
  14931. _vector$8.fromBufferAttribute( normals, i );
  14932. _vector$8.normalize();
  14933. normals.setXYZ( i, _vector$8.x, _vector$8.y, _vector$8.z );
  14934. }
  14935. }
  14936. /**
  14937. * Return a new non-index version of this indexed geometry. If the geometry
  14938. * is already non-indexed, the method is a NOOP.
  14939. *
  14940. * @return {BufferGeometry} The non-indexed version of this indexed geometry.
  14941. */
  14942. toNonIndexed() {
  14943. function convertBufferAttribute( attribute, indices ) {
  14944. const array = attribute.array;
  14945. const itemSize = attribute.itemSize;
  14946. const normalized = attribute.normalized;
  14947. const array2 = new array.constructor( indices.length * itemSize );
  14948. let index = 0, index2 = 0;
  14949. for ( let i = 0, l = indices.length; i < l; i ++ ) {
  14950. if ( attribute.isInterleavedBufferAttribute ) {
  14951. index = indices[ i ] * attribute.data.stride + attribute.offset;
  14952. } else {
  14953. index = indices[ i ] * itemSize;
  14954. }
  14955. for ( let j = 0; j < itemSize; j ++ ) {
  14956. array2[ index2 ++ ] = array[ index ++ ];
  14957. }
  14958. }
  14959. return new BufferAttribute( array2, itemSize, normalized );
  14960. }
  14961. //
  14962. if ( this.index === null ) {
  14963. warn( 'BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed.' );
  14964. return this;
  14965. }
  14966. const geometry2 = new BufferGeometry();
  14967. const indices = this.index.array;
  14968. const attributes = this.attributes;
  14969. // attributes
  14970. for ( const name in attributes ) {
  14971. const attribute = attributes[ name ];
  14972. const newAttribute = convertBufferAttribute( attribute, indices );
  14973. geometry2.setAttribute( name, newAttribute );
  14974. }
  14975. // morph attributes
  14976. const morphAttributes = this.morphAttributes;
  14977. for ( const name in morphAttributes ) {
  14978. const morphArray = [];
  14979. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  14980. for ( let i = 0, il = morphAttribute.length; i < il; i ++ ) {
  14981. const attribute = morphAttribute[ i ];
  14982. const newAttribute = convertBufferAttribute( attribute, indices );
  14983. morphArray.push( newAttribute );
  14984. }
  14985. geometry2.morphAttributes[ name ] = morphArray;
  14986. }
  14987. geometry2.morphTargetsRelative = this.morphTargetsRelative;
  14988. // groups
  14989. const groups = this.groups;
  14990. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  14991. const group = groups[ i ];
  14992. geometry2.addGroup( group.start, group.count, group.materialIndex );
  14993. }
  14994. return geometry2;
  14995. }
  14996. /**
  14997. * Serializes the geometry into JSON.
  14998. *
  14999. * @return {Object} A JSON object representing the serialized geometry.
  15000. */
  15001. toJSON() {
  15002. const data = {
  15003. metadata: {
  15004. version: 4.7,
  15005. type: 'BufferGeometry',
  15006. generator: 'BufferGeometry.toJSON'
  15007. }
  15008. };
  15009. // standard BufferGeometry serialization
  15010. data.uuid = this.uuid;
  15011. data.type = this.type;
  15012. if ( this.name !== '' ) data.name = this.name;
  15013. if ( Object.keys( this.userData ).length > 0 ) data.userData = this.userData;
  15014. if ( this.parameters !== undefined ) {
  15015. const parameters = this.parameters;
  15016. for ( const key in parameters ) {
  15017. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  15018. }
  15019. return data;
  15020. }
  15021. // for simplicity the code assumes attributes are not shared across geometries, see #15811
  15022. data.data = { attributes: {} };
  15023. const index = this.index;
  15024. if ( index !== null ) {
  15025. data.data.index = {
  15026. type: index.array.constructor.name,
  15027. array: Array.prototype.slice.call( index.array )
  15028. };
  15029. }
  15030. const attributes = this.attributes;
  15031. for ( const key in attributes ) {
  15032. const attribute = attributes[ key ];
  15033. data.data.attributes[ key ] = attribute.toJSON( data.data );
  15034. }
  15035. const morphAttributes = {};
  15036. let hasMorphAttributes = false;
  15037. for ( const key in this.morphAttributes ) {
  15038. const attributeArray = this.morphAttributes[ key ];
  15039. const array = [];
  15040. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  15041. const attribute = attributeArray[ i ];
  15042. array.push( attribute.toJSON( data.data ) );
  15043. }
  15044. if ( array.length > 0 ) {
  15045. morphAttributes[ key ] = array;
  15046. hasMorphAttributes = true;
  15047. }
  15048. }
  15049. if ( hasMorphAttributes ) {
  15050. data.data.morphAttributes = morphAttributes;
  15051. data.data.morphTargetsRelative = this.morphTargetsRelative;
  15052. }
  15053. const groups = this.groups;
  15054. if ( groups.length > 0 ) {
  15055. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  15056. }
  15057. const boundingSphere = this.boundingSphere;
  15058. if ( boundingSphere !== null ) {
  15059. data.data.boundingSphere = boundingSphere.toJSON();
  15060. }
  15061. return data;
  15062. }
  15063. /**
  15064. * Returns a new geometry with copied values from this instance.
  15065. *
  15066. * @return {BufferGeometry} A clone of this instance.
  15067. */
  15068. clone() {
  15069. return new this.constructor().copy( this );
  15070. }
  15071. /**
  15072. * Copies the values of the given geometry to this instance.
  15073. *
  15074. * @param {BufferGeometry} source - The geometry to copy.
  15075. * @return {BufferGeometry} A reference to this instance.
  15076. */
  15077. copy( source ) {
  15078. // reset
  15079. this.index = null;
  15080. this.attributes = {};
  15081. this.morphAttributes = {};
  15082. this.groups = [];
  15083. this.boundingBox = null;
  15084. this.boundingSphere = null;
  15085. // used for storing cloned, shared data
  15086. const data = {};
  15087. // name
  15088. this.name = source.name;
  15089. // index
  15090. const index = source.index;
  15091. if ( index !== null ) {
  15092. this.setIndex( index.clone() );
  15093. }
  15094. // attributes
  15095. const attributes = source.attributes;
  15096. for ( const name in attributes ) {
  15097. const attribute = attributes[ name ];
  15098. this.setAttribute( name, attribute.clone( data ) );
  15099. }
  15100. // morph attributes
  15101. const morphAttributes = source.morphAttributes;
  15102. for ( const name in morphAttributes ) {
  15103. const array = [];
  15104. const morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  15105. for ( let i = 0, l = morphAttribute.length; i < l; i ++ ) {
  15106. array.push( morphAttribute[ i ].clone( data ) );
  15107. }
  15108. this.morphAttributes[ name ] = array;
  15109. }
  15110. this.morphTargetsRelative = source.morphTargetsRelative;
  15111. // groups
  15112. const groups = source.groups;
  15113. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  15114. const group = groups[ i ];
  15115. this.addGroup( group.start, group.count, group.materialIndex );
  15116. }
  15117. // bounding box
  15118. const boundingBox = source.boundingBox;
  15119. if ( boundingBox !== null ) {
  15120. this.boundingBox = boundingBox.clone();
  15121. }
  15122. // bounding sphere
  15123. const boundingSphere = source.boundingSphere;
  15124. if ( boundingSphere !== null ) {
  15125. this.boundingSphere = boundingSphere.clone();
  15126. }
  15127. // draw range
  15128. this.drawRange.start = source.drawRange.start;
  15129. this.drawRange.count = source.drawRange.count;
  15130. // user data
  15131. this.userData = source.userData;
  15132. return this;
  15133. }
  15134. /**
  15135. * Frees the GPU-related resources allocated by this instance. Call this
  15136. * method whenever this instance is no longer used in your app.
  15137. *
  15138. * @fires BufferGeometry#dispose
  15139. */
  15140. dispose() {
  15141. this.dispatchEvent( { type: 'dispose' } );
  15142. }
  15143. }
  15144. const _inverseMatrix$3 = /*@__PURE__*/ new Matrix4();
  15145. const _ray$3 = /*@__PURE__*/ new Ray();
  15146. const _sphere$6 = /*@__PURE__*/ new Sphere();
  15147. const _sphereHitAt = /*@__PURE__*/ new Vector3();
  15148. const _vA$1 = /*@__PURE__*/ new Vector3();
  15149. const _vB$1 = /*@__PURE__*/ new Vector3();
  15150. const _vC$1 = /*@__PURE__*/ new Vector3();
  15151. const _tempA = /*@__PURE__*/ new Vector3();
  15152. const _morphA = /*@__PURE__*/ new Vector3();
  15153. const _intersectionPoint = /*@__PURE__*/ new Vector3();
  15154. const _intersectionPointWorld = /*@__PURE__*/ new Vector3();
  15155. /**
  15156. * Class representing triangular polygon mesh based objects.
  15157. *
  15158. * ```js
  15159. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15160. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  15161. * const mesh = new THREE.Mesh( geometry, material );
  15162. * scene.add( mesh );
  15163. * ```
  15164. *
  15165. * @augments Object3D
  15166. */
  15167. class Mesh extends Object3D {
  15168. /**
  15169. * Constructs a new mesh.
  15170. *
  15171. * @param {BufferGeometry} [geometry] - The mesh geometry.
  15172. * @param {Material|Array<Material>} [material] - The mesh material.
  15173. */
  15174. constructor( geometry = new BufferGeometry(), material = new MeshBasicMaterial() ) {
  15175. super();
  15176. /**
  15177. * This flag can be used for type testing.
  15178. *
  15179. * @type {boolean}
  15180. * @readonly
  15181. * @default true
  15182. */
  15183. this.isMesh = true;
  15184. this.type = 'Mesh';
  15185. /**
  15186. * The mesh geometry.
  15187. *
  15188. * @type {BufferGeometry}
  15189. */
  15190. this.geometry = geometry;
  15191. /**
  15192. * The mesh material.
  15193. *
  15194. * @type {Material|Array<Material>}
  15195. * @default MeshBasicMaterial
  15196. */
  15197. this.material = material;
  15198. /**
  15199. * A dictionary representing the morph targets in the geometry. The key is the
  15200. * morph targets name, the value its attribute index. This member is `undefined`
  15201. * by default and only set when morph targets are detected in the geometry.
  15202. *
  15203. * @type {Object<String,number>|undefined}
  15204. * @default undefined
  15205. */
  15206. this.morphTargetDictionary = undefined;
  15207. /**
  15208. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  15209. * is applied. This member is `undefined` by default and only set when morph targets are
  15210. * detected in the geometry.
  15211. *
  15212. * @type {Array<number>|undefined}
  15213. * @default undefined
  15214. */
  15215. this.morphTargetInfluences = undefined;
  15216. /**
  15217. * The number of instances of this mesh.
  15218. * Can only be used with {@link WebGPURenderer}.
  15219. *
  15220. * @type {number}
  15221. * @default 1
  15222. */
  15223. this.count = 1;
  15224. this.updateMorphTargets();
  15225. }
  15226. copy( source, recursive ) {
  15227. super.copy( source, recursive );
  15228. if ( source.morphTargetInfluences !== undefined ) {
  15229. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  15230. }
  15231. if ( source.morphTargetDictionary !== undefined ) {
  15232. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  15233. }
  15234. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  15235. this.geometry = source.geometry;
  15236. return this;
  15237. }
  15238. /**
  15239. * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences}
  15240. * to make sure existing morph targets can influence this 3D object.
  15241. */
  15242. updateMorphTargets() {
  15243. const geometry = this.geometry;
  15244. const morphAttributes = geometry.morphAttributes;
  15245. const keys = Object.keys( morphAttributes );
  15246. if ( keys.length > 0 ) {
  15247. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  15248. if ( morphAttribute !== undefined ) {
  15249. this.morphTargetInfluences = [];
  15250. this.morphTargetDictionary = {};
  15251. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  15252. const name = morphAttribute[ m ].name || String( m );
  15253. this.morphTargetInfluences.push( 0 );
  15254. this.morphTargetDictionary[ name ] = m;
  15255. }
  15256. }
  15257. }
  15258. }
  15259. /**
  15260. * Returns the local-space position of the vertex at the given index, taking into
  15261. * account the current animation state of both morph targets and skinning.
  15262. *
  15263. * @param {number} index - The vertex index.
  15264. * @param {Vector3} target - The target object that is used to store the method's result.
  15265. * @return {Vector3} The vertex position in local space.
  15266. */
  15267. getVertexPosition( index, target ) {
  15268. const geometry = this.geometry;
  15269. const position = geometry.attributes.position;
  15270. const morphPosition = geometry.morphAttributes.position;
  15271. const morphTargetsRelative = geometry.morphTargetsRelative;
  15272. target.fromBufferAttribute( position, index );
  15273. const morphInfluences = this.morphTargetInfluences;
  15274. if ( morphPosition && morphInfluences ) {
  15275. _morphA.set( 0, 0, 0 );
  15276. for ( let i = 0, il = morphPosition.length; i < il; i ++ ) {
  15277. const influence = morphInfluences[ i ];
  15278. const morphAttribute = morphPosition[ i ];
  15279. if ( influence === 0 ) continue;
  15280. _tempA.fromBufferAttribute( morphAttribute, index );
  15281. if ( morphTargetsRelative ) {
  15282. _morphA.addScaledVector( _tempA, influence );
  15283. } else {
  15284. _morphA.addScaledVector( _tempA.sub( target ), influence );
  15285. }
  15286. }
  15287. target.add( _morphA );
  15288. }
  15289. return target;
  15290. }
  15291. /**
  15292. * Computes intersection points between a casted ray and this line.
  15293. *
  15294. * @param {Raycaster} raycaster - The raycaster.
  15295. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  15296. */
  15297. raycast( raycaster, intersects ) {
  15298. const geometry = this.geometry;
  15299. const material = this.material;
  15300. const matrixWorld = this.matrixWorld;
  15301. if ( material === undefined ) return;
  15302. // test with bounding sphere in world space
  15303. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  15304. _sphere$6.copy( geometry.boundingSphere );
  15305. _sphere$6.applyMatrix4( matrixWorld );
  15306. // check distance from ray origin to bounding sphere
  15307. _ray$3.copy( raycaster.ray ).recast( raycaster.near );
  15308. if ( _sphere$6.containsPoint( _ray$3.origin ) === false ) {
  15309. if ( _ray$3.intersectSphere( _sphere$6, _sphereHitAt ) === null ) return;
  15310. if ( _ray$3.origin.distanceToSquared( _sphereHitAt ) > ( raycaster.far - raycaster.near ) ** 2 ) return;
  15311. }
  15312. // convert ray to local space of mesh
  15313. _inverseMatrix$3.copy( matrixWorld ).invert();
  15314. _ray$3.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$3 );
  15315. // test with bounding box in local space
  15316. if ( geometry.boundingBox !== null ) {
  15317. if ( _ray$3.intersectsBox( geometry.boundingBox ) === false ) return;
  15318. }
  15319. // test for intersections with geometry
  15320. this._computeIntersections( raycaster, intersects, _ray$3 );
  15321. }
  15322. _computeIntersections( raycaster, intersects, rayLocalSpace ) {
  15323. let intersection;
  15324. const geometry = this.geometry;
  15325. const material = this.material;
  15326. const index = geometry.index;
  15327. const position = geometry.attributes.position;
  15328. const uv = geometry.attributes.uv;
  15329. const uv1 = geometry.attributes.uv1;
  15330. const normal = geometry.attributes.normal;
  15331. const groups = geometry.groups;
  15332. const drawRange = geometry.drawRange;
  15333. if ( index !== null ) {
  15334. // indexed buffer geometry
  15335. if ( Array.isArray( material ) ) {
  15336. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15337. const group = groups[ i ];
  15338. const groupMaterial = material[ group.materialIndex ];
  15339. const start = Math.max( group.start, drawRange.start );
  15340. const end = Math.min( index.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15341. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15342. const a = index.getX( j );
  15343. const b = index.getX( j + 1 );
  15344. const c = index.getX( j + 2 );
  15345. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15346. if ( intersection ) {
  15347. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in indexed buffer semantics
  15348. intersection.face.materialIndex = group.materialIndex;
  15349. intersects.push( intersection );
  15350. }
  15351. }
  15352. }
  15353. } else {
  15354. const start = Math.max( 0, drawRange.start );
  15355. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  15356. for ( let i = start, il = end; i < il; i += 3 ) {
  15357. const a = index.getX( i );
  15358. const b = index.getX( i + 1 );
  15359. const c = index.getX( i + 2 );
  15360. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15361. if ( intersection ) {
  15362. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indexed buffer semantics
  15363. intersects.push( intersection );
  15364. }
  15365. }
  15366. }
  15367. } else if ( position !== undefined ) {
  15368. // non-indexed buffer geometry
  15369. if ( Array.isArray( material ) ) {
  15370. for ( let i = 0, il = groups.length; i < il; i ++ ) {
  15371. const group = groups[ i ];
  15372. const groupMaterial = material[ group.materialIndex ];
  15373. const start = Math.max( group.start, drawRange.start );
  15374. const end = Math.min( position.count, Math.min( ( group.start + group.count ), ( drawRange.start + drawRange.count ) ) );
  15375. for ( let j = start, jl = end; j < jl; j += 3 ) {
  15376. const a = j;
  15377. const b = j + 1;
  15378. const c = j + 2;
  15379. intersection = checkGeometryIntersection( this, groupMaterial, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15380. if ( intersection ) {
  15381. intersection.faceIndex = Math.floor( j / 3 ); // triangle number in non-indexed buffer semantics
  15382. intersection.face.materialIndex = group.materialIndex;
  15383. intersects.push( intersection );
  15384. }
  15385. }
  15386. }
  15387. } else {
  15388. const start = Math.max( 0, drawRange.start );
  15389. const end = Math.min( position.count, ( drawRange.start + drawRange.count ) );
  15390. for ( let i = start, il = end; i < il; i += 3 ) {
  15391. const a = i;
  15392. const b = i + 1;
  15393. const c = i + 2;
  15394. intersection = checkGeometryIntersection( this, material, raycaster, rayLocalSpace, uv, uv1, normal, a, b, c );
  15395. if ( intersection ) {
  15396. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in non-indexed buffer semantics
  15397. intersects.push( intersection );
  15398. }
  15399. }
  15400. }
  15401. }
  15402. }
  15403. }
  15404. function checkIntersection$1( object, material, raycaster, ray, pA, pB, pC, point ) {
  15405. let intersect;
  15406. if ( material.side === BackSide ) {
  15407. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  15408. } else {
  15409. intersect = ray.intersectTriangle( pA, pB, pC, ( material.side === FrontSide ), point );
  15410. }
  15411. if ( intersect === null ) return null;
  15412. _intersectionPointWorld.copy( point );
  15413. _intersectionPointWorld.applyMatrix4( object.matrixWorld );
  15414. const distance = raycaster.ray.origin.distanceTo( _intersectionPointWorld );
  15415. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  15416. return {
  15417. distance: distance,
  15418. point: _intersectionPointWorld.clone(),
  15419. object: object
  15420. };
  15421. }
  15422. function checkGeometryIntersection( object, material, raycaster, ray, uv, uv1, normal, a, b, c ) {
  15423. object.getVertexPosition( a, _vA$1 );
  15424. object.getVertexPosition( b, _vB$1 );
  15425. object.getVertexPosition( c, _vC$1 );
  15426. const intersection = checkIntersection$1( object, material, raycaster, ray, _vA$1, _vB$1, _vC$1, _intersectionPoint );
  15427. if ( intersection ) {
  15428. const barycoord = new Vector3();
  15429. Triangle.getBarycoord( _intersectionPoint, _vA$1, _vB$1, _vC$1, barycoord );
  15430. if ( uv ) {
  15431. intersection.uv = Triangle.getInterpolatedAttribute( uv, a, b, c, barycoord, new Vector2() );
  15432. }
  15433. if ( uv1 ) {
  15434. intersection.uv1 = Triangle.getInterpolatedAttribute( uv1, a, b, c, barycoord, new Vector2() );
  15435. }
  15436. if ( normal ) {
  15437. intersection.normal = Triangle.getInterpolatedAttribute( normal, a, b, c, barycoord, new Vector3() );
  15438. if ( intersection.normal.dot( ray.direction ) > 0 ) {
  15439. intersection.normal.multiplyScalar( -1 );
  15440. }
  15441. }
  15442. const face = {
  15443. a: a,
  15444. b: b,
  15445. c: c,
  15446. normal: new Vector3(),
  15447. materialIndex: 0
  15448. };
  15449. Triangle.getNormal( _vA$1, _vB$1, _vC$1, face.normal );
  15450. intersection.face = face;
  15451. intersection.barycoord = barycoord;
  15452. }
  15453. return intersection;
  15454. }
  15455. /**
  15456. * A geometry class for a rectangular cuboid with a given width, height, and depth.
  15457. * On creation, the cuboid is centred on the origin, with each edge parallel to one
  15458. * of the axes.
  15459. *
  15460. * ```js
  15461. * const geometry = new THREE.BoxGeometry( 1, 1, 1 );
  15462. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  15463. * const cube = new THREE.Mesh( geometry, material );
  15464. * scene.add( cube );
  15465. * ```
  15466. *
  15467. * @augments BufferGeometry
  15468. * @demo scenes/geometry-browser.html#BoxGeometry
  15469. */
  15470. class BoxGeometry extends BufferGeometry {
  15471. /**
  15472. * Constructs a new box geometry.
  15473. *
  15474. * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis.
  15475. * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis.
  15476. * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis.
  15477. * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides.
  15478. * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides.
  15479. * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides.
  15480. */
  15481. constructor( width = 1, height = 1, depth = 1, widthSegments = 1, heightSegments = 1, depthSegments = 1 ) {
  15482. super();
  15483. this.type = 'BoxGeometry';
  15484. /**
  15485. * Holds the constructor parameters that have been
  15486. * used to generate the geometry. Any modification
  15487. * after instantiation does not change the geometry.
  15488. *
  15489. * @type {Object}
  15490. */
  15491. this.parameters = {
  15492. width: width,
  15493. height: height,
  15494. depth: depth,
  15495. widthSegments: widthSegments,
  15496. heightSegments: heightSegments,
  15497. depthSegments: depthSegments
  15498. };
  15499. const scope = this;
  15500. // segments
  15501. widthSegments = Math.floor( widthSegments );
  15502. heightSegments = Math.floor( heightSegments );
  15503. depthSegments = Math.floor( depthSegments );
  15504. // buffers
  15505. const indices = [];
  15506. const vertices = [];
  15507. const normals = [];
  15508. const uvs = [];
  15509. // helper variables
  15510. let numberOfVertices = 0;
  15511. let groupStart = 0;
  15512. // build each side of the box geometry
  15513. buildPlane( 'z', 'y', 'x', -1, -1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  15514. buildPlane( 'z', 'y', 'x', 1, -1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  15515. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  15516. buildPlane( 'x', 'z', 'y', 1, -1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  15517. buildPlane( 'x', 'y', 'z', 1, -1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  15518. buildPlane( 'x', 'y', 'z', -1, -1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  15519. // build geometry
  15520. this.setIndex( indices );
  15521. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  15522. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  15523. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  15524. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  15525. const segmentWidth = width / gridX;
  15526. const segmentHeight = height / gridY;
  15527. const widthHalf = width / 2;
  15528. const heightHalf = height / 2;
  15529. const depthHalf = depth / 2;
  15530. const gridX1 = gridX + 1;
  15531. const gridY1 = gridY + 1;
  15532. let vertexCounter = 0;
  15533. let groupCount = 0;
  15534. const vector = new Vector3();
  15535. // generate vertices, normals and uvs
  15536. for ( let iy = 0; iy < gridY1; iy ++ ) {
  15537. const y = iy * segmentHeight - heightHalf;
  15538. for ( let ix = 0; ix < gridX1; ix ++ ) {
  15539. const x = ix * segmentWidth - widthHalf;
  15540. // set values to correct vector component
  15541. vector[ u ] = x * udir;
  15542. vector[ v ] = y * vdir;
  15543. vector[ w ] = depthHalf;
  15544. // now apply vector to vertex buffer
  15545. vertices.push( vector.x, vector.y, vector.z );
  15546. // set values to correct vector component
  15547. vector[ u ] = 0;
  15548. vector[ v ] = 0;
  15549. vector[ w ] = depth > 0 ? 1 : -1;
  15550. // now apply vector to normal buffer
  15551. normals.push( vector.x, vector.y, vector.z );
  15552. // uvs
  15553. uvs.push( ix / gridX );
  15554. uvs.push( 1 - ( iy / gridY ) );
  15555. // counters
  15556. vertexCounter += 1;
  15557. }
  15558. }
  15559. // indices
  15560. // 1. you need three indices to draw a single face
  15561. // 2. a single segment consists of two faces
  15562. // 3. so we need to generate six (2*3) indices per segment
  15563. for ( let iy = 0; iy < gridY; iy ++ ) {
  15564. for ( let ix = 0; ix < gridX; ix ++ ) {
  15565. const a = numberOfVertices + ix + gridX1 * iy;
  15566. const b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  15567. const c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  15568. const d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  15569. // faces
  15570. indices.push( a, b, d );
  15571. indices.push( b, c, d );
  15572. // increase counter
  15573. groupCount += 6;
  15574. }
  15575. }
  15576. // add a group to the geometry. this will ensure multi material support
  15577. scope.addGroup( groupStart, groupCount, materialIndex );
  15578. // calculate new start value for groups
  15579. groupStart += groupCount;
  15580. // update total number of vertices
  15581. numberOfVertices += vertexCounter;
  15582. }
  15583. }
  15584. copy( source ) {
  15585. super.copy( source );
  15586. this.parameters = Object.assign( {}, source.parameters );
  15587. return this;
  15588. }
  15589. /**
  15590. * Factory method for creating an instance of this class from the given
  15591. * JSON object.
  15592. *
  15593. * @param {Object} data - A JSON object representing the serialized geometry.
  15594. * @return {BoxGeometry} A new instance.
  15595. */
  15596. static fromJSON( data ) {
  15597. return new BoxGeometry( data.width, data.height, data.depth, data.widthSegments, data.heightSegments, data.depthSegments );
  15598. }
  15599. }
  15600. /**
  15601. * Provides utility functions for managing uniforms.
  15602. *
  15603. * @module UniformsUtils
  15604. */
  15605. /**
  15606. * Clones the given uniform definitions by performing a deep-copy. That means
  15607. * if the value of a uniform refers to an object like a Vector3 or Texture,
  15608. * the cloned uniform will refer to a new object reference.
  15609. *
  15610. * @param {Object} src - An object representing uniform definitions.
  15611. * @return {Object} The cloned uniforms.
  15612. */
  15613. function cloneUniforms( src ) {
  15614. const dst = {};
  15615. for ( const u in src ) {
  15616. dst[ u ] = {};
  15617. for ( const p in src[ u ] ) {
  15618. const property = src[ u ][ p ];
  15619. if ( property && ( property.isColor ||
  15620. property.isMatrix3 || property.isMatrix4 ||
  15621. property.isVector2 || property.isVector3 || property.isVector4 ||
  15622. property.isTexture || property.isQuaternion ) ) {
  15623. if ( property.isRenderTargetTexture ) {
  15624. warn( 'UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms().' );
  15625. dst[ u ][ p ] = null;
  15626. } else {
  15627. dst[ u ][ p ] = property.clone();
  15628. }
  15629. } else if ( Array.isArray( property ) ) {
  15630. dst[ u ][ p ] = property.slice();
  15631. } else {
  15632. dst[ u ][ p ] = property;
  15633. }
  15634. }
  15635. }
  15636. return dst;
  15637. }
  15638. /**
  15639. * Merges the given uniform definitions into a single object. Since the
  15640. * method internally uses cloneUniforms(), it performs a deep-copy when
  15641. * producing the merged uniform definitions.
  15642. *
  15643. * @param {Array} uniforms - An array of objects containing uniform definitions.
  15644. * @return {Object} The merged uniforms.
  15645. */
  15646. function mergeUniforms( uniforms ) {
  15647. const merged = {};
  15648. for ( let u = 0; u < uniforms.length; u ++ ) {
  15649. const tmp = cloneUniforms( uniforms[ u ] );
  15650. for ( const p in tmp ) {
  15651. merged[ p ] = tmp[ p ];
  15652. }
  15653. }
  15654. return merged;
  15655. }
  15656. function cloneUniformsGroups( src ) {
  15657. const dst = [];
  15658. for ( let u = 0; u < src.length; u ++ ) {
  15659. dst.push( src[ u ].clone() );
  15660. }
  15661. return dst;
  15662. }
  15663. function getUnlitUniformColorSpace( renderer ) {
  15664. const currentRenderTarget = renderer.getRenderTarget();
  15665. if ( currentRenderTarget === null ) {
  15666. // https://github.com/mrdoob/three.js/pull/23937#issuecomment-1111067398
  15667. return renderer.outputColorSpace;
  15668. }
  15669. // https://github.com/mrdoob/three.js/issues/27868
  15670. if ( currentRenderTarget.isXRRenderTarget === true ) {
  15671. return currentRenderTarget.texture.colorSpace;
  15672. }
  15673. return ColorManagement.workingColorSpace;
  15674. }
  15675. // Legacy
  15676. const UniformsUtils = { clone: cloneUniforms, merge: mergeUniforms };
  15677. var default_vertex = "void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}";
  15678. var default_fragment = "void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}";
  15679. /**
  15680. * A material rendered with custom shaders. A shader is a small program written in GLSL.
  15681. * that runs on the GPU. You may want to use a custom shader if you need to implement an
  15682. * effect not included with any of the built-in materials.
  15683. *
  15684. * There are the following notes to bear in mind when using a `ShaderMaterial`:
  15685. *
  15686. * - `ShaderMaterial` can only be used with {@link WebGLRenderer}.
  15687. * - Built in attributes and uniforms are passed to the shaders along with your code. If
  15688. * you don't want that, use {@link RawShaderMaterial} instead.
  15689. * - You can use the directive `#pragma unroll_loop_start` and `#pragma unroll_loop_end`
  15690. * in order to unroll a `for` loop in GLSL by the shader preprocessor. The directive has
  15691. * to be placed right above the loop. The loop formatting has to correspond to a defined standard.
  15692. * - The loop has to be [normalized](https://en.wikipedia.org/wiki/Normalized_loop).
  15693. * - The loop variable has to be *i*.
  15694. * - The value `UNROLLED_LOOP_INDEX` will be replaced with the explicitly
  15695. * value of *i* for the given iteration and can be used in preprocessor
  15696. * statements.
  15697. *
  15698. * ```js
  15699. * const material = new THREE.ShaderMaterial( {
  15700. * uniforms: {
  15701. * time: { value: 1.0 },
  15702. * resolution: { value: new THREE.Vector2() }
  15703. * },
  15704. * vertexShader: document.getElementById( 'vertexShader' ).textContent,
  15705. * fragmentShader: document.getElementById( 'fragmentShader' ).textContent
  15706. * } );
  15707. * ```
  15708. *
  15709. * @augments Material
  15710. */
  15711. class ShaderMaterial extends Material {
  15712. /**
  15713. * Constructs a new shader material.
  15714. *
  15715. * @param {Object} [parameters] - An object with one or more properties
  15716. * defining the material's appearance. Any property of the material
  15717. * (including any property from inherited materials) can be passed
  15718. * in here. Color values can be passed any type of value accepted
  15719. * by {@link Color#set}.
  15720. */
  15721. constructor( parameters ) {
  15722. super();
  15723. /**
  15724. * This flag can be used for type testing.
  15725. *
  15726. * @type {boolean}
  15727. * @readonly
  15728. * @default true
  15729. */
  15730. this.isShaderMaterial = true;
  15731. this.type = 'ShaderMaterial';
  15732. /**
  15733. * Defines custom constants using `#define` directives within the GLSL code
  15734. * for both the vertex shader and the fragment shader; each key/value pair
  15735. * yields another directive.
  15736. * ```js
  15737. * defines: {
  15738. * FOO: 15,
  15739. * BAR: true
  15740. * }
  15741. * ```
  15742. * Yields the lines:
  15743. * ```
  15744. * #define FOO 15
  15745. * #define BAR true
  15746. * ```
  15747. *
  15748. * @type {Object}
  15749. */
  15750. this.defines = {};
  15751. /**
  15752. * An object of the form:
  15753. * ```js
  15754. * {
  15755. * "uniform1": { value: 1.0 },
  15756. * "uniform2": { value: 2 }
  15757. * }
  15758. * ```
  15759. * specifying the uniforms to be passed to the shader code; keys are uniform
  15760. * names, values are definitions of the form
  15761. * ```
  15762. * {
  15763. * value: 1.0
  15764. * }
  15765. * ```
  15766. * where `value` is the value of the uniform. Names must match the name of
  15767. * the uniform, as defined in the GLSL code. Note that uniforms are refreshed
  15768. * on every frame, so updating the value of the uniform will immediately
  15769. * update the value available to the GLSL code.
  15770. *
  15771. * @type {Object}
  15772. */
  15773. this.uniforms = {};
  15774. /**
  15775. * An array holding uniforms groups for configuring UBOs.
  15776. *
  15777. * @type {Array<UniformsGroup>}
  15778. */
  15779. this.uniformsGroups = [];
  15780. /**
  15781. * Vertex shader GLSL code. This is the actual code for the shader.
  15782. *
  15783. * @type {string}
  15784. */
  15785. this.vertexShader = default_vertex;
  15786. /**
  15787. * Fragment shader GLSL code. This is the actual code for the shader.
  15788. *
  15789. * @type {string}
  15790. */
  15791. this.fragmentShader = default_fragment;
  15792. /**
  15793. * Controls line thickness or lines.
  15794. *
  15795. * WebGL and WebGPU ignore this setting and always render line primitives with a
  15796. * width of one pixel.
  15797. *
  15798. * @type {number}
  15799. * @default 1
  15800. */
  15801. this.linewidth = 1;
  15802. /**
  15803. * Renders the geometry as a wireframe.
  15804. *
  15805. * @type {boolean}
  15806. * @default false
  15807. */
  15808. this.wireframe = false;
  15809. /**
  15810. * Controls the thickness of the wireframe.
  15811. *
  15812. * WebGL and WebGPU ignore this property and always render
  15813. * 1 pixel wide lines.
  15814. *
  15815. * @type {number}
  15816. * @default 1
  15817. */
  15818. this.wireframeLinewidth = 1;
  15819. /**
  15820. * Defines whether the material color is affected by global fog settings; `true`
  15821. * to pass fog uniforms to the shader.
  15822. *
  15823. * Setting this property to `true` requires the definition of fog uniforms. It is
  15824. * recommended to use `UniformsUtils.merge()` to combine the custom shader uniforms
  15825. * with predefined fog uniforms.
  15826. *
  15827. * ```js
  15828. * const material = new ShaderMaterial( {
  15829. * uniforms: UniformsUtils.merge( [ UniformsLib[ 'fog' ], shaderUniforms ] );
  15830. * vertexShader: vertexShader,
  15831. * fragmentShader: fragmentShader,
  15832. * fog: true
  15833. * } );
  15834. * ```
  15835. *
  15836. * @type {boolean}
  15837. * @default false
  15838. */
  15839. this.fog = false;
  15840. /**
  15841. * Defines whether this material uses lighting; `true` to pass uniform data
  15842. * related to lighting to this shader.
  15843. *
  15844. * @type {boolean}
  15845. * @default false
  15846. */
  15847. this.lights = false;
  15848. /**
  15849. * Defines whether this material supports clipping; `true` to let the renderer
  15850. * pass the clippingPlanes uniform.
  15851. *
  15852. * @type {boolean}
  15853. * @default false
  15854. */
  15855. this.clipping = false;
  15856. /**
  15857. * Overwritten and set to `true` by default.
  15858. *
  15859. * @type {boolean}
  15860. * @default true
  15861. */
  15862. this.forceSinglePass = true;
  15863. /**
  15864. * This object allows to enable certain WebGL 2 extensions.
  15865. *
  15866. * - clipCullDistance: set to `true` to use vertex shader clipping
  15867. * - multiDraw: set to `true` to use vertex shader multi_draw / enable gl_DrawID
  15868. *
  15869. * @type {{clipCullDistance:false,multiDraw:false}}
  15870. */
  15871. this.extensions = {
  15872. clipCullDistance: false, // set to use vertex shader clipping
  15873. multiDraw: false // set to use vertex shader multi_draw / enable gl_DrawID
  15874. };
  15875. /**
  15876. * When the rendered geometry doesn't include these attributes but the
  15877. * material does, these default values will be passed to the shaders. This
  15878. * avoids errors when buffer data is missing.
  15879. *
  15880. * - color: [ 1, 1, 1 ]
  15881. * - uv: [ 0, 0 ]
  15882. * - uv1: [ 0, 0 ]
  15883. *
  15884. * @type {Object}
  15885. */
  15886. this.defaultAttributeValues = {
  15887. 'color': [ 1, 1, 1 ],
  15888. 'uv': [ 0, 0 ],
  15889. 'uv1': [ 0, 0 ]
  15890. };
  15891. /**
  15892. * If set, this calls [gl.bindAttribLocation](https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/bindAttribLocation)
  15893. * to bind a generic vertex index to an attribute variable.
  15894. *
  15895. * @type {string|undefined}
  15896. * @default undefined
  15897. */
  15898. this.index0AttributeName = undefined;
  15899. /**
  15900. * Can be used to force a uniform update while changing uniforms in
  15901. * {@link Object3D#onBeforeRender}.
  15902. *
  15903. * @type {boolean}
  15904. * @default false
  15905. */
  15906. this.uniformsNeedUpdate = false;
  15907. /**
  15908. * Defines the GLSL version of custom shader code.
  15909. *
  15910. * @type {?(GLSL1|GLSL3)}
  15911. * @default null
  15912. */
  15913. this.glslVersion = null;
  15914. if ( parameters !== undefined ) {
  15915. this.setValues( parameters );
  15916. }
  15917. }
  15918. copy( source ) {
  15919. super.copy( source );
  15920. this.fragmentShader = source.fragmentShader;
  15921. this.vertexShader = source.vertexShader;
  15922. this.uniforms = cloneUniforms( source.uniforms );
  15923. this.uniformsGroups = cloneUniformsGroups( source.uniformsGroups );
  15924. this.defines = Object.assign( {}, source.defines );
  15925. this.wireframe = source.wireframe;
  15926. this.wireframeLinewidth = source.wireframeLinewidth;
  15927. this.fog = source.fog;
  15928. this.lights = source.lights;
  15929. this.clipping = source.clipping;
  15930. this.extensions = Object.assign( {}, source.extensions );
  15931. this.glslVersion = source.glslVersion;
  15932. this.defaultAttributeValues = Object.assign( {}, source.defaultAttributeValues );
  15933. this.index0AttributeName = source.index0AttributeName;
  15934. this.uniformsNeedUpdate = source.uniformsNeedUpdate;
  15935. return this;
  15936. }
  15937. toJSON( meta ) {
  15938. const data = super.toJSON( meta );
  15939. data.glslVersion = this.glslVersion;
  15940. data.uniforms = {};
  15941. for ( const name in this.uniforms ) {
  15942. const uniform = this.uniforms[ name ];
  15943. const value = uniform.value;
  15944. if ( value && value.isTexture ) {
  15945. data.uniforms[ name ] = {
  15946. type: 't',
  15947. value: value.toJSON( meta ).uuid
  15948. };
  15949. } else if ( value && value.isColor ) {
  15950. data.uniforms[ name ] = {
  15951. type: 'c',
  15952. value: value.getHex()
  15953. };
  15954. } else if ( value && value.isVector2 ) {
  15955. data.uniforms[ name ] = {
  15956. type: 'v2',
  15957. value: value.toArray()
  15958. };
  15959. } else if ( value && value.isVector3 ) {
  15960. data.uniforms[ name ] = {
  15961. type: 'v3',
  15962. value: value.toArray()
  15963. };
  15964. } else if ( value && value.isVector4 ) {
  15965. data.uniforms[ name ] = {
  15966. type: 'v4',
  15967. value: value.toArray()
  15968. };
  15969. } else if ( value && value.isMatrix3 ) {
  15970. data.uniforms[ name ] = {
  15971. type: 'm3',
  15972. value: value.toArray()
  15973. };
  15974. } else if ( value && value.isMatrix4 ) {
  15975. data.uniforms[ name ] = {
  15976. type: 'm4',
  15977. value: value.toArray()
  15978. };
  15979. } else {
  15980. data.uniforms[ name ] = {
  15981. value: value
  15982. };
  15983. // note: the array variants v2v, v3v, v4v, m4v and tv are not supported so far
  15984. }
  15985. }
  15986. if ( Object.keys( this.defines ).length > 0 ) data.defines = this.defines;
  15987. data.vertexShader = this.vertexShader;
  15988. data.fragmentShader = this.fragmentShader;
  15989. data.lights = this.lights;
  15990. data.clipping = this.clipping;
  15991. const extensions = {};
  15992. for ( const key in this.extensions ) {
  15993. if ( this.extensions[ key ] === true ) extensions[ key ] = true;
  15994. }
  15995. if ( Object.keys( extensions ).length > 0 ) data.extensions = extensions;
  15996. return data;
  15997. }
  15998. }
  15999. /**
  16000. * Abstract base class for cameras. This class should always be inherited
  16001. * when you build a new camera.
  16002. *
  16003. * @abstract
  16004. * @augments Object3D
  16005. */
  16006. class Camera extends Object3D {
  16007. /**
  16008. * Constructs a new camera.
  16009. */
  16010. constructor() {
  16011. super();
  16012. /**
  16013. * This flag can be used for type testing.
  16014. *
  16015. * @type {boolean}
  16016. * @readonly
  16017. * @default true
  16018. */
  16019. this.isCamera = true;
  16020. this.type = 'Camera';
  16021. /**
  16022. * The inverse of the camera's world matrix.
  16023. *
  16024. * @type {Matrix4}
  16025. */
  16026. this.matrixWorldInverse = new Matrix4();
  16027. /**
  16028. * The camera's projection matrix.
  16029. *
  16030. * @type {Matrix4}
  16031. */
  16032. this.projectionMatrix = new Matrix4();
  16033. /**
  16034. * The inverse of the camera's projection matrix.
  16035. *
  16036. * @type {Matrix4}
  16037. */
  16038. this.projectionMatrixInverse = new Matrix4();
  16039. /**
  16040. * The coordinate system in which the camera is used.
  16041. *
  16042. * @type {(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16043. */
  16044. this.coordinateSystem = WebGLCoordinateSystem;
  16045. this._reversedDepth = false;
  16046. }
  16047. /**
  16048. * The flag that indicates whether the camera uses a reversed depth buffer.
  16049. *
  16050. * @type {boolean}
  16051. * @default false
  16052. */
  16053. get reversedDepth() {
  16054. return this._reversedDepth;
  16055. }
  16056. copy( source, recursive ) {
  16057. super.copy( source, recursive );
  16058. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  16059. this.projectionMatrix.copy( source.projectionMatrix );
  16060. this.projectionMatrixInverse.copy( source.projectionMatrixInverse );
  16061. this.coordinateSystem = source.coordinateSystem;
  16062. return this;
  16063. }
  16064. /**
  16065. * Returns a vector representing the ("look") direction of the 3D object in world space.
  16066. *
  16067. * This method is overwritten since cameras have a different forward vector compared to other
  16068. * 3D objects. A camera looks down its local, negative z-axis by default.
  16069. *
  16070. * @param {Vector3} target - The target vector the result is stored to.
  16071. * @return {Vector3} The 3D object's direction in world space.
  16072. */
  16073. getWorldDirection( target ) {
  16074. return super.getWorldDirection( target ).negate();
  16075. }
  16076. updateMatrixWorld( force ) {
  16077. super.updateMatrixWorld( force );
  16078. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16079. }
  16080. updateWorldMatrix( updateParents, updateChildren ) {
  16081. super.updateWorldMatrix( updateParents, updateChildren );
  16082. this.matrixWorldInverse.copy( this.matrixWorld ).invert();
  16083. }
  16084. clone() {
  16085. return new this.constructor().copy( this );
  16086. }
  16087. }
  16088. const _v3$1 = /*@__PURE__*/ new Vector3();
  16089. const _minTarget = /*@__PURE__*/ new Vector2();
  16090. const _maxTarget = /*@__PURE__*/ new Vector2();
  16091. /**
  16092. * Camera that uses [perspective projection](https://en.wikipedia.org/wiki/Perspective_(graphical)).
  16093. *
  16094. * This projection mode is designed to mimic the way the human eye sees. It
  16095. * is the most common projection mode used for rendering a 3D scene.
  16096. *
  16097. * ```js
  16098. * const camera = new THREE.PerspectiveCamera( 45, width / height, 1, 1000 );
  16099. * scene.add( camera );
  16100. * ```
  16101. *
  16102. * @augments Camera
  16103. */
  16104. class PerspectiveCamera extends Camera {
  16105. /**
  16106. * Constructs a new perspective camera.
  16107. *
  16108. * @param {number} [fov=50] - The vertical field of view.
  16109. * @param {number} [aspect=1] - The aspect ratio.
  16110. * @param {number} [near=0.1] - The camera's near plane.
  16111. * @param {number} [far=2000] - The camera's far plane.
  16112. */
  16113. constructor( fov = 50, aspect = 1, near = 0.1, far = 2000 ) {
  16114. super();
  16115. /**
  16116. * This flag can be used for type testing.
  16117. *
  16118. * @type {boolean}
  16119. * @readonly
  16120. * @default true
  16121. */
  16122. this.isPerspectiveCamera = true;
  16123. this.type = 'PerspectiveCamera';
  16124. /**
  16125. * The vertical field of view, from bottom to top of view,
  16126. * in degrees.
  16127. *
  16128. * @type {number}
  16129. * @default 50
  16130. */
  16131. this.fov = fov;
  16132. /**
  16133. * The zoom factor of the camera.
  16134. *
  16135. * @type {number}
  16136. * @default 1
  16137. */
  16138. this.zoom = 1;
  16139. /**
  16140. * The camera's near plane. The valid range is greater than `0`
  16141. * and less than the current value of {@link PerspectiveCamera#far}.
  16142. *
  16143. * Note that, unlike for the {@link OrthographicCamera}, `0` is <em>not</em> a
  16144. * valid value for a perspective camera's near plane.
  16145. *
  16146. * @type {number}
  16147. * @default 0.1
  16148. */
  16149. this.near = near;
  16150. /**
  16151. * The camera's far plane. Must be greater than the
  16152. * current value of {@link PerspectiveCamera#near}.
  16153. *
  16154. * @type {number}
  16155. * @default 2000
  16156. */
  16157. this.far = far;
  16158. /**
  16159. * Object distance used for stereoscopy and depth-of-field effects. This
  16160. * parameter does not influence the projection matrix unless a
  16161. * {@link StereoCamera} is being used.
  16162. *
  16163. * @type {number}
  16164. * @default 10
  16165. */
  16166. this.focus = 10;
  16167. /**
  16168. * The aspect ratio, usually the canvas width / canvas height.
  16169. *
  16170. * @type {number}
  16171. * @default 1
  16172. */
  16173. this.aspect = aspect;
  16174. /**
  16175. * Represents the frustum window specification. This property should not be edited
  16176. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  16177. *
  16178. * @type {?Object}
  16179. * @default null
  16180. */
  16181. this.view = null;
  16182. /**
  16183. * Film size used for the larger axis. Default is `35` (millimeters). This
  16184. * parameter does not influence the projection matrix unless {@link PerspectiveCamera#filmOffset}
  16185. * is set to a nonzero value.
  16186. *
  16187. * @type {number}
  16188. * @default 35
  16189. */
  16190. this.filmGauge = 35;
  16191. /**
  16192. * Horizontal off-center offset in the same unit as {@link PerspectiveCamera#filmGauge}.
  16193. *
  16194. * @type {number}
  16195. * @default 0
  16196. */
  16197. this.filmOffset = 0;
  16198. this.updateProjectionMatrix();
  16199. }
  16200. copy( source, recursive ) {
  16201. super.copy( source, recursive );
  16202. this.fov = source.fov;
  16203. this.zoom = source.zoom;
  16204. this.near = source.near;
  16205. this.far = source.far;
  16206. this.focus = source.focus;
  16207. this.aspect = source.aspect;
  16208. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16209. this.filmGauge = source.filmGauge;
  16210. this.filmOffset = source.filmOffset;
  16211. return this;
  16212. }
  16213. /**
  16214. * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}.
  16215. *
  16216. * The default film gauge is 35, so that the focal length can be specified for
  16217. * a 35mm (full frame) camera.
  16218. *
  16219. * @param {number} focalLength - Values for focal length and film gauge must have the same unit.
  16220. */
  16221. setFocalLength( focalLength ) {
  16222. /** see {@link http://www.bobatkins.com/photography/technical/field_of_view.html} */
  16223. const vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16224. this.fov = RAD2DEG * 2 * Math.atan( vExtentSlope );
  16225. this.updateProjectionMatrix();
  16226. }
  16227. /**
  16228. * Returns the focal length from the current {@link PerspectiveCamera#fov} and
  16229. * {@link PerspectiveCamera#filmGauge}.
  16230. *
  16231. * @return {number} The computed focal length.
  16232. */
  16233. getFocalLength() {
  16234. const vExtentSlope = Math.tan( DEG2RAD * 0.5 * this.fov );
  16235. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16236. }
  16237. /**
  16238. * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}.
  16239. *
  16240. * @return {number} The effective FOV.
  16241. */
  16242. getEffectiveFOV() {
  16243. return RAD2DEG * 2 * Math.atan(
  16244. Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16245. }
  16246. /**
  16247. * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16248. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16249. *
  16250. * @return {number} The film width.
  16251. */
  16252. getFilmWidth() {
  16253. // film not completely covered in portrait format (aspect < 1)
  16254. return this.filmGauge * Math.min( this.aspect, 1 );
  16255. }
  16256. /**
  16257. * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or
  16258. * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}.
  16259. *
  16260. * @return {number} The film width.
  16261. */
  16262. getFilmHeight() {
  16263. // film not completely covered in landscape format (aspect > 1)
  16264. return this.filmGauge / Math.max( this.aspect, 1 );
  16265. }
  16266. /**
  16267. * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction.
  16268. * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle.
  16269. *
  16270. * @param {number} distance - The viewing distance.
  16271. * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector.
  16272. * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector.
  16273. */
  16274. getViewBounds( distance, minTarget, maxTarget ) {
  16275. _v3$1.set( -1, -1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16276. minTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16277. _v3$1.set( 1, 1, 0.5 ).applyMatrix4( this.projectionMatrixInverse );
  16278. maxTarget.set( _v3$1.x, _v3$1.y ).multiplyScalar( - distance / _v3$1.z );
  16279. }
  16280. /**
  16281. * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction.
  16282. *
  16283. * @param {number} distance - The viewing distance.
  16284. * @param {Vector2} target - The target vector that is used to store result where x is width and y is height.
  16285. * @returns {Vector2} The view size.
  16286. */
  16287. getViewSize( distance, target ) {
  16288. this.getViewBounds( distance, _minTarget, _maxTarget );
  16289. return target.subVectors( _maxTarget, _minTarget );
  16290. }
  16291. /**
  16292. * Sets an offset in a larger frustum. This is useful for multi-window or
  16293. * multi-monitor/multi-machine setups.
  16294. *
  16295. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16296. * the monitors are in grid like this
  16297. *```
  16298. * +---+---+---+
  16299. * | A | B | C |
  16300. * +---+---+---+
  16301. * | D | E | F |
  16302. * +---+---+---+
  16303. *```
  16304. * then for each monitor you would call it like this:
  16305. *```js
  16306. * const w = 1920;
  16307. * const h = 1080;
  16308. * const fullWidth = w * 3;
  16309. * const fullHeight = h * 2;
  16310. *
  16311. * // --A--
  16312. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16313. * // --B--
  16314. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16315. * // --C--
  16316. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16317. * // --D--
  16318. * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16319. * // --E--
  16320. * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16321. * // --F--
  16322. * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16323. * ```
  16324. *
  16325. * Note there is no reason monitors have to be the same size or in a grid.
  16326. *
  16327. * @param {number} fullWidth - The full width of multiview setup.
  16328. * @param {number} fullHeight - The full height of multiview setup.
  16329. * @param {number} x - The horizontal offset of the subcamera.
  16330. * @param {number} y - The vertical offset of the subcamera.
  16331. * @param {number} width - The width of subcamera.
  16332. * @param {number} height - The height of subcamera.
  16333. */
  16334. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  16335. this.aspect = fullWidth / fullHeight;
  16336. if ( this.view === null ) {
  16337. this.view = {
  16338. enabled: true,
  16339. fullWidth: 1,
  16340. fullHeight: 1,
  16341. offsetX: 0,
  16342. offsetY: 0,
  16343. width: 1,
  16344. height: 1
  16345. };
  16346. }
  16347. this.view.enabled = true;
  16348. this.view.fullWidth = fullWidth;
  16349. this.view.fullHeight = fullHeight;
  16350. this.view.offsetX = x;
  16351. this.view.offsetY = y;
  16352. this.view.width = width;
  16353. this.view.height = height;
  16354. this.updateProjectionMatrix();
  16355. }
  16356. /**
  16357. * Removes the view offset from the projection matrix.
  16358. */
  16359. clearViewOffset() {
  16360. if ( this.view !== null ) {
  16361. this.view.enabled = false;
  16362. }
  16363. this.updateProjectionMatrix();
  16364. }
  16365. /**
  16366. * Updates the camera's projection matrix. Must be called after any change of
  16367. * camera properties.
  16368. */
  16369. updateProjectionMatrix() {
  16370. const near = this.near;
  16371. let top = near * Math.tan( DEG2RAD * 0.5 * this.fov ) / this.zoom;
  16372. let height = 2 * top;
  16373. let width = this.aspect * height;
  16374. let left = -0.5 * width;
  16375. const view = this.view;
  16376. if ( this.view !== null && this.view.enabled ) {
  16377. const fullWidth = view.fullWidth,
  16378. fullHeight = view.fullHeight;
  16379. left += view.offsetX * width / fullWidth;
  16380. top -= view.offsetY * height / fullHeight;
  16381. width *= view.width / fullWidth;
  16382. height *= view.height / fullHeight;
  16383. }
  16384. const skew = this.filmOffset;
  16385. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16386. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far, this.coordinateSystem, this.reversedDepth );
  16387. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  16388. }
  16389. toJSON( meta ) {
  16390. const data = super.toJSON( meta );
  16391. data.object.fov = this.fov;
  16392. data.object.zoom = this.zoom;
  16393. data.object.near = this.near;
  16394. data.object.far = this.far;
  16395. data.object.focus = this.focus;
  16396. data.object.aspect = this.aspect;
  16397. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16398. data.object.filmGauge = this.filmGauge;
  16399. data.object.filmOffset = this.filmOffset;
  16400. return data;
  16401. }
  16402. }
  16403. const fov = -90; // negative fov is not an error
  16404. const aspect = 1;
  16405. /**
  16406. * A special type of camera that is positioned in 3D space to render its surroundings into a
  16407. * cube render target. The render target can then be used as an environment map for rendering
  16408. * realtime reflections in your scene.
  16409. *
  16410. * ```js
  16411. * // Create cube render target
  16412. * const cubeRenderTarget = new THREE.WebGLCubeRenderTarget( 256, { generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter } );
  16413. *
  16414. * // Create cube camera
  16415. * const cubeCamera = new THREE.CubeCamera( 1, 100000, cubeRenderTarget );
  16416. * scene.add( cubeCamera );
  16417. *
  16418. * // Create car
  16419. * const chromeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff, envMap: cubeRenderTarget.texture } );
  16420. * const car = new THREE.Mesh( carGeometry, chromeMaterial );
  16421. * scene.add( car );
  16422. *
  16423. * // Update the render target cube
  16424. * car.visible = false;
  16425. * cubeCamera.position.copy( car.position );
  16426. * cubeCamera.update( renderer, scene );
  16427. *
  16428. * // Render the scene
  16429. * car.visible = true;
  16430. * renderer.render( scene, camera );
  16431. * ```
  16432. *
  16433. * @augments Object3D
  16434. */
  16435. class CubeCamera extends Object3D {
  16436. /**
  16437. * Constructs a new cube camera.
  16438. *
  16439. * @param {number} near - The camera's near plane.
  16440. * @param {number} far - The camera's far plane.
  16441. * @param {WebGLCubeRenderTarget} renderTarget - The cube render target.
  16442. */
  16443. constructor( near, far, renderTarget ) {
  16444. super();
  16445. this.type = 'CubeCamera';
  16446. /**
  16447. * A reference to the cube render target.
  16448. *
  16449. * @type {WebGLCubeRenderTarget}
  16450. */
  16451. this.renderTarget = renderTarget;
  16452. /**
  16453. * The current active coordinate system.
  16454. *
  16455. * @type {?(WebGLCoordinateSystem|WebGPUCoordinateSystem)}
  16456. * @default null
  16457. */
  16458. this.coordinateSystem = null;
  16459. /**
  16460. * The current active mipmap level
  16461. *
  16462. * @type {number}
  16463. * @default 0
  16464. */
  16465. this.activeMipmapLevel = 0;
  16466. const cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  16467. cameraPX.layers = this.layers;
  16468. this.add( cameraPX );
  16469. const cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  16470. cameraNX.layers = this.layers;
  16471. this.add( cameraNX );
  16472. const cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  16473. cameraPY.layers = this.layers;
  16474. this.add( cameraPY );
  16475. const cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  16476. cameraNY.layers = this.layers;
  16477. this.add( cameraNY );
  16478. const cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  16479. cameraPZ.layers = this.layers;
  16480. this.add( cameraPZ );
  16481. const cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  16482. cameraNZ.layers = this.layers;
  16483. this.add( cameraNZ );
  16484. }
  16485. /**
  16486. * Must be called when the coordinate system of the cube camera is changed.
  16487. */
  16488. updateCoordinateSystem() {
  16489. const coordinateSystem = this.coordinateSystem;
  16490. const cameras = this.children.concat();
  16491. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = cameras;
  16492. for ( const camera of cameras ) this.remove( camera );
  16493. if ( coordinateSystem === WebGLCoordinateSystem ) {
  16494. cameraPX.up.set( 0, 1, 0 );
  16495. cameraPX.lookAt( 1, 0, 0 );
  16496. cameraNX.up.set( 0, 1, 0 );
  16497. cameraNX.lookAt( -1, 0, 0 );
  16498. cameraPY.up.set( 0, 0, -1 );
  16499. cameraPY.lookAt( 0, 1, 0 );
  16500. cameraNY.up.set( 0, 0, 1 );
  16501. cameraNY.lookAt( 0, -1, 0 );
  16502. cameraPZ.up.set( 0, 1, 0 );
  16503. cameraPZ.lookAt( 0, 0, 1 );
  16504. cameraNZ.up.set( 0, 1, 0 );
  16505. cameraNZ.lookAt( 0, 0, -1 );
  16506. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  16507. cameraPX.up.set( 0, -1, 0 );
  16508. cameraPX.lookAt( -1, 0, 0 );
  16509. cameraNX.up.set( 0, -1, 0 );
  16510. cameraNX.lookAt( 1, 0, 0 );
  16511. cameraPY.up.set( 0, 0, 1 );
  16512. cameraPY.lookAt( 0, 1, 0 );
  16513. cameraNY.up.set( 0, 0, -1 );
  16514. cameraNY.lookAt( 0, -1, 0 );
  16515. cameraPZ.up.set( 0, -1, 0 );
  16516. cameraPZ.lookAt( 0, 0, 1 );
  16517. cameraNZ.up.set( 0, -1, 0 );
  16518. cameraNZ.lookAt( 0, 0, -1 );
  16519. } else {
  16520. throw new Error( 'THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: ' + coordinateSystem );
  16521. }
  16522. for ( const camera of cameras ) {
  16523. this.add( camera );
  16524. camera.updateMatrixWorld();
  16525. }
  16526. }
  16527. /**
  16528. * Calling this method will render the given scene with the given renderer
  16529. * into the cube render target of the camera.
  16530. *
  16531. * @param {(Renderer|WebGLRenderer)} renderer - The renderer.
  16532. * @param {Scene} scene - The scene to render.
  16533. */
  16534. update( renderer, scene ) {
  16535. if ( this.parent === null ) this.updateMatrixWorld();
  16536. const { renderTarget, activeMipmapLevel } = this;
  16537. if ( this.coordinateSystem !== renderer.coordinateSystem ) {
  16538. this.coordinateSystem = renderer.coordinateSystem;
  16539. this.updateCoordinateSystem();
  16540. }
  16541. const [ cameraPX, cameraNX, cameraPY, cameraNY, cameraPZ, cameraNZ ] = this.children;
  16542. const currentRenderTarget = renderer.getRenderTarget();
  16543. const currentActiveCubeFace = renderer.getActiveCubeFace();
  16544. const currentActiveMipmapLevel = renderer.getActiveMipmapLevel();
  16545. const currentXrEnabled = renderer.xr.enabled;
  16546. renderer.xr.enabled = false;
  16547. const generateMipmaps = renderTarget.texture.generateMipmaps;
  16548. renderTarget.texture.generateMipmaps = false;
  16549. renderer.setRenderTarget( renderTarget, 0, activeMipmapLevel );
  16550. renderer.render( scene, cameraPX );
  16551. renderer.setRenderTarget( renderTarget, 1, activeMipmapLevel );
  16552. renderer.render( scene, cameraNX );
  16553. renderer.setRenderTarget( renderTarget, 2, activeMipmapLevel );
  16554. renderer.render( scene, cameraPY );
  16555. renderer.setRenderTarget( renderTarget, 3, activeMipmapLevel );
  16556. renderer.render( scene, cameraNY );
  16557. renderer.setRenderTarget( renderTarget, 4, activeMipmapLevel );
  16558. renderer.render( scene, cameraPZ );
  16559. // mipmaps are generated during the last call of render()
  16560. // at this point, all sides of the cube render target are defined
  16561. renderTarget.texture.generateMipmaps = generateMipmaps;
  16562. renderer.setRenderTarget( renderTarget, 5, activeMipmapLevel );
  16563. renderer.render( scene, cameraNZ );
  16564. renderer.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  16565. renderer.xr.enabled = currentXrEnabled;
  16566. renderTarget.texture.needsPMREMUpdate = true;
  16567. }
  16568. }
  16569. /**
  16570. * Creates a cube texture made up of six images.
  16571. *
  16572. * ```js
  16573. * const loader = new THREE.CubeTextureLoader();
  16574. * loader.setPath( 'textures/cube/pisa/' );
  16575. *
  16576. * const textureCube = loader.load( [
  16577. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  16578. * ] );
  16579. *
  16580. * const material = new THREE.MeshBasicMaterial( { color: 0xffffff, envMap: textureCube } );
  16581. * ```
  16582. *
  16583. * @augments Texture
  16584. */
  16585. class CubeTexture extends Texture {
  16586. /**
  16587. * Constructs a new cube texture.
  16588. *
  16589. * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube.
  16590. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  16591. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  16592. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  16593. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  16594. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  16595. * @param {number} [format=RGBAFormat] - The texture format.
  16596. * @param {number} [type=UnsignedByteType] - The texture type.
  16597. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  16598. * @param {string} [colorSpace=NoColorSpace] - The color space value.
  16599. */
  16600. constructor( images = [], mapping = CubeReflectionMapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace ) {
  16601. super( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  16602. /**
  16603. * This flag can be used for type testing.
  16604. *
  16605. * @type {boolean}
  16606. * @readonly
  16607. * @default true
  16608. */
  16609. this.isCubeTexture = true;
  16610. /**
  16611. * If set to `true`, the texture is flipped along the vertical axis when
  16612. * uploaded to the GPU.
  16613. *
  16614. * Overwritten and set to `false` by default.
  16615. *
  16616. * @type {boolean}
  16617. * @default false
  16618. */
  16619. this.flipY = false;
  16620. }
  16621. /**
  16622. * Alias for {@link CubeTexture#image}.
  16623. *
  16624. * @type {Array<Image>}
  16625. */
  16626. get images() {
  16627. return this.image;
  16628. }
  16629. set images( value ) {
  16630. this.image = value;
  16631. }
  16632. }
  16633. /**
  16634. * A cube render target used in context of {@link WebGLRenderer}.
  16635. *
  16636. * @augments WebGLRenderTarget
  16637. */
  16638. class WebGLCubeRenderTarget extends WebGLRenderTarget {
  16639. /**
  16640. * Constructs a new cube render target.
  16641. *
  16642. * @param {number} [size=1] - The size of the render target.
  16643. * @param {RenderTarget~Options} [options] - The configuration object.
  16644. */
  16645. constructor( size = 1, options = {} ) {
  16646. super( size, size, options );
  16647. /**
  16648. * This flag can be used for type testing.
  16649. *
  16650. * @type {boolean}
  16651. * @readonly
  16652. * @default true
  16653. */
  16654. this.isWebGLCubeRenderTarget = true;
  16655. const image = { width: size, height: size, depth: 1 };
  16656. const images = [ image, image, image, image, image, image ];
  16657. /**
  16658. * Overwritten with a different texture type.
  16659. *
  16660. * @type {DataArrayTexture}
  16661. */
  16662. this.texture = new CubeTexture( images );
  16663. this._setTextureOptions( options );
  16664. // By convention -- likely based on the RenderMan spec from the 1990's -- cube maps are specified by WebGL (and three.js)
  16665. // in a coordinate system in which positive-x is to the right when looking up the positive-z axis -- in other words,
  16666. // in a left-handed coordinate system. By continuing this convention, preexisting cube maps continued to render correctly.
  16667. // three.js uses a right-handed coordinate system. So environment maps used in three.js appear to have px and nx swapped
  16668. // and the flag isRenderTargetTexture controls this conversion. The flip is not required when using WebGLCubeRenderTarget.texture
  16669. // as a cube texture (this is detected when isRenderTargetTexture is set to true for cube textures).
  16670. this.texture.isRenderTargetTexture = true;
  16671. }
  16672. /**
  16673. * Converts the given equirectangular texture to a cube map.
  16674. *
  16675. * @param {WebGLRenderer} renderer - The renderer.
  16676. * @param {Texture} texture - The equirectangular texture.
  16677. * @return {WebGLCubeRenderTarget} A reference to this cube render target.
  16678. */
  16679. fromEquirectangularTexture( renderer, texture ) {
  16680. this.texture.type = texture.type;
  16681. this.texture.colorSpace = texture.colorSpace;
  16682. this.texture.generateMipmaps = texture.generateMipmaps;
  16683. this.texture.minFilter = texture.minFilter;
  16684. this.texture.magFilter = texture.magFilter;
  16685. const shader = {
  16686. uniforms: {
  16687. tEquirect: { value: null },
  16688. },
  16689. vertexShader: /* glsl */`
  16690. varying vec3 vWorldDirection;
  16691. vec3 transformDirection( in vec3 dir, in mat4 matrix ) {
  16692. return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );
  16693. }
  16694. void main() {
  16695. vWorldDirection = transformDirection( position, modelMatrix );
  16696. #include <begin_vertex>
  16697. #include <project_vertex>
  16698. }
  16699. `,
  16700. fragmentShader: /* glsl */`
  16701. uniform sampler2D tEquirect;
  16702. varying vec3 vWorldDirection;
  16703. #include <common>
  16704. void main() {
  16705. vec3 direction = normalize( vWorldDirection );
  16706. vec2 sampleUV = equirectUv( direction );
  16707. gl_FragColor = texture2D( tEquirect, sampleUV );
  16708. }
  16709. `
  16710. };
  16711. const geometry = new BoxGeometry( 5, 5, 5 );
  16712. const material = new ShaderMaterial( {
  16713. name: 'CubemapFromEquirect',
  16714. uniforms: cloneUniforms( shader.uniforms ),
  16715. vertexShader: shader.vertexShader,
  16716. fragmentShader: shader.fragmentShader,
  16717. side: BackSide,
  16718. blending: NoBlending
  16719. } );
  16720. material.uniforms.tEquirect.value = texture;
  16721. const mesh = new Mesh( geometry, material );
  16722. const currentMinFilter = texture.minFilter;
  16723. // Avoid blurred poles
  16724. if ( texture.minFilter === LinearMipmapLinearFilter ) texture.minFilter = LinearFilter;
  16725. const camera = new CubeCamera( 1, 10, this );
  16726. camera.update( renderer, mesh );
  16727. texture.minFilter = currentMinFilter;
  16728. mesh.geometry.dispose();
  16729. mesh.material.dispose();
  16730. return this;
  16731. }
  16732. /**
  16733. * Clears this cube render target.
  16734. *
  16735. * @param {WebGLRenderer} renderer - The renderer.
  16736. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  16737. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  16738. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  16739. */
  16740. clear( renderer, color = true, depth = true, stencil = true ) {
  16741. const currentRenderTarget = renderer.getRenderTarget();
  16742. for ( let i = 0; i < 6; i ++ ) {
  16743. renderer.setRenderTarget( this, i );
  16744. renderer.clear( color, depth, stencil );
  16745. }
  16746. renderer.setRenderTarget( currentRenderTarget );
  16747. }
  16748. }
  16749. /**
  16750. * This is almost identical to an {@link Object3D}. Its purpose is to
  16751. * make working with groups of objects syntactically clearer.
  16752. *
  16753. * ```js
  16754. * // Create a group and add the two cubes.
  16755. * // These cubes can now be rotated / scaled etc as a group.
  16756. * const group = new THREE.Group();
  16757. *
  16758. * group.add( meshA );
  16759. * group.add( meshB );
  16760. *
  16761. * scene.add( group );
  16762. * ```
  16763. *
  16764. * @augments Object3D
  16765. */
  16766. class Group extends Object3D {
  16767. constructor() {
  16768. super();
  16769. /**
  16770. * This flag can be used for type testing.
  16771. *
  16772. * @type {boolean}
  16773. * @readonly
  16774. * @default true
  16775. */
  16776. this.isGroup = true;
  16777. this.type = 'Group';
  16778. }
  16779. }
  16780. const _moveEvent = { type: 'move' };
  16781. /**
  16782. * Class for representing a XR controller with its
  16783. * different coordinate systems.
  16784. *
  16785. * @private
  16786. */
  16787. class WebXRController {
  16788. /**
  16789. * Constructs a new XR controller.
  16790. */
  16791. constructor() {
  16792. /**
  16793. * A group representing the target ray space
  16794. * of the XR controller.
  16795. *
  16796. * @private
  16797. * @type {?Group}
  16798. * @default null
  16799. */
  16800. this._targetRay = null;
  16801. /**
  16802. * A group representing the grip space
  16803. * of the XR controller.
  16804. *
  16805. * @private
  16806. * @type {?Group}
  16807. * @default null
  16808. */
  16809. this._grip = null;
  16810. /**
  16811. * A group representing the hand space
  16812. * of the XR controller.
  16813. *
  16814. * @private
  16815. * @type {?Group}
  16816. * @default null
  16817. */
  16818. this._hand = null;
  16819. }
  16820. /**
  16821. * Returns a group representing the hand space of the XR controller.
  16822. *
  16823. * @return {Group} A group representing the hand space of the XR controller.
  16824. */
  16825. getHandSpace() {
  16826. if ( this._hand === null ) {
  16827. this._hand = new Group();
  16828. this._hand.matrixAutoUpdate = false;
  16829. this._hand.visible = false;
  16830. this._hand.joints = {};
  16831. this._hand.inputState = { pinching: false };
  16832. }
  16833. return this._hand;
  16834. }
  16835. /**
  16836. * Returns a group representing the target ray space of the XR controller.
  16837. *
  16838. * @return {Group} A group representing the target ray space of the XR controller.
  16839. */
  16840. getTargetRaySpace() {
  16841. if ( this._targetRay === null ) {
  16842. this._targetRay = new Group();
  16843. this._targetRay.matrixAutoUpdate = false;
  16844. this._targetRay.visible = false;
  16845. this._targetRay.hasLinearVelocity = false;
  16846. this._targetRay.linearVelocity = new Vector3();
  16847. this._targetRay.hasAngularVelocity = false;
  16848. this._targetRay.angularVelocity = new Vector3();
  16849. }
  16850. return this._targetRay;
  16851. }
  16852. /**
  16853. * Returns a group representing the grip space of the XR controller.
  16854. *
  16855. * @return {Group} A group representing the grip space of the XR controller.
  16856. */
  16857. getGripSpace() {
  16858. if ( this._grip === null ) {
  16859. this._grip = new Group();
  16860. this._grip.matrixAutoUpdate = false;
  16861. this._grip.visible = false;
  16862. this._grip.hasLinearVelocity = false;
  16863. this._grip.linearVelocity = new Vector3();
  16864. this._grip.hasAngularVelocity = false;
  16865. this._grip.angularVelocity = new Vector3();
  16866. }
  16867. return this._grip;
  16868. }
  16869. /**
  16870. * Dispatches the given event to the groups representing
  16871. * the different coordinate spaces of the XR controller.
  16872. *
  16873. * @param {Object} event - The event to dispatch.
  16874. * @return {WebXRController} A reference to this instance.
  16875. */
  16876. dispatchEvent( event ) {
  16877. if ( this._targetRay !== null ) {
  16878. this._targetRay.dispatchEvent( event );
  16879. }
  16880. if ( this._grip !== null ) {
  16881. this._grip.dispatchEvent( event );
  16882. }
  16883. if ( this._hand !== null ) {
  16884. this._hand.dispatchEvent( event );
  16885. }
  16886. return this;
  16887. }
  16888. /**
  16889. * Connects the controller with the given XR input source.
  16890. *
  16891. * @param {XRInputSource} inputSource - The input source.
  16892. * @return {WebXRController} A reference to this instance.
  16893. */
  16894. connect( inputSource ) {
  16895. if ( inputSource && inputSource.hand ) {
  16896. const hand = this._hand;
  16897. if ( hand ) {
  16898. for ( const inputjoint of inputSource.hand.values() ) {
  16899. // Initialize hand with joints when connected
  16900. this._getHandJoint( hand, inputjoint );
  16901. }
  16902. }
  16903. }
  16904. this.dispatchEvent( { type: 'connected', data: inputSource } );
  16905. return this;
  16906. }
  16907. /**
  16908. * Disconnects the controller from the given XR input source.
  16909. *
  16910. * @param {XRInputSource} inputSource - The input source.
  16911. * @return {WebXRController} A reference to this instance.
  16912. */
  16913. disconnect( inputSource ) {
  16914. this.dispatchEvent( { type: 'disconnected', data: inputSource } );
  16915. if ( this._targetRay !== null ) {
  16916. this._targetRay.visible = false;
  16917. }
  16918. if ( this._grip !== null ) {
  16919. this._grip.visible = false;
  16920. }
  16921. if ( this._hand !== null ) {
  16922. this._hand.visible = false;
  16923. }
  16924. return this;
  16925. }
  16926. /**
  16927. * Updates the controller with the given input source, XR frame and reference space.
  16928. * This updates the transformations of the groups that represent the different
  16929. * coordinate systems of the controller.
  16930. *
  16931. * @param {XRInputSource} inputSource - The input source.
  16932. * @param {XRFrame} frame - The XR frame.
  16933. * @param {XRReferenceSpace} referenceSpace - The reference space.
  16934. * @return {WebXRController} A reference to this instance.
  16935. */
  16936. update( inputSource, frame, referenceSpace ) {
  16937. let inputPose = null;
  16938. let gripPose = null;
  16939. let handPose = null;
  16940. const targetRay = this._targetRay;
  16941. const grip = this._grip;
  16942. const hand = this._hand;
  16943. if ( inputSource && frame.session.visibilityState !== 'visible-blurred' ) {
  16944. if ( hand && inputSource.hand ) {
  16945. handPose = true;
  16946. for ( const inputjoint of inputSource.hand.values() ) {
  16947. // Update the joints groups with the XRJoint poses
  16948. const jointPose = frame.getJointPose( inputjoint, referenceSpace );
  16949. // The transform of this joint will be updated with the joint pose on each frame
  16950. const joint = this._getHandJoint( hand, inputjoint );
  16951. if ( jointPose !== null ) {
  16952. joint.matrix.fromArray( jointPose.transform.matrix );
  16953. joint.matrix.decompose( joint.position, joint.rotation, joint.scale );
  16954. joint.matrixWorldNeedsUpdate = true;
  16955. joint.jointRadius = jointPose.radius;
  16956. }
  16957. joint.visible = jointPose !== null;
  16958. }
  16959. // Custom events
  16960. // Check pinchz
  16961. const indexTip = hand.joints[ 'index-finger-tip' ];
  16962. const thumbTip = hand.joints[ 'thumb-tip' ];
  16963. const distance = indexTip.position.distanceTo( thumbTip.position );
  16964. const distanceToPinch = 0.02;
  16965. const threshold = 0.005;
  16966. if ( hand.inputState.pinching && distance > distanceToPinch + threshold ) {
  16967. hand.inputState.pinching = false;
  16968. this.dispatchEvent( {
  16969. type: 'pinchend',
  16970. handedness: inputSource.handedness,
  16971. target: this
  16972. } );
  16973. } else if ( ! hand.inputState.pinching && distance <= distanceToPinch - threshold ) {
  16974. hand.inputState.pinching = true;
  16975. this.dispatchEvent( {
  16976. type: 'pinchstart',
  16977. handedness: inputSource.handedness,
  16978. target: this
  16979. } );
  16980. }
  16981. } else {
  16982. if ( grip !== null && inputSource.gripSpace ) {
  16983. gripPose = frame.getPose( inputSource.gripSpace, referenceSpace );
  16984. if ( gripPose !== null ) {
  16985. grip.matrix.fromArray( gripPose.transform.matrix );
  16986. grip.matrix.decompose( grip.position, grip.rotation, grip.scale );
  16987. grip.matrixWorldNeedsUpdate = true;
  16988. if ( gripPose.linearVelocity ) {
  16989. grip.hasLinearVelocity = true;
  16990. grip.linearVelocity.copy( gripPose.linearVelocity );
  16991. } else {
  16992. grip.hasLinearVelocity = false;
  16993. }
  16994. if ( gripPose.angularVelocity ) {
  16995. grip.hasAngularVelocity = true;
  16996. grip.angularVelocity.copy( gripPose.angularVelocity );
  16997. } else {
  16998. grip.hasAngularVelocity = false;
  16999. }
  17000. }
  17001. }
  17002. }
  17003. if ( targetRay !== null ) {
  17004. inputPose = frame.getPose( inputSource.targetRaySpace, referenceSpace );
  17005. // Some runtimes (namely Vive Cosmos with Vive OpenXR Runtime) have only grip space and ray space is equal to it
  17006. if ( inputPose === null && gripPose !== null ) {
  17007. inputPose = gripPose;
  17008. }
  17009. if ( inputPose !== null ) {
  17010. targetRay.matrix.fromArray( inputPose.transform.matrix );
  17011. targetRay.matrix.decompose( targetRay.position, targetRay.rotation, targetRay.scale );
  17012. targetRay.matrixWorldNeedsUpdate = true;
  17013. if ( inputPose.linearVelocity ) {
  17014. targetRay.hasLinearVelocity = true;
  17015. targetRay.linearVelocity.copy( inputPose.linearVelocity );
  17016. } else {
  17017. targetRay.hasLinearVelocity = false;
  17018. }
  17019. if ( inputPose.angularVelocity ) {
  17020. targetRay.hasAngularVelocity = true;
  17021. targetRay.angularVelocity.copy( inputPose.angularVelocity );
  17022. } else {
  17023. targetRay.hasAngularVelocity = false;
  17024. }
  17025. this.dispatchEvent( _moveEvent );
  17026. }
  17027. }
  17028. }
  17029. if ( targetRay !== null ) {
  17030. targetRay.visible = ( inputPose !== null );
  17031. }
  17032. if ( grip !== null ) {
  17033. grip.visible = ( gripPose !== null );
  17034. }
  17035. if ( hand !== null ) {
  17036. hand.visible = ( handPose !== null );
  17037. }
  17038. return this;
  17039. }
  17040. /**
  17041. * Returns a group representing the hand joint for the given input joint.
  17042. *
  17043. * @private
  17044. * @param {Group} hand - The group representing the hand space.
  17045. * @param {XRJointSpace} inputjoint - The hand joint data.
  17046. * @return {Group} A group representing the hand joint for the given input joint.
  17047. */
  17048. _getHandJoint( hand, inputjoint ) {
  17049. if ( hand.joints[ inputjoint.jointName ] === undefined ) {
  17050. const joint = new Group();
  17051. joint.matrixAutoUpdate = false;
  17052. joint.visible = false;
  17053. hand.joints[ inputjoint.jointName ] = joint;
  17054. hand.add( joint );
  17055. }
  17056. return hand.joints[ inputjoint.jointName ];
  17057. }
  17058. }
  17059. /**
  17060. * This class can be used to define an exponential squared fog,
  17061. * which gives a clear view near the camera and a faster than exponentially
  17062. * densening fog farther from the camera.
  17063. *
  17064. * ```js
  17065. * const scene = new THREE.Scene();
  17066. * scene.fog = new THREE.FogExp2( 0xcccccc, 0.002 );
  17067. * ```
  17068. */
  17069. class FogExp2 {
  17070. /**
  17071. * Constructs a new fog.
  17072. *
  17073. * @param {number|Color} color - The fog's color.
  17074. * @param {number} [density=0.00025] - Defines how fast the fog will grow dense.
  17075. */
  17076. constructor( color, density = 0.00025 ) {
  17077. /**
  17078. * This flag can be used for type testing.
  17079. *
  17080. * @type {boolean}
  17081. * @readonly
  17082. * @default true
  17083. */
  17084. this.isFogExp2 = true;
  17085. /**
  17086. * The name of the fog.
  17087. *
  17088. * @type {string}
  17089. */
  17090. this.name = '';
  17091. /**
  17092. * The fog's color.
  17093. *
  17094. * @type {Color}
  17095. */
  17096. this.color = new Color( color );
  17097. /**
  17098. * Defines how fast the fog will grow dense.
  17099. *
  17100. * @type {number}
  17101. * @default 0.00025
  17102. */
  17103. this.density = density;
  17104. }
  17105. /**
  17106. * Returns a new fog with copied values from this instance.
  17107. *
  17108. * @return {FogExp2} A clone of this instance.
  17109. */
  17110. clone() {
  17111. return new FogExp2( this.color, this.density );
  17112. }
  17113. /**
  17114. * Serializes the fog into JSON.
  17115. *
  17116. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17117. * @return {Object} A JSON object representing the serialized fog
  17118. */
  17119. toJSON( /* meta */ ) {
  17120. return {
  17121. type: 'FogExp2',
  17122. name: this.name,
  17123. color: this.color.getHex(),
  17124. density: this.density
  17125. };
  17126. }
  17127. }
  17128. /**
  17129. * This class can be used to define a linear fog that grows linearly denser
  17130. * with the distance.
  17131. *
  17132. * ```js
  17133. * const scene = new THREE.Scene();
  17134. * scene.fog = new THREE.Fog( 0xcccccc, 10, 15 );
  17135. * ```
  17136. */
  17137. class Fog {
  17138. /**
  17139. * Constructs a new fog.
  17140. *
  17141. * @param {number|Color} color - The fog's color.
  17142. * @param {number} [near=1] - The minimum distance to start applying fog.
  17143. * @param {number} [far=1000] - The maximum distance at which fog stops being calculated and applied.
  17144. */
  17145. constructor( color, near = 1, far = 1000 ) {
  17146. /**
  17147. * This flag can be used for type testing.
  17148. *
  17149. * @type {boolean}
  17150. * @readonly
  17151. * @default true
  17152. */
  17153. this.isFog = true;
  17154. /**
  17155. * The name of the fog.
  17156. *
  17157. * @type {string}
  17158. */
  17159. this.name = '';
  17160. /**
  17161. * The fog's color.
  17162. *
  17163. * @type {Color}
  17164. */
  17165. this.color = new Color( color );
  17166. /**
  17167. * The minimum distance to start applying fog. Objects that are less than
  17168. * `near` units from the active camera won't be affected by fog.
  17169. *
  17170. * @type {number}
  17171. * @default 1
  17172. */
  17173. this.near = near;
  17174. /**
  17175. * The maximum distance at which fog stops being calculated and applied.
  17176. * Objects that are more than `far` units away from the active camera won't
  17177. * be affected by fog.
  17178. *
  17179. * @type {number}
  17180. * @default 1000
  17181. */
  17182. this.far = far;
  17183. }
  17184. /**
  17185. * Returns a new fog with copied values from this instance.
  17186. *
  17187. * @return {Fog} A clone of this instance.
  17188. */
  17189. clone() {
  17190. return new Fog( this.color, this.near, this.far );
  17191. }
  17192. /**
  17193. * Serializes the fog into JSON.
  17194. *
  17195. * @param {?(Object|string)} meta - An optional value holding meta information about the serialization.
  17196. * @return {Object} A JSON object representing the serialized fog
  17197. */
  17198. toJSON( /* meta */ ) {
  17199. return {
  17200. type: 'Fog',
  17201. name: this.name,
  17202. color: this.color.getHex(),
  17203. near: this.near,
  17204. far: this.far
  17205. };
  17206. }
  17207. }
  17208. /**
  17209. * Scenes allow you to set up what is to be rendered and where by three.js.
  17210. * This is where you place 3D objects like meshes, lines or lights.
  17211. *
  17212. * @augments Object3D
  17213. */
  17214. class Scene extends Object3D {
  17215. /**
  17216. * Constructs a new scene.
  17217. */
  17218. constructor() {
  17219. super();
  17220. /**
  17221. * This flag can be used for type testing.
  17222. *
  17223. * @type {boolean}
  17224. * @readonly
  17225. * @default true
  17226. */
  17227. this.isScene = true;
  17228. this.type = 'Scene';
  17229. /**
  17230. * Defines the background of the scene. Valid inputs are:
  17231. *
  17232. * - A color for defining a uniform colored background.
  17233. * - A texture for defining a (flat) textured background.
  17234. * - Cube textures or equirectangular textures for defining a skybox.
  17235. *
  17236. * @type {?(Color|Texture)}
  17237. * @default null
  17238. */
  17239. this.background = null;
  17240. /**
  17241. * Sets the environment map for all physical materials in the scene. However,
  17242. * it's not possible to overwrite an existing texture assigned to the `envMap`
  17243. * material property.
  17244. *
  17245. * @type {?Texture}
  17246. * @default null
  17247. */
  17248. this.environment = null;
  17249. /**
  17250. * A fog instance defining the type of fog that affects everything
  17251. * rendered in the scene.
  17252. *
  17253. * @type {?(Fog|FogExp2)}
  17254. * @default null
  17255. */
  17256. this.fog = null;
  17257. /**
  17258. * Sets the blurriness of the background. Only influences environment maps
  17259. * assigned to {@link Scene#background}. Valid input is a float between `0`
  17260. * and `1`.
  17261. *
  17262. * @type {number}
  17263. * @default 0
  17264. */
  17265. this.backgroundBlurriness = 0;
  17266. /**
  17267. * Attenuates the color of the background. Only applies to background textures.
  17268. *
  17269. * @type {number}
  17270. * @default 1
  17271. */
  17272. this.backgroundIntensity = 1;
  17273. /**
  17274. * The rotation of the background in radians. Only influences environment maps
  17275. * assigned to {@link Scene#background}.
  17276. *
  17277. * @type {Euler}
  17278. * @default (0,0,0)
  17279. */
  17280. this.backgroundRotation = new Euler();
  17281. /**
  17282. * Attenuates the color of the environment. Only influences environment maps
  17283. * assigned to {@link Scene#environment}.
  17284. *
  17285. * @type {number}
  17286. * @default 1
  17287. */
  17288. this.environmentIntensity = 1;
  17289. /**
  17290. * The rotation of the environment map in radians. Only influences physical materials
  17291. * in the scene when {@link Scene#environment} is used.
  17292. *
  17293. * @type {Euler}
  17294. * @default (0,0,0)
  17295. */
  17296. this.environmentRotation = new Euler();
  17297. /**
  17298. * Forces everything in the scene to be rendered with the defined material. It is possible
  17299. * to exclude materials from override by setting {@link Material#allowOverride} to `false`.
  17300. *
  17301. * @type {?Material}
  17302. * @default null
  17303. */
  17304. this.overrideMaterial = null;
  17305. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  17306. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  17307. }
  17308. }
  17309. copy( source, recursive ) {
  17310. super.copy( source, recursive );
  17311. if ( source.background !== null ) this.background = source.background.clone();
  17312. if ( source.environment !== null ) this.environment = source.environment.clone();
  17313. if ( source.fog !== null ) this.fog = source.fog.clone();
  17314. this.backgroundBlurriness = source.backgroundBlurriness;
  17315. this.backgroundIntensity = source.backgroundIntensity;
  17316. this.backgroundRotation.copy( source.backgroundRotation );
  17317. this.environmentIntensity = source.environmentIntensity;
  17318. this.environmentRotation.copy( source.environmentRotation );
  17319. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17320. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17321. return this;
  17322. }
  17323. toJSON( meta ) {
  17324. const data = super.toJSON( meta );
  17325. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17326. if ( this.backgroundBlurriness > 0 ) data.object.backgroundBlurriness = this.backgroundBlurriness;
  17327. if ( this.backgroundIntensity !== 1 ) data.object.backgroundIntensity = this.backgroundIntensity;
  17328. data.object.backgroundRotation = this.backgroundRotation.toArray();
  17329. if ( this.environmentIntensity !== 1 ) data.object.environmentIntensity = this.environmentIntensity;
  17330. data.object.environmentRotation = this.environmentRotation.toArray();
  17331. return data;
  17332. }
  17333. }
  17334. /**
  17335. * "Interleaved" means that multiple attributes, possibly of different types,
  17336. * (e.g., position, normal, uv, color) are packed into a single array buffer.
  17337. *
  17338. * An introduction into interleaved arrays can be found here: [Interleaved array basics](https://blog.tojicode.com/2011/05/interleaved-array-basics.html)
  17339. */
  17340. class InterleavedBuffer {
  17341. /**
  17342. * Constructs a new interleaved buffer.
  17343. *
  17344. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  17345. * @param {number} stride - The number of typed-array elements per vertex.
  17346. */
  17347. constructor( array, stride ) {
  17348. /**
  17349. * This flag can be used for type testing.
  17350. *
  17351. * @type {boolean}
  17352. * @readonly
  17353. * @default true
  17354. */
  17355. this.isInterleavedBuffer = true;
  17356. /**
  17357. * A typed array with a shared buffer storing attribute data.
  17358. *
  17359. * @type {TypedArray}
  17360. */
  17361. this.array = array;
  17362. /**
  17363. * The number of typed-array elements per vertex.
  17364. *
  17365. * @type {number}
  17366. */
  17367. this.stride = stride;
  17368. /**
  17369. * The total number of elements in the array
  17370. *
  17371. * @type {number}
  17372. * @readonly
  17373. */
  17374. this.count = array !== undefined ? array.length / stride : 0;
  17375. /**
  17376. * Defines the intended usage pattern of the data store for optimization purposes.
  17377. *
  17378. * Note: After the initial use of a buffer, its usage cannot be changed. Instead,
  17379. * instantiate a new one and set the desired usage before the next render.
  17380. *
  17381. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  17382. * @default StaticDrawUsage
  17383. */
  17384. this.usage = StaticDrawUsage;
  17385. /**
  17386. * This can be used to only update some components of stored vectors (for example, just the
  17387. * component related to color). Use the `addUpdateRange()` function to add ranges to this array.
  17388. *
  17389. * @type {Array<Object>}
  17390. */
  17391. this.updateRanges = [];
  17392. /**
  17393. * A version number, incremented every time the `needsUpdate` is set to `true`.
  17394. *
  17395. * @type {number}
  17396. */
  17397. this.version = 0;
  17398. /**
  17399. * The UUID of the interleaved buffer.
  17400. *
  17401. * @type {string}
  17402. * @readonly
  17403. */
  17404. this.uuid = generateUUID();
  17405. }
  17406. /**
  17407. * A callback function that is executed after the renderer has transferred the attribute array
  17408. * data to the GPU.
  17409. */
  17410. onUploadCallback() {}
  17411. /**
  17412. * Flag to indicate that this attribute has changed and should be re-sent to
  17413. * the GPU. Set this to `true` when you modify the value of the array.
  17414. *
  17415. * @type {number}
  17416. * @default false
  17417. * @param {boolean} value
  17418. */
  17419. set needsUpdate( value ) {
  17420. if ( value === true ) this.version ++;
  17421. }
  17422. /**
  17423. * Sets the usage of this interleaved buffer.
  17424. *
  17425. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  17426. * @return {InterleavedBuffer} A reference to this interleaved buffer.
  17427. */
  17428. setUsage( value ) {
  17429. this.usage = value;
  17430. return this;
  17431. }
  17432. /**
  17433. * Adds a range of data in the data array to be updated on the GPU.
  17434. *
  17435. * @param {number} start - Position at which to start update.
  17436. * @param {number} count - The number of components to update.
  17437. */
  17438. addUpdateRange( start, count ) {
  17439. this.updateRanges.push( { start, count } );
  17440. }
  17441. /**
  17442. * Clears the update ranges.
  17443. */
  17444. clearUpdateRanges() {
  17445. this.updateRanges.length = 0;
  17446. }
  17447. /**
  17448. * Copies the values of the given interleaved buffer to this instance.
  17449. *
  17450. * @param {InterleavedBuffer} source - The interleaved buffer to copy.
  17451. * @return {InterleavedBuffer} A reference to this instance.
  17452. */
  17453. copy( source ) {
  17454. this.array = new source.array.constructor( source.array );
  17455. this.count = source.count;
  17456. this.stride = source.stride;
  17457. this.usage = source.usage;
  17458. return this;
  17459. }
  17460. /**
  17461. * Copies a vector from the given interleaved buffer to this one. The start
  17462. * and destination position in the attribute buffers are represented by the
  17463. * given indices.
  17464. *
  17465. * @param {number} index1 - The destination index into this interleaved buffer.
  17466. * @param {InterleavedBuffer} interleavedBuffer - The interleaved buffer to copy from.
  17467. * @param {number} index2 - The source index into the given interleaved buffer.
  17468. * @return {InterleavedBuffer} A reference to this instance.
  17469. */
  17470. copyAt( index1, interleavedBuffer, index2 ) {
  17471. index1 *= this.stride;
  17472. index2 *= interleavedBuffer.stride;
  17473. for ( let i = 0, l = this.stride; i < l; i ++ ) {
  17474. this.array[ index1 + i ] = interleavedBuffer.array[ index2 + i ];
  17475. }
  17476. return this;
  17477. }
  17478. /**
  17479. * Sets the given array data in the interleaved buffer.
  17480. *
  17481. * @param {(TypedArray|Array)} value - The array data to set.
  17482. * @param {number} [offset=0] - The offset in this interleaved buffer's array.
  17483. * @return {InterleavedBuffer} A reference to this instance.
  17484. */
  17485. set( value, offset = 0 ) {
  17486. this.array.set( value, offset );
  17487. return this;
  17488. }
  17489. /**
  17490. * Returns a new interleaved buffer with copied values from this instance.
  17491. *
  17492. * @param {Object} [data] - An object with shared array buffers that allows to retain shared structures.
  17493. * @return {InterleavedBuffer} A clone of this instance.
  17494. */
  17495. clone( data ) {
  17496. if ( data.arrayBuffers === undefined ) {
  17497. data.arrayBuffers = {};
  17498. }
  17499. if ( this.array.buffer._uuid === undefined ) {
  17500. this.array.buffer._uuid = generateUUID();
  17501. }
  17502. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17503. data.arrayBuffers[ this.array.buffer._uuid ] = this.array.slice( 0 ).buffer;
  17504. }
  17505. const array = new this.array.constructor( data.arrayBuffers[ this.array.buffer._uuid ] );
  17506. const ib = new this.constructor( array, this.stride );
  17507. ib.setUsage( this.usage );
  17508. return ib;
  17509. }
  17510. /**
  17511. * Sets the given callback function that is executed after the Renderer has transferred
  17512. * the array data to the GPU. Can be used to perform clean-up operations after
  17513. * the upload when data are not needed anymore on the CPU side.
  17514. *
  17515. * @param {Function} callback - The `onUpload()` callback.
  17516. * @return {InterleavedBuffer} A reference to this instance.
  17517. */
  17518. onUpload( callback ) {
  17519. this.onUploadCallback = callback;
  17520. return this;
  17521. }
  17522. /**
  17523. * Serializes the interleaved buffer into JSON.
  17524. *
  17525. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17526. * @return {Object} A JSON object representing the serialized interleaved buffer.
  17527. */
  17528. toJSON( data ) {
  17529. if ( data.arrayBuffers === undefined ) {
  17530. data.arrayBuffers = {};
  17531. }
  17532. // generate UUID for array buffer if necessary
  17533. if ( this.array.buffer._uuid === undefined ) {
  17534. this.array.buffer._uuid = generateUUID();
  17535. }
  17536. if ( data.arrayBuffers[ this.array.buffer._uuid ] === undefined ) {
  17537. data.arrayBuffers[ this.array.buffer._uuid ] = Array.from( new Uint32Array( this.array.buffer ) );
  17538. }
  17539. //
  17540. return {
  17541. uuid: this.uuid,
  17542. buffer: this.array.buffer._uuid,
  17543. type: this.array.constructor.name,
  17544. stride: this.stride
  17545. };
  17546. }
  17547. }
  17548. const _vector$7 = /*@__PURE__*/ new Vector3();
  17549. /**
  17550. * An alternative version of a buffer attribute with interleaved data. Interleaved
  17551. * attributes share a common interleaved data storage ({@link InterleavedBuffer}) and refer with
  17552. * different offsets into the buffer.
  17553. */
  17554. class InterleavedBufferAttribute {
  17555. /**
  17556. * Constructs a new interleaved buffer attribute.
  17557. *
  17558. * @param {InterleavedBuffer} interleavedBuffer - The buffer holding the interleaved data.
  17559. * @param {number} itemSize - The item size.
  17560. * @param {number} offset - The attribute offset into the buffer.
  17561. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  17562. */
  17563. constructor( interleavedBuffer, itemSize, offset, normalized = false ) {
  17564. /**
  17565. * This flag can be used for type testing.
  17566. *
  17567. * @type {boolean}
  17568. * @readonly
  17569. * @default true
  17570. */
  17571. this.isInterleavedBufferAttribute = true;
  17572. /**
  17573. * The name of the buffer attribute.
  17574. *
  17575. * @type {string}
  17576. */
  17577. this.name = '';
  17578. /**
  17579. * The buffer holding the interleaved data.
  17580. *
  17581. * @type {InterleavedBuffer}
  17582. */
  17583. this.data = interleavedBuffer;
  17584. /**
  17585. * The item size, see {@link BufferAttribute#itemSize}.
  17586. *
  17587. * @type {number}
  17588. */
  17589. this.itemSize = itemSize;
  17590. /**
  17591. * The attribute offset into the buffer.
  17592. *
  17593. * @type {number}
  17594. */
  17595. this.offset = offset;
  17596. /**
  17597. * Whether the data are normalized or not, see {@link BufferAttribute#normalized}
  17598. *
  17599. * @type {InterleavedBuffer}
  17600. */
  17601. this.normalized = normalized;
  17602. }
  17603. /**
  17604. * The item count of this buffer attribute.
  17605. *
  17606. * @type {number}
  17607. * @readonly
  17608. */
  17609. get count() {
  17610. return this.data.count;
  17611. }
  17612. /**
  17613. * The array holding the interleaved buffer attribute data.
  17614. *
  17615. * @type {TypedArray}
  17616. */
  17617. get array() {
  17618. return this.data.array;
  17619. }
  17620. /**
  17621. * Flag to indicate that this attribute has changed and should be re-sent to
  17622. * the GPU. Set this to `true` when you modify the value of the array.
  17623. *
  17624. * @type {number}
  17625. * @default false
  17626. * @param {boolean} value
  17627. */
  17628. set needsUpdate( value ) {
  17629. this.data.needsUpdate = value;
  17630. }
  17631. /**
  17632. * Applies the given 4x4 matrix to the given attribute. Only works with
  17633. * item size `3`.
  17634. *
  17635. * @param {Matrix4} m - The matrix to apply.
  17636. * @return {InterleavedBufferAttribute} A reference to this instance.
  17637. */
  17638. applyMatrix4( m ) {
  17639. for ( let i = 0, l = this.data.count; i < l; i ++ ) {
  17640. _vector$7.fromBufferAttribute( this, i );
  17641. _vector$7.applyMatrix4( m );
  17642. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17643. }
  17644. return this;
  17645. }
  17646. /**
  17647. * Applies the given 3x3 normal matrix to the given attribute. Only works with
  17648. * item size `3`.
  17649. *
  17650. * @param {Matrix3} m - The normal matrix to apply.
  17651. * @return {InterleavedBufferAttribute} A reference to this instance.
  17652. */
  17653. applyNormalMatrix( m ) {
  17654. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17655. _vector$7.fromBufferAttribute( this, i );
  17656. _vector$7.applyNormalMatrix( m );
  17657. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17658. }
  17659. return this;
  17660. }
  17661. /**
  17662. * Applies the given 4x4 matrix to the given attribute. Only works with
  17663. * item size `3` and with direction vectors.
  17664. *
  17665. * @param {Matrix4} m - The matrix to apply.
  17666. * @return {InterleavedBufferAttribute} A reference to this instance.
  17667. */
  17668. transformDirection( m ) {
  17669. for ( let i = 0, l = this.count; i < l; i ++ ) {
  17670. _vector$7.fromBufferAttribute( this, i );
  17671. _vector$7.transformDirection( m );
  17672. this.setXYZ( i, _vector$7.x, _vector$7.y, _vector$7.z );
  17673. }
  17674. return this;
  17675. }
  17676. /**
  17677. * Returns the given component of the vector at the given index.
  17678. *
  17679. * @param {number} index - The index into the buffer attribute.
  17680. * @param {number} component - The component index.
  17681. * @return {number} The returned value.
  17682. */
  17683. getComponent( index, component ) {
  17684. let value = this.array[ index * this.data.stride + this.offset + component ];
  17685. if ( this.normalized ) value = denormalize( value, this.array );
  17686. return value;
  17687. }
  17688. /**
  17689. * Sets the given value to the given component of the vector at the given index.
  17690. *
  17691. * @param {number} index - The index into the buffer attribute.
  17692. * @param {number} component - The component index.
  17693. * @param {number} value - The value to set.
  17694. * @return {InterleavedBufferAttribute} A reference to this instance.
  17695. */
  17696. setComponent( index, component, value ) {
  17697. if ( this.normalized ) value = normalize( value, this.array );
  17698. this.data.array[ index * this.data.stride + this.offset + component ] = value;
  17699. return this;
  17700. }
  17701. /**
  17702. * Sets the x component of the vector at the given index.
  17703. *
  17704. * @param {number} index - The index into the buffer attribute.
  17705. * @param {number} x - The value to set.
  17706. * @return {InterleavedBufferAttribute} A reference to this instance.
  17707. */
  17708. setX( index, x ) {
  17709. if ( this.normalized ) x = normalize( x, this.array );
  17710. this.data.array[ index * this.data.stride + this.offset ] = x;
  17711. return this;
  17712. }
  17713. /**
  17714. * Sets the y component of the vector at the given index.
  17715. *
  17716. * @param {number} index - The index into the buffer attribute.
  17717. * @param {number} y - The value to set.
  17718. * @return {InterleavedBufferAttribute} A reference to this instance.
  17719. */
  17720. setY( index, y ) {
  17721. if ( this.normalized ) y = normalize( y, this.array );
  17722. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  17723. return this;
  17724. }
  17725. /**
  17726. * Sets the z component of the vector at the given index.
  17727. *
  17728. * @param {number} index - The index into the buffer attribute.
  17729. * @param {number} z - The value to set.
  17730. * @return {InterleavedBufferAttribute} A reference to this instance.
  17731. */
  17732. setZ( index, z ) {
  17733. if ( this.normalized ) z = normalize( z, this.array );
  17734. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  17735. return this;
  17736. }
  17737. /**
  17738. * Sets the w component of the vector at the given index.
  17739. *
  17740. * @param {number} index - The index into the buffer attribute.
  17741. * @param {number} w - The value to set.
  17742. * @return {InterleavedBufferAttribute} A reference to this instance.
  17743. */
  17744. setW( index, w ) {
  17745. if ( this.normalized ) w = normalize( w, this.array );
  17746. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  17747. return this;
  17748. }
  17749. /**
  17750. * Returns the x component of the vector at the given index.
  17751. *
  17752. * @param {number} index - The index into the buffer attribute.
  17753. * @return {number} The x component.
  17754. */
  17755. getX( index ) {
  17756. let x = this.data.array[ index * this.data.stride + this.offset ];
  17757. if ( this.normalized ) x = denormalize( x, this.array );
  17758. return x;
  17759. }
  17760. /**
  17761. * Returns the y component of the vector at the given index.
  17762. *
  17763. * @param {number} index - The index into the buffer attribute.
  17764. * @return {number} The y component.
  17765. */
  17766. getY( index ) {
  17767. let y = this.data.array[ index * this.data.stride + this.offset + 1 ];
  17768. if ( this.normalized ) y = denormalize( y, this.array );
  17769. return y;
  17770. }
  17771. /**
  17772. * Returns the z component of the vector at the given index.
  17773. *
  17774. * @param {number} index - The index into the buffer attribute.
  17775. * @return {number} The z component.
  17776. */
  17777. getZ( index ) {
  17778. let z = this.data.array[ index * this.data.stride + this.offset + 2 ];
  17779. if ( this.normalized ) z = denormalize( z, this.array );
  17780. return z;
  17781. }
  17782. /**
  17783. * Returns the w component of the vector at the given index.
  17784. *
  17785. * @param {number} index - The index into the buffer attribute.
  17786. * @return {number} The w component.
  17787. */
  17788. getW( index ) {
  17789. let w = this.data.array[ index * this.data.stride + this.offset + 3 ];
  17790. if ( this.normalized ) w = denormalize( w, this.array );
  17791. return w;
  17792. }
  17793. /**
  17794. * Sets the x and y component of the vector at the given index.
  17795. *
  17796. * @param {number} index - The index into the buffer attribute.
  17797. * @param {number} x - The value for the x component to set.
  17798. * @param {number} y - The value for the y component to set.
  17799. * @return {InterleavedBufferAttribute} A reference to this instance.
  17800. */
  17801. setXY( index, x, y ) {
  17802. index = index * this.data.stride + this.offset;
  17803. if ( this.normalized ) {
  17804. x = normalize( x, this.array );
  17805. y = normalize( y, this.array );
  17806. }
  17807. this.data.array[ index + 0 ] = x;
  17808. this.data.array[ index + 1 ] = y;
  17809. return this;
  17810. }
  17811. /**
  17812. * Sets the x, y and z component of the vector at the given index.
  17813. *
  17814. * @param {number} index - The index into the buffer attribute.
  17815. * @param {number} x - The value for the x component to set.
  17816. * @param {number} y - The value for the y component to set.
  17817. * @param {number} z - The value for the z component to set.
  17818. * @return {InterleavedBufferAttribute} A reference to this instance.
  17819. */
  17820. setXYZ( index, x, y, z ) {
  17821. index = index * this.data.stride + this.offset;
  17822. if ( this.normalized ) {
  17823. x = normalize( x, this.array );
  17824. y = normalize( y, this.array );
  17825. z = normalize( z, this.array );
  17826. }
  17827. this.data.array[ index + 0 ] = x;
  17828. this.data.array[ index + 1 ] = y;
  17829. this.data.array[ index + 2 ] = z;
  17830. return this;
  17831. }
  17832. /**
  17833. * Sets the x, y, z and w component of the vector at the given index.
  17834. *
  17835. * @param {number} index - The index into the buffer attribute.
  17836. * @param {number} x - The value for the x component to set.
  17837. * @param {number} y - The value for the y component to set.
  17838. * @param {number} z - The value for the z component to set.
  17839. * @param {number} w - The value for the w component to set.
  17840. * @return {InterleavedBufferAttribute} A reference to this instance.
  17841. */
  17842. setXYZW( index, x, y, z, w ) {
  17843. index = index * this.data.stride + this.offset;
  17844. if ( this.normalized ) {
  17845. x = normalize( x, this.array );
  17846. y = normalize( y, this.array );
  17847. z = normalize( z, this.array );
  17848. w = normalize( w, this.array );
  17849. }
  17850. this.data.array[ index + 0 ] = x;
  17851. this.data.array[ index + 1 ] = y;
  17852. this.data.array[ index + 2 ] = z;
  17853. this.data.array[ index + 3 ] = w;
  17854. return this;
  17855. }
  17856. /**
  17857. * Returns a new buffer attribute with copied values from this instance.
  17858. *
  17859. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17860. *
  17861. * @param {Object} [data] - An object with interleaved buffers that allows to retain the interleaved property.
  17862. * @return {BufferAttribute|InterleavedBufferAttribute} A clone of this instance.
  17863. */
  17864. clone( data ) {
  17865. if ( data === undefined ) {
  17866. log( 'InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.' );
  17867. const array = [];
  17868. for ( let i = 0; i < this.count; i ++ ) {
  17869. const index = i * this.data.stride + this.offset;
  17870. for ( let j = 0; j < this.itemSize; j ++ ) {
  17871. array.push( this.data.array[ index + j ] );
  17872. }
  17873. }
  17874. return new BufferAttribute( new this.array.constructor( array ), this.itemSize, this.normalized );
  17875. } else {
  17876. if ( data.interleavedBuffers === undefined ) {
  17877. data.interleavedBuffers = {};
  17878. }
  17879. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17880. data.interleavedBuffers[ this.data.uuid ] = this.data.clone( data );
  17881. }
  17882. return new InterleavedBufferAttribute( data.interleavedBuffers[ this.data.uuid ], this.itemSize, this.offset, this.normalized );
  17883. }
  17884. }
  17885. /**
  17886. * Serializes the buffer attribute into JSON.
  17887. *
  17888. * If no parameter is provided, cloning an interleaved buffer attribute will de-interleave buffer data.
  17889. *
  17890. * @param {Object} [data] - An optional value holding meta information about the serialization.
  17891. * @return {Object} A JSON object representing the serialized buffer attribute.
  17892. */
  17893. toJSON( data ) {
  17894. if ( data === undefined ) {
  17895. log( 'InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.' );
  17896. const array = [];
  17897. for ( let i = 0; i < this.count; i ++ ) {
  17898. const index = i * this.data.stride + this.offset;
  17899. for ( let j = 0; j < this.itemSize; j ++ ) {
  17900. array.push( this.data.array[ index + j ] );
  17901. }
  17902. }
  17903. // de-interleave data and save it as an ordinary buffer attribute for now
  17904. return {
  17905. itemSize: this.itemSize,
  17906. type: this.array.constructor.name,
  17907. array: array,
  17908. normalized: this.normalized
  17909. };
  17910. } else {
  17911. // save as true interleaved attribute
  17912. if ( data.interleavedBuffers === undefined ) {
  17913. data.interleavedBuffers = {};
  17914. }
  17915. if ( data.interleavedBuffers[ this.data.uuid ] === undefined ) {
  17916. data.interleavedBuffers[ this.data.uuid ] = this.data.toJSON( data );
  17917. }
  17918. return {
  17919. isInterleavedBufferAttribute: true,
  17920. itemSize: this.itemSize,
  17921. data: this.data.uuid,
  17922. offset: this.offset,
  17923. normalized: this.normalized
  17924. };
  17925. }
  17926. }
  17927. }
  17928. /**
  17929. * A material for rendering instances of {@link Sprite}.
  17930. *
  17931. * ```js
  17932. * const map = new THREE.TextureLoader().load( 'textures/sprite.png' );
  17933. * const material = new THREE.SpriteMaterial( { map: map, color: 0xffffff } );
  17934. *
  17935. * const sprite = new THREE.Sprite( material );
  17936. * sprite.scale.set(200, 200, 1)
  17937. * scene.add( sprite );
  17938. * ```
  17939. *
  17940. * @augments Material
  17941. */
  17942. class SpriteMaterial extends Material {
  17943. /**
  17944. * Constructs a new sprite material.
  17945. *
  17946. * @param {Object} [parameters] - An object with one or more properties
  17947. * defining the material's appearance. Any property of the material
  17948. * (including any property from inherited materials) can be passed
  17949. * in here. Color values can be passed any type of value accepted
  17950. * by {@link Color#set}.
  17951. */
  17952. constructor( parameters ) {
  17953. super();
  17954. /**
  17955. * This flag can be used for type testing.
  17956. *
  17957. * @type {boolean}
  17958. * @readonly
  17959. * @default true
  17960. */
  17961. this.isSpriteMaterial = true;
  17962. this.type = 'SpriteMaterial';
  17963. /**
  17964. * Color of the material.
  17965. *
  17966. * @type {Color}
  17967. * @default (1,1,1)
  17968. */
  17969. this.color = new Color( 0xffffff );
  17970. /**
  17971. * The color map. May optionally include an alpha channel, typically combined
  17972. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  17973. * color is modulated by the diffuse `color`.
  17974. *
  17975. * @type {?Texture}
  17976. * @default null
  17977. */
  17978. this.map = null;
  17979. /**
  17980. * The alpha map is a grayscale texture that controls the opacity across the
  17981. * surface (black: fully transparent; white: fully opaque).
  17982. *
  17983. * Only the color of the texture is used, ignoring the alpha channel if one
  17984. * exists. For RGB and RGBA textures, the renderer will use the green channel
  17985. * when sampling this texture due to the extra bit of precision provided for
  17986. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  17987. * luminance/alpha textures will also still work as expected.
  17988. *
  17989. * @type {?Texture}
  17990. * @default null
  17991. */
  17992. this.alphaMap = null;
  17993. /**
  17994. * The rotation of the sprite in radians.
  17995. *
  17996. * @type {number}
  17997. * @default 0
  17998. */
  17999. this.rotation = 0;
  18000. /**
  18001. * Specifies whether size of the sprite is attenuated by the camera depth (perspective camera only).
  18002. *
  18003. * @type {boolean}
  18004. * @default true
  18005. */
  18006. this.sizeAttenuation = true;
  18007. /**
  18008. * Overwritten since sprite materials are transparent
  18009. * by default.
  18010. *
  18011. * @type {boolean}
  18012. * @default true
  18013. */
  18014. this.transparent = true;
  18015. /**
  18016. * Whether the material is affected by fog or not.
  18017. *
  18018. * @type {boolean}
  18019. * @default true
  18020. */
  18021. this.fog = true;
  18022. this.setValues( parameters );
  18023. }
  18024. copy( source ) {
  18025. super.copy( source );
  18026. this.color.copy( source.color );
  18027. this.map = source.map;
  18028. this.alphaMap = source.alphaMap;
  18029. this.rotation = source.rotation;
  18030. this.sizeAttenuation = source.sizeAttenuation;
  18031. this.fog = source.fog;
  18032. return this;
  18033. }
  18034. }
  18035. let _geometry;
  18036. const _intersectPoint = /*@__PURE__*/ new Vector3();
  18037. const _worldScale = /*@__PURE__*/ new Vector3();
  18038. const _mvPosition = /*@__PURE__*/ new Vector3();
  18039. const _alignedPosition = /*@__PURE__*/ new Vector2();
  18040. const _rotatedPosition = /*@__PURE__*/ new Vector2();
  18041. const _viewWorldMatrix = /*@__PURE__*/ new Matrix4();
  18042. const _vA = /*@__PURE__*/ new Vector3();
  18043. const _vB = /*@__PURE__*/ new Vector3();
  18044. const _vC = /*@__PURE__*/ new Vector3();
  18045. const _uvA = /*@__PURE__*/ new Vector2();
  18046. const _uvB = /*@__PURE__*/ new Vector2();
  18047. const _uvC = /*@__PURE__*/ new Vector2();
  18048. /**
  18049. * A sprite is a plane that always faces towards the camera, generally with a
  18050. * partially transparent texture applied.
  18051. *
  18052. * Sprites do not cast shadows, setting {@link Object3D#castShadow} to `true` will
  18053. * have no effect.
  18054. *
  18055. * ```js
  18056. * const map = new THREE.TextureLoader().load( 'sprite.png' );
  18057. * const material = new THREE.SpriteMaterial( { map: map } );
  18058. *
  18059. * const sprite = new THREE.Sprite( material );
  18060. * scene.add( sprite );
  18061. * ```
  18062. *
  18063. * @augments Object3D
  18064. */
  18065. class Sprite extends Object3D {
  18066. /**
  18067. * Constructs a new sprite.
  18068. *
  18069. * @param {(SpriteMaterial|SpriteNodeMaterial)} [material] - The sprite material.
  18070. */
  18071. constructor( material = new SpriteMaterial() ) {
  18072. super();
  18073. /**
  18074. * This flag can be used for type testing.
  18075. *
  18076. * @type {boolean}
  18077. * @readonly
  18078. * @default true
  18079. */
  18080. this.isSprite = true;
  18081. this.type = 'Sprite';
  18082. if ( _geometry === undefined ) {
  18083. _geometry = new BufferGeometry();
  18084. const float32Array = new Float32Array( [
  18085. -0.5, -0.5, 0, 0, 0,
  18086. 0.5, -0.5, 0, 1, 0,
  18087. 0.5, 0.5, 0, 1, 1,
  18088. -0.5, 0.5, 0, 0, 1
  18089. ] );
  18090. const interleavedBuffer = new InterleavedBuffer( float32Array, 5 );
  18091. _geometry.setIndex( [ 0, 1, 2, 0, 2, 3 ] );
  18092. _geometry.setAttribute( 'position', new InterleavedBufferAttribute( interleavedBuffer, 3, 0, false ) );
  18093. _geometry.setAttribute( 'uv', new InterleavedBufferAttribute( interleavedBuffer, 2, 3, false ) );
  18094. }
  18095. /**
  18096. * The sprite geometry.
  18097. *
  18098. * @type {BufferGeometry}
  18099. */
  18100. this.geometry = _geometry;
  18101. /**
  18102. * The sprite material.
  18103. *
  18104. * @type {(SpriteMaterial|SpriteNodeMaterial)}
  18105. */
  18106. this.material = material;
  18107. /**
  18108. * The sprite's anchor point, and the point around which the sprite rotates.
  18109. * A value of `(0.5, 0.5)` corresponds to the midpoint of the sprite. A value
  18110. * of `(0, 0)` corresponds to the lower left corner of the sprite.
  18111. *
  18112. * @type {Vector2}
  18113. * @default (0.5,0.5)
  18114. */
  18115. this.center = new Vector2( 0.5, 0.5 );
  18116. /**
  18117. * The number of instances of this sprite.
  18118. * Can only be used with {@link WebGPURenderer}.
  18119. *
  18120. * @type {number}
  18121. * @default 1
  18122. */
  18123. this.count = 1;
  18124. }
  18125. /**
  18126. * Computes intersection points between a casted ray and this sprite.
  18127. *
  18128. * @param {Raycaster} raycaster - The raycaster.
  18129. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18130. */
  18131. raycast( raycaster, intersects ) {
  18132. if ( raycaster.camera === null ) {
  18133. error( 'Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.' );
  18134. }
  18135. _worldScale.setFromMatrixScale( this.matrixWorld );
  18136. _viewWorldMatrix.copy( raycaster.camera.matrixWorld );
  18137. this.modelViewMatrix.multiplyMatrices( raycaster.camera.matrixWorldInverse, this.matrixWorld );
  18138. _mvPosition.setFromMatrixPosition( this.modelViewMatrix );
  18139. if ( raycaster.camera.isPerspectiveCamera && this.material.sizeAttenuation === false ) {
  18140. _worldScale.multiplyScalar( - _mvPosition.z );
  18141. }
  18142. const rotation = this.material.rotation;
  18143. let sin, cos;
  18144. if ( rotation !== 0 ) {
  18145. cos = Math.cos( rotation );
  18146. sin = Math.sin( rotation );
  18147. }
  18148. const center = this.center;
  18149. transformVertex( _vA.set( -0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18150. transformVertex( _vB.set( 0.5, -0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18151. transformVertex( _vC.set( 0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18152. _uvA.set( 0, 0 );
  18153. _uvB.set( 1, 0 );
  18154. _uvC.set( 1, 1 );
  18155. // check first triangle
  18156. let intersect = raycaster.ray.intersectTriangle( _vA, _vB, _vC, false, _intersectPoint );
  18157. if ( intersect === null ) {
  18158. // check second triangle
  18159. transformVertex( _vB.set( -0.5, 0.5, 0 ), _mvPosition, center, _worldScale, sin, cos );
  18160. _uvB.set( 0, 1 );
  18161. intersect = raycaster.ray.intersectTriangle( _vA, _vC, _vB, false, _intersectPoint );
  18162. if ( intersect === null ) {
  18163. return;
  18164. }
  18165. }
  18166. const distance = raycaster.ray.origin.distanceTo( _intersectPoint );
  18167. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18168. intersects.push( {
  18169. distance: distance,
  18170. point: _intersectPoint.clone(),
  18171. uv: Triangle.getInterpolation( _intersectPoint, _vA, _vB, _vC, _uvA, _uvB, _uvC, new Vector2() ),
  18172. face: null,
  18173. object: this
  18174. } );
  18175. }
  18176. copy( source, recursive ) {
  18177. super.copy( source, recursive );
  18178. if ( source.center !== undefined ) this.center.copy( source.center );
  18179. this.material = source.material;
  18180. return this;
  18181. }
  18182. }
  18183. function transformVertex( vertexPosition, mvPosition, center, scale, sin, cos ) {
  18184. // compute position in camera space
  18185. _alignedPosition.subVectors( vertexPosition, center ).addScalar( 0.5 ).multiply( scale );
  18186. // to check if rotation is not zero
  18187. if ( sin !== undefined ) {
  18188. _rotatedPosition.x = ( cos * _alignedPosition.x ) - ( sin * _alignedPosition.y );
  18189. _rotatedPosition.y = ( sin * _alignedPosition.x ) + ( cos * _alignedPosition.y );
  18190. } else {
  18191. _rotatedPosition.copy( _alignedPosition );
  18192. }
  18193. vertexPosition.copy( mvPosition );
  18194. vertexPosition.x += _rotatedPosition.x;
  18195. vertexPosition.y += _rotatedPosition.y;
  18196. // transform to world space
  18197. vertexPosition.applyMatrix4( _viewWorldMatrix );
  18198. }
  18199. const _v1$2 = /*@__PURE__*/ new Vector3();
  18200. const _v2$1 = /*@__PURE__*/ new Vector3();
  18201. /**
  18202. * A component for providing a basic Level of Detail (LOD) mechanism.
  18203. *
  18204. * Every LOD level is associated with an object, and rendering can be switched
  18205. * between them at the distances specified. Typically you would create, say,
  18206. * three meshes, one for far away (low detail), one for mid range (medium
  18207. * detail) and one for close up (high detail).
  18208. *
  18209. * ```js
  18210. * const lod = new THREE.LOD();
  18211. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  18212. *
  18213. * //Create spheres with 3 levels of detail and create new LOD levels for them
  18214. * for( let i = 0; i < 3; i++ ) {
  18215. *
  18216. * const geometry = new THREE.IcosahedronGeometry( 10, 3 - i );
  18217. * const mesh = new THREE.Mesh( geometry, material );
  18218. * lod.addLevel( mesh, i * 75 );
  18219. *
  18220. * }
  18221. *
  18222. * scene.add( lod );
  18223. * ```
  18224. *
  18225. * @augments Object3D
  18226. */
  18227. class LOD extends Object3D {
  18228. /**
  18229. * Constructs a new LOD.
  18230. */
  18231. constructor() {
  18232. super();
  18233. /**
  18234. * This flag can be used for type testing.
  18235. *
  18236. * @type {boolean}
  18237. * @readonly
  18238. * @default true
  18239. */
  18240. this.isLOD = true;
  18241. /**
  18242. * The current LOD index.
  18243. *
  18244. * @private
  18245. * @type {number}
  18246. * @default 0
  18247. */
  18248. this._currentLevel = 0;
  18249. this.type = 'LOD';
  18250. Object.defineProperties( this, {
  18251. /**
  18252. * This array holds the LOD levels.
  18253. *
  18254. * @name LOD#levels
  18255. * @type {Array<{object:Object3D,distance:number,hysteresis:number}>}
  18256. */
  18257. levels: {
  18258. enumerable: true,
  18259. value: []
  18260. }
  18261. } );
  18262. /**
  18263. * Whether the LOD object is updated automatically by the renderer per frame
  18264. * or not. If set to `false`, you have to call {@link LOD#update} in the
  18265. * render loop by yourself.
  18266. *
  18267. * @type {boolean}
  18268. * @default true
  18269. */
  18270. this.autoUpdate = true;
  18271. }
  18272. copy( source ) {
  18273. super.copy( source, false );
  18274. const levels = source.levels;
  18275. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18276. const level = levels[ i ];
  18277. this.addLevel( level.object.clone(), level.distance, level.hysteresis );
  18278. }
  18279. this.autoUpdate = source.autoUpdate;
  18280. return this;
  18281. }
  18282. /**
  18283. * Adds a mesh that will display at a certain distance and greater. Typically
  18284. * the further away the distance, the lower the detail on the mesh.
  18285. *
  18286. * @param {Object3D} object - The 3D object to display at this level.
  18287. * @param {number} [distance=0] - The distance at which to display this level of detail.
  18288. * @param {number} [hysteresis=0] - Threshold used to avoid flickering at LOD boundaries, as a fraction of distance.
  18289. * @return {LOD} A reference to this instance.
  18290. */
  18291. addLevel( object, distance = 0, hysteresis = 0 ) {
  18292. distance = Math.abs( distance );
  18293. const levels = this.levels;
  18294. let l;
  18295. for ( l = 0; l < levels.length; l ++ ) {
  18296. if ( distance < levels[ l ].distance ) {
  18297. break;
  18298. }
  18299. }
  18300. levels.splice( l, 0, { distance: distance, hysteresis: hysteresis, object: object } );
  18301. this.add( object );
  18302. return this;
  18303. }
  18304. /**
  18305. * Removes an existing level, based on the distance from the camera.
  18306. * Returns `true` when the level has been removed. Otherwise `false`.
  18307. *
  18308. * @param {number} distance - Distance of the level to remove.
  18309. * @return {boolean} Whether the level has been removed or not.
  18310. */
  18311. removeLevel( distance ) {
  18312. const levels = this.levels;
  18313. for ( let i = 0; i < levels.length; i ++ ) {
  18314. if ( levels[ i ].distance === distance ) {
  18315. const removedElements = levels.splice( i, 1 );
  18316. this.remove( removedElements[ 0 ].object );
  18317. return true;
  18318. }
  18319. }
  18320. return false;
  18321. }
  18322. /**
  18323. * Returns the currently active LOD level index.
  18324. *
  18325. * @return {number} The current active LOD level index.
  18326. */
  18327. getCurrentLevel() {
  18328. return this._currentLevel;
  18329. }
  18330. /**
  18331. * Returns a reference to the first 3D object that is greater than
  18332. * the given distance.
  18333. *
  18334. * @param {number} distance - The LOD distance.
  18335. * @return {?Object3D} The found 3D object. `null` if no 3D object has been found.
  18336. */
  18337. getObjectForDistance( distance ) {
  18338. const levels = this.levels;
  18339. if ( levels.length > 0 ) {
  18340. let i, l;
  18341. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18342. let levelDistance = levels[ i ].distance;
  18343. if ( levels[ i ].object.visible ) {
  18344. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18345. }
  18346. if ( distance < levelDistance ) {
  18347. break;
  18348. }
  18349. }
  18350. return levels[ i - 1 ].object;
  18351. }
  18352. return null;
  18353. }
  18354. /**
  18355. * Computes intersection points between a casted ray and this LOD.
  18356. *
  18357. * @param {Raycaster} raycaster - The raycaster.
  18358. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  18359. */
  18360. raycast( raycaster, intersects ) {
  18361. const levels = this.levels;
  18362. if ( levels.length > 0 ) {
  18363. _v1$2.setFromMatrixPosition( this.matrixWorld );
  18364. const distance = raycaster.ray.origin.distanceTo( _v1$2 );
  18365. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18366. }
  18367. }
  18368. /**
  18369. * Updates the LOD by computing which LOD level should be visible according
  18370. * to the current distance of the given camera.
  18371. *
  18372. * @param {Camera} camera - The camera the scene is rendered with.
  18373. */
  18374. update( camera ) {
  18375. const levels = this.levels;
  18376. if ( levels.length > 1 ) {
  18377. _v1$2.setFromMatrixPosition( camera.matrixWorld );
  18378. _v2$1.setFromMatrixPosition( this.matrixWorld );
  18379. const distance = _v1$2.distanceTo( _v2$1 ) / camera.zoom;
  18380. levels[ 0 ].object.visible = true;
  18381. let i, l;
  18382. for ( i = 1, l = levels.length; i < l; i ++ ) {
  18383. let levelDistance = levels[ i ].distance;
  18384. if ( levels[ i ].object.visible ) {
  18385. levelDistance -= levelDistance * levels[ i ].hysteresis;
  18386. }
  18387. if ( distance >= levelDistance ) {
  18388. levels[ i - 1 ].object.visible = false;
  18389. levels[ i ].object.visible = true;
  18390. } else {
  18391. break;
  18392. }
  18393. }
  18394. this._currentLevel = i - 1;
  18395. for ( ; i < l; i ++ ) {
  18396. levels[ i ].object.visible = false;
  18397. }
  18398. }
  18399. }
  18400. toJSON( meta ) {
  18401. const data = super.toJSON( meta );
  18402. if ( this.autoUpdate === false ) data.object.autoUpdate = false;
  18403. data.object.levels = [];
  18404. const levels = this.levels;
  18405. for ( let i = 0, l = levels.length; i < l; i ++ ) {
  18406. const level = levels[ i ];
  18407. data.object.levels.push( {
  18408. object: level.object.uuid,
  18409. distance: level.distance,
  18410. hysteresis: level.hysteresis
  18411. } );
  18412. }
  18413. return data;
  18414. }
  18415. }
  18416. const _basePosition = /*@__PURE__*/ new Vector3();
  18417. const _skinIndex = /*@__PURE__*/ new Vector4();
  18418. const _skinWeight = /*@__PURE__*/ new Vector4();
  18419. const _vector3 = /*@__PURE__*/ new Vector3();
  18420. const _matrix4 = /*@__PURE__*/ new Matrix4();
  18421. const _vertex = /*@__PURE__*/ new Vector3();
  18422. const _sphere$5 = /*@__PURE__*/ new Sphere();
  18423. const _inverseMatrix$2 = /*@__PURE__*/ new Matrix4();
  18424. const _ray$2 = /*@__PURE__*/ new Ray();
  18425. /**
  18426. * A mesh that has a {@link Skeleton} that can then be used to animate the
  18427. * vertices of the geometry with skinning/skeleton animation.
  18428. *
  18429. * Next to a valid skeleton, the skinned mesh requires skin indices and weights
  18430. * as buffer attributes in its geometry. These attribute define which bones affect a single
  18431. * vertex to a certain extend.
  18432. *
  18433. * Typically skinned meshes are not created manually but loaders like {@link GLTFLoader}
  18434. * or {@link FBXLoader } import respective models.
  18435. *
  18436. * @augments Mesh
  18437. * @demo scenes/bones-browser.html
  18438. */
  18439. class SkinnedMesh extends Mesh {
  18440. /**
  18441. * Constructs a new skinned mesh.
  18442. *
  18443. * @param {BufferGeometry} [geometry] - The mesh geometry.
  18444. * @param {Material|Array<Material>} [material] - The mesh material.
  18445. */
  18446. constructor( geometry, material ) {
  18447. super( geometry, material );
  18448. /**
  18449. * This flag can be used for type testing.
  18450. *
  18451. * @type {boolean}
  18452. * @readonly
  18453. * @default true
  18454. */
  18455. this.isSkinnedMesh = true;
  18456. this.type = 'SkinnedMesh';
  18457. /**
  18458. * `AttachedBindMode` means the skinned mesh shares the same world space as the skeleton.
  18459. * This is not true when using `DetachedBindMode` which is useful when sharing a skeleton
  18460. * across multiple skinned meshes.
  18461. *
  18462. * @type {(AttachedBindMode|DetachedBindMode)}
  18463. * @default AttachedBindMode
  18464. */
  18465. this.bindMode = AttachedBindMode;
  18466. /**
  18467. * The base matrix that is used for the bound bone transforms.
  18468. *
  18469. * @type {Matrix4}
  18470. */
  18471. this.bindMatrix = new Matrix4();
  18472. /**
  18473. * The base matrix that is used for resetting the bound bone transforms.
  18474. *
  18475. * @type {Matrix4}
  18476. */
  18477. this.bindMatrixInverse = new Matrix4();
  18478. /**
  18479. * The bounding box of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingBox}.
  18480. *
  18481. * @type {?Box3}
  18482. * @default null
  18483. */
  18484. this.boundingBox = null;
  18485. /**
  18486. * The bounding sphere of the skinned mesh. Can be computed via {@link SkinnedMesh#computeBoundingSphere}.
  18487. *
  18488. * @type {?Sphere}
  18489. * @default null
  18490. */
  18491. this.boundingSphere = null;
  18492. }
  18493. /**
  18494. * Computes the bounding box of the skinned mesh, and updates {@link SkinnedMesh#boundingBox}.
  18495. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  18496. * If the skinned mesh is animated, the bounding box should be recomputed per frame in order to reflect
  18497. * the current animation state.
  18498. */
  18499. computeBoundingBox() {
  18500. const geometry = this.geometry;
  18501. if ( this.boundingBox === null ) {
  18502. this.boundingBox = new Box3();
  18503. }
  18504. this.boundingBox.makeEmpty();
  18505. const positionAttribute = geometry.getAttribute( 'position' );
  18506. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18507. this.getVertexPosition( i, _vertex );
  18508. this.boundingBox.expandByPoint( _vertex );
  18509. }
  18510. }
  18511. /**
  18512. * Computes the bounding sphere of the skinned mesh, and updates {@link SkinnedMesh#boundingSphere}.
  18513. * The bounding sphere is automatically computed by the engine once when it is needed, e.g., for ray casting
  18514. * and view frustum culling. If the skinned mesh is animated, the bounding sphere should be recomputed
  18515. * per frame in order to reflect the current animation state.
  18516. */
  18517. computeBoundingSphere() {
  18518. const geometry = this.geometry;
  18519. if ( this.boundingSphere === null ) {
  18520. this.boundingSphere = new Sphere();
  18521. }
  18522. this.boundingSphere.makeEmpty();
  18523. const positionAttribute = geometry.getAttribute( 'position' );
  18524. for ( let i = 0; i < positionAttribute.count; i ++ ) {
  18525. this.getVertexPosition( i, _vertex );
  18526. this.boundingSphere.expandByPoint( _vertex );
  18527. }
  18528. }
  18529. copy( source, recursive ) {
  18530. super.copy( source, recursive );
  18531. this.bindMode = source.bindMode;
  18532. this.bindMatrix.copy( source.bindMatrix );
  18533. this.bindMatrixInverse.copy( source.bindMatrixInverse );
  18534. this.skeleton = source.skeleton;
  18535. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  18536. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  18537. return this;
  18538. }
  18539. raycast( raycaster, intersects ) {
  18540. const material = this.material;
  18541. const matrixWorld = this.matrixWorld;
  18542. if ( material === undefined ) return;
  18543. // test with bounding sphere in world space
  18544. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  18545. _sphere$5.copy( this.boundingSphere );
  18546. _sphere$5.applyMatrix4( matrixWorld );
  18547. if ( raycaster.ray.intersectsSphere( _sphere$5 ) === false ) return;
  18548. // convert ray to local space of skinned mesh
  18549. _inverseMatrix$2.copy( matrixWorld ).invert();
  18550. _ray$2.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$2 );
  18551. // test with bounding box in local space
  18552. if ( this.boundingBox !== null ) {
  18553. if ( _ray$2.intersectsBox( this.boundingBox ) === false ) return;
  18554. }
  18555. // test for intersections with geometry
  18556. this._computeIntersections( raycaster, intersects, _ray$2 );
  18557. }
  18558. getVertexPosition( index, target ) {
  18559. super.getVertexPosition( index, target );
  18560. this.applyBoneTransform( index, target );
  18561. return target;
  18562. }
  18563. /**
  18564. * Binds the given skeleton to the skinned mesh.
  18565. *
  18566. * @param {Skeleton} skeleton - The skeleton to bind.
  18567. * @param {Matrix4} [bindMatrix] - The bind matrix. If no bind matrix is provided,
  18568. * the skinned mesh's world matrix will be used instead.
  18569. */
  18570. bind( skeleton, bindMatrix ) {
  18571. this.skeleton = skeleton;
  18572. if ( bindMatrix === undefined ) {
  18573. this.updateMatrixWorld( true );
  18574. this.skeleton.calculateInverses();
  18575. bindMatrix = this.matrixWorld;
  18576. }
  18577. this.bindMatrix.copy( bindMatrix );
  18578. this.bindMatrixInverse.copy( bindMatrix ).invert();
  18579. }
  18580. /**
  18581. * This method sets the skinned mesh in the rest pose).
  18582. */
  18583. pose() {
  18584. this.skeleton.pose();
  18585. }
  18586. /**
  18587. * Normalizes the skin weights which are defined as a buffer attribute
  18588. * in the skinned mesh's geometry.
  18589. */
  18590. normalizeSkinWeights() {
  18591. const vector = new Vector4();
  18592. const skinWeight = this.geometry.attributes.skinWeight;
  18593. for ( let i = 0, l = skinWeight.count; i < l; i ++ ) {
  18594. vector.fromBufferAttribute( skinWeight, i );
  18595. const scale = 1.0 / vector.manhattanLength();
  18596. if ( scale !== Infinity ) {
  18597. vector.multiplyScalar( scale );
  18598. } else {
  18599. vector.set( 1, 0, 0, 0 ); // do something reasonable
  18600. }
  18601. skinWeight.setXYZW( i, vector.x, vector.y, vector.z, vector.w );
  18602. }
  18603. }
  18604. updateMatrixWorld( force ) {
  18605. super.updateMatrixWorld( force );
  18606. if ( this.bindMode === AttachedBindMode ) {
  18607. this.bindMatrixInverse.copy( this.matrixWorld ).invert();
  18608. } else if ( this.bindMode === DetachedBindMode ) {
  18609. this.bindMatrixInverse.copy( this.bindMatrix ).invert();
  18610. } else {
  18611. warn( 'SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18612. }
  18613. }
  18614. /**
  18615. * Applies the bone transform associated with the given index to the given
  18616. * vertex position. Returns the updated vector.
  18617. *
  18618. * @param {number} index - The vertex index.
  18619. * @param {Vector3} target - The target object that is used to store the method's result.
  18620. * the skinned mesh's world matrix will be used instead.
  18621. * @return {Vector3} The updated vertex position.
  18622. */
  18623. applyBoneTransform( index, target ) {
  18624. const skeleton = this.skeleton;
  18625. const geometry = this.geometry;
  18626. _skinIndex.fromBufferAttribute( geometry.attributes.skinIndex, index );
  18627. _skinWeight.fromBufferAttribute( geometry.attributes.skinWeight, index );
  18628. _basePosition.copy( target ).applyMatrix4( this.bindMatrix );
  18629. target.set( 0, 0, 0 );
  18630. for ( let i = 0; i < 4; i ++ ) {
  18631. const weight = _skinWeight.getComponent( i );
  18632. if ( weight !== 0 ) {
  18633. const boneIndex = _skinIndex.getComponent( i );
  18634. _matrix4.multiplyMatrices( skeleton.bones[ boneIndex ].matrixWorld, skeleton.boneInverses[ boneIndex ] );
  18635. target.addScaledVector( _vector3.copy( _basePosition ).applyMatrix4( _matrix4 ), weight );
  18636. }
  18637. }
  18638. return target.applyMatrix4( this.bindMatrixInverse );
  18639. }
  18640. }
  18641. /**
  18642. * A bone which is part of a {@link Skeleton}. The skeleton in turn is used by
  18643. * the {@link SkinnedMesh}.
  18644. *
  18645. * ```js
  18646. * const root = new THREE.Bone();
  18647. * const child = new THREE.Bone();
  18648. *
  18649. * root.add( child );
  18650. * child.position.y = 5;
  18651. * ```
  18652. *
  18653. * @augments Object3D
  18654. */
  18655. class Bone extends Object3D {
  18656. /**
  18657. * Constructs a new bone.
  18658. */
  18659. constructor() {
  18660. super();
  18661. /**
  18662. * This flag can be used for type testing.
  18663. *
  18664. * @type {boolean}
  18665. * @readonly
  18666. * @default true
  18667. */
  18668. this.isBone = true;
  18669. this.type = 'Bone';
  18670. }
  18671. }
  18672. /**
  18673. * Creates a texture directly from raw buffer data.
  18674. *
  18675. * The interpretation of the data depends on type and format: If the type is
  18676. * `UnsignedByteType`, a `Uint8Array` will be useful for addressing the
  18677. * texel data. If the format is `RGBAFormat`, data needs four values for
  18678. * one texel; Red, Green, Blue and Alpha (typically the opacity).
  18679. *
  18680. * @augments Texture
  18681. */
  18682. class DataTexture extends Texture {
  18683. /**
  18684. * Constructs a new data texture.
  18685. *
  18686. * @param {?TypedArray} [data=null] - The buffer data.
  18687. * @param {number} [width=1] - The width of the texture.
  18688. * @param {number} [height=1] - The height of the texture.
  18689. * @param {number} [format=RGBAFormat] - The texture format.
  18690. * @param {number} [type=UnsignedByteType] - The texture type.
  18691. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  18692. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  18693. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  18694. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  18695. * @param {number} [minFilter=NearestFilter] - The min filter value.
  18696. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  18697. * @param {string} [colorSpace=NoColorSpace] - The color space.
  18698. */
  18699. constructor( data = null, width = 1, height = 1, format, type, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, colorSpace ) {
  18700. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  18701. /**
  18702. * This flag can be used for type testing.
  18703. *
  18704. * @type {boolean}
  18705. * @readonly
  18706. * @default true
  18707. */
  18708. this.isDataTexture = true;
  18709. /**
  18710. * The image definition of a data texture.
  18711. *
  18712. * @type {{data:TypedArray,width:number,height:number}}
  18713. */
  18714. this.image = { data: data, width: width, height: height };
  18715. /**
  18716. * Whether to generate mipmaps (if possible) for a texture.
  18717. *
  18718. * Overwritten and set to `false` by default.
  18719. *
  18720. * @type {boolean}
  18721. * @default false
  18722. */
  18723. this.generateMipmaps = false;
  18724. /**
  18725. * If set to `true`, the texture is flipped along the vertical axis when
  18726. * uploaded to the GPU.
  18727. *
  18728. * Overwritten and set to `false` by default.
  18729. *
  18730. * @type {boolean}
  18731. * @default false
  18732. */
  18733. this.flipY = false;
  18734. /**
  18735. * Specifies the alignment requirements for the start of each pixel row in memory.
  18736. *
  18737. * Overwritten and set to `1` by default.
  18738. *
  18739. * @type {boolean}
  18740. * @default 1
  18741. */
  18742. this.unpackAlignment = 1;
  18743. }
  18744. }
  18745. const _offsetMatrix = /*@__PURE__*/ new Matrix4();
  18746. const _identityMatrix = /*@__PURE__*/ new Matrix4();
  18747. /**
  18748. * Class for representing the armatures in `three.js`. The skeleton
  18749. * is defined by a hierarchy of bones.
  18750. *
  18751. * ```js
  18752. * const bones = [];
  18753. *
  18754. * const shoulder = new THREE.Bone();
  18755. * const elbow = new THREE.Bone();
  18756. * const hand = new THREE.Bone();
  18757. *
  18758. * shoulder.add( elbow );
  18759. * elbow.add( hand );
  18760. *
  18761. * bones.push( shoulder , elbow, hand);
  18762. *
  18763. * shoulder.position.y = -5;
  18764. * elbow.position.y = 0;
  18765. * hand.position.y = 5;
  18766. *
  18767. * const armSkeleton = new THREE.Skeleton( bones );
  18768. * ```
  18769. */
  18770. class Skeleton {
  18771. /**
  18772. * Constructs a new skeleton.
  18773. *
  18774. * @param {Array<Bone>} [bones] - An array of bones.
  18775. * @param {Array<Matrix4>} [boneInverses] - An array of bone inverse matrices.
  18776. * If not provided, these matrices will be computed automatically via {@link Skeleton#calculateInverses}.
  18777. */
  18778. constructor( bones = [], boneInverses = [] ) {
  18779. this.uuid = generateUUID();
  18780. /**
  18781. * An array of bones defining the skeleton.
  18782. *
  18783. * @type {Array<Bone>}
  18784. */
  18785. this.bones = bones.slice( 0 );
  18786. /**
  18787. * An array of bone inverse matrices.
  18788. *
  18789. * @type {Array<Matrix4>}
  18790. */
  18791. this.boneInverses = boneInverses;
  18792. /**
  18793. * An array buffer holding the bone data.
  18794. * Input data for {@link Skeleton#boneTexture}.
  18795. *
  18796. * @type {?Float32Array}
  18797. * @default null
  18798. */
  18799. this.boneMatrices = null;
  18800. /**
  18801. * A texture holding the bone data for use
  18802. * in the vertex shader.
  18803. *
  18804. * @type {?DataTexture}
  18805. * @default null
  18806. */
  18807. this.boneTexture = null;
  18808. this.init();
  18809. }
  18810. /**
  18811. * Initializes the skeleton. This method gets automatically called by the constructor
  18812. * but depending on how the skeleton is created it might be necessary to call this method
  18813. * manually.
  18814. */
  18815. init() {
  18816. const bones = this.bones;
  18817. const boneInverses = this.boneInverses;
  18818. this.boneMatrices = new Float32Array( bones.length * 16 );
  18819. // calculate inverse bone matrices if necessary
  18820. if ( boneInverses.length === 0 ) {
  18821. this.calculateInverses();
  18822. } else {
  18823. // handle special case
  18824. if ( bones.length !== boneInverses.length ) {
  18825. warn( 'Skeleton: Number of inverse bone matrices does not match amount of bones.' );
  18826. this.boneInverses = [];
  18827. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18828. this.boneInverses.push( new Matrix4() );
  18829. }
  18830. }
  18831. }
  18832. }
  18833. /**
  18834. * Computes the bone inverse matrices. This method resets {@link Skeleton#boneInverses}
  18835. * and fills it with new matrices.
  18836. */
  18837. calculateInverses() {
  18838. this.boneInverses.length = 0;
  18839. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18840. const inverse = new Matrix4();
  18841. if ( this.bones[ i ] ) {
  18842. inverse.copy( this.bones[ i ].matrixWorld ).invert();
  18843. }
  18844. this.boneInverses.push( inverse );
  18845. }
  18846. }
  18847. /**
  18848. * Resets the skeleton to the base pose.
  18849. */
  18850. pose() {
  18851. // recover the bind-time world matrices
  18852. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18853. const bone = this.bones[ i ];
  18854. if ( bone ) {
  18855. bone.matrixWorld.copy( this.boneInverses[ i ] ).invert();
  18856. }
  18857. }
  18858. // compute the local matrices, positions, rotations and scales
  18859. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18860. const bone = this.bones[ i ];
  18861. if ( bone ) {
  18862. if ( bone.parent && bone.parent.isBone ) {
  18863. bone.matrix.copy( bone.parent.matrixWorld ).invert();
  18864. bone.matrix.multiply( bone.matrixWorld );
  18865. } else {
  18866. bone.matrix.copy( bone.matrixWorld );
  18867. }
  18868. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18869. }
  18870. }
  18871. }
  18872. /**
  18873. * Resets the skeleton to the base pose.
  18874. */
  18875. update() {
  18876. const bones = this.bones;
  18877. const boneInverses = this.boneInverses;
  18878. const boneMatrices = this.boneMatrices;
  18879. const boneTexture = this.boneTexture;
  18880. // flatten bone matrices to array
  18881. for ( let i = 0, il = bones.length; i < il; i ++ ) {
  18882. // compute the offset between the current and the original transform
  18883. const matrix = bones[ i ] ? bones[ i ].matrixWorld : _identityMatrix;
  18884. _offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18885. _offsetMatrix.toArray( boneMatrices, i * 16 );
  18886. }
  18887. if ( boneTexture !== null ) {
  18888. boneTexture.needsUpdate = true;
  18889. }
  18890. }
  18891. /**
  18892. * Returns a new skeleton with copied values from this instance.
  18893. *
  18894. * @return {Skeleton} A clone of this instance.
  18895. */
  18896. clone() {
  18897. return new Skeleton( this.bones, this.boneInverses );
  18898. }
  18899. /**
  18900. * Computes a data texture for passing bone data to the vertex shader.
  18901. *
  18902. * @return {Skeleton} A reference of this instance.
  18903. */
  18904. computeBoneTexture() {
  18905. // layout (1 matrix = 4 pixels)
  18906. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18907. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18908. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18909. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18910. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18911. let size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  18912. size = Math.ceil( size / 4 ) * 4;
  18913. size = Math.max( size, 4 );
  18914. const boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18915. boneMatrices.set( this.boneMatrices ); // copy current values
  18916. const boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18917. boneTexture.needsUpdate = true;
  18918. this.boneMatrices = boneMatrices;
  18919. this.boneTexture = boneTexture;
  18920. return this;
  18921. }
  18922. /**
  18923. * Searches through the skeleton's bone array and returns the first with a
  18924. * matching name.
  18925. *
  18926. * @param {string} name - The name of the bone.
  18927. * @return {Bone|undefined} The found bone. `undefined` if no bone has been found.
  18928. */
  18929. getBoneByName( name ) {
  18930. for ( let i = 0, il = this.bones.length; i < il; i ++ ) {
  18931. const bone = this.bones[ i ];
  18932. if ( bone.name === name ) {
  18933. return bone;
  18934. }
  18935. }
  18936. return undefined;
  18937. }
  18938. /**
  18939. * Frees the GPU-related resources allocated by this instance. Call this
  18940. * method whenever this instance is no longer used in your app.
  18941. */
  18942. dispose( ) {
  18943. if ( this.boneTexture !== null ) {
  18944. this.boneTexture.dispose();
  18945. this.boneTexture = null;
  18946. }
  18947. }
  18948. /**
  18949. * Setups the skeleton by the given JSON and bones.
  18950. *
  18951. * @param {Object} json - The skeleton as serialized JSON.
  18952. * @param {Object<string, Bone>} bones - An array of bones.
  18953. * @return {Skeleton} A reference of this instance.
  18954. */
  18955. fromJSON( json, bones ) {
  18956. this.uuid = json.uuid;
  18957. for ( let i = 0, l = json.bones.length; i < l; i ++ ) {
  18958. const uuid = json.bones[ i ];
  18959. let bone = bones[ uuid ];
  18960. if ( bone === undefined ) {
  18961. warn( 'Skeleton: No bone found with UUID:', uuid );
  18962. bone = new Bone();
  18963. }
  18964. this.bones.push( bone );
  18965. this.boneInverses.push( new Matrix4().fromArray( json.boneInverses[ i ] ) );
  18966. }
  18967. this.init();
  18968. return this;
  18969. }
  18970. /**
  18971. * Serializes the skeleton into JSON.
  18972. *
  18973. * @return {Object} A JSON object representing the serialized skeleton.
  18974. * @see {@link ObjectLoader#parse}
  18975. */
  18976. toJSON() {
  18977. const data = {
  18978. metadata: {
  18979. version: 4.7,
  18980. type: 'Skeleton',
  18981. generator: 'Skeleton.toJSON'
  18982. },
  18983. bones: [],
  18984. boneInverses: []
  18985. };
  18986. data.uuid = this.uuid;
  18987. const bones = this.bones;
  18988. const boneInverses = this.boneInverses;
  18989. for ( let i = 0, l = bones.length; i < l; i ++ ) {
  18990. const bone = bones[ i ];
  18991. data.bones.push( bone.uuid );
  18992. const boneInverse = boneInverses[ i ];
  18993. data.boneInverses.push( boneInverse.toArray() );
  18994. }
  18995. return data;
  18996. }
  18997. }
  18998. /**
  18999. * An instanced version of a buffer attribute.
  19000. *
  19001. * @augments BufferAttribute
  19002. */
  19003. class InstancedBufferAttribute extends BufferAttribute {
  19004. /**
  19005. * Constructs a new instanced buffer attribute.
  19006. *
  19007. * @param {TypedArray} array - The array holding the attribute data.
  19008. * @param {number} itemSize - The item size.
  19009. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  19010. * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated.
  19011. */
  19012. constructor( array, itemSize, normalized, meshPerAttribute = 1 ) {
  19013. super( array, itemSize, normalized );
  19014. /**
  19015. * This flag can be used for type testing.
  19016. *
  19017. * @type {boolean}
  19018. * @readonly
  19019. * @default true
  19020. */
  19021. this.isInstancedBufferAttribute = true;
  19022. /**
  19023. * Defines how often a value of this buffer attribute should be repeated. A
  19024. * value of one means that each value of the instanced attribute is used for
  19025. * a single instance. A value of two means that each value is used for two
  19026. * consecutive instances (and so on).
  19027. *
  19028. * @type {number}
  19029. * @default 1
  19030. */
  19031. this.meshPerAttribute = meshPerAttribute;
  19032. }
  19033. copy( source ) {
  19034. super.copy( source );
  19035. this.meshPerAttribute = source.meshPerAttribute;
  19036. return this;
  19037. }
  19038. toJSON() {
  19039. const data = super.toJSON();
  19040. data.meshPerAttribute = this.meshPerAttribute;
  19041. data.isInstancedBufferAttribute = true;
  19042. return data;
  19043. }
  19044. }
  19045. const _instanceLocalMatrix = /*@__PURE__*/ new Matrix4();
  19046. const _instanceWorldMatrix = /*@__PURE__*/ new Matrix4();
  19047. const _instanceIntersects = [];
  19048. const _box3 = /*@__PURE__*/ new Box3();
  19049. const _identity = /*@__PURE__*/ new Matrix4();
  19050. const _mesh$1 = /*@__PURE__*/ new Mesh();
  19051. const _sphere$4 = /*@__PURE__*/ new Sphere();
  19052. /**
  19053. * A special version of a mesh with instanced rendering support. Use
  19054. * this class if you have to render a large number of objects with the same
  19055. * geometry and material(s) but with different world transformations. The usage
  19056. * of 'InstancedMesh' will help you to reduce the number of draw calls and thus
  19057. * improve the overall rendering performance in your application.
  19058. *
  19059. * @augments Mesh
  19060. */
  19061. class InstancedMesh extends Mesh {
  19062. /**
  19063. * Constructs a new instanced mesh.
  19064. *
  19065. * @param {BufferGeometry} [geometry] - The mesh geometry.
  19066. * @param {Material|Array<Material>} [material] - The mesh material.
  19067. * @param {number} count - The number of instances.
  19068. */
  19069. constructor( geometry, material, count ) {
  19070. super( geometry, material );
  19071. /**
  19072. * This flag can be used for type testing.
  19073. *
  19074. * @type {boolean}
  19075. * @readonly
  19076. * @default true
  19077. */
  19078. this.isInstancedMesh = true;
  19079. /**
  19080. * Represents the local transformation of all instances. You have to set its
  19081. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19082. * via {@link InstancedMesh#setMatrixAt}.
  19083. *
  19084. * @type {InstancedBufferAttribute}
  19085. */
  19086. this.instanceMatrix = new InstancedBufferAttribute( new Float32Array( count * 16 ), 16 );
  19087. /**
  19088. * Represents the color of all instances. You have to set its
  19089. * {@link BufferAttribute#needsUpdate} flag to true if you modify instanced data
  19090. * via {@link InstancedMesh#setColorAt}.
  19091. *
  19092. * @type {?InstancedBufferAttribute}
  19093. * @default null
  19094. */
  19095. this.instanceColor = null;
  19096. /**
  19097. * Represents the morph target weights of all instances. You have to set its
  19098. * {@link Texture#needsUpdate} flag to true if you modify instanced data
  19099. * via {@link InstancedMesh#setMorphAt}.
  19100. *
  19101. * @type {?DataTexture}
  19102. * @default null
  19103. */
  19104. this.morphTexture = null;
  19105. /**
  19106. * The number of instances.
  19107. *
  19108. * @type {number}
  19109. */
  19110. this.count = count;
  19111. /**
  19112. * The bounding box of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingBox}.
  19113. *
  19114. * @type {?Box3}
  19115. * @default null
  19116. */
  19117. this.boundingBox = null;
  19118. /**
  19119. * The bounding sphere of the instanced mesh. Can be computed via {@link InstancedMesh#computeBoundingSphere}.
  19120. *
  19121. * @type {?Sphere}
  19122. * @default null
  19123. */
  19124. this.boundingSphere = null;
  19125. for ( let i = 0; i < count; i ++ ) {
  19126. this.setMatrixAt( i, _identity );
  19127. }
  19128. }
  19129. /**
  19130. * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}.
  19131. * The bounding box is not automatically computed by the engine; this method must be called by your app.
  19132. * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19133. */
  19134. computeBoundingBox() {
  19135. const geometry = this.geometry;
  19136. const count = this.count;
  19137. if ( this.boundingBox === null ) {
  19138. this.boundingBox = new Box3();
  19139. }
  19140. if ( geometry.boundingBox === null ) {
  19141. geometry.computeBoundingBox();
  19142. }
  19143. this.boundingBox.makeEmpty();
  19144. for ( let i = 0; i < count; i ++ ) {
  19145. this.getMatrixAt( i, _instanceLocalMatrix );
  19146. _box3.copy( geometry.boundingBox ).applyMatrix4( _instanceLocalMatrix );
  19147. this.boundingBox.union( _box3 );
  19148. }
  19149. }
  19150. /**
  19151. * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere}
  19152. * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling.
  19153. * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}.
  19154. */
  19155. computeBoundingSphere() {
  19156. const geometry = this.geometry;
  19157. const count = this.count;
  19158. if ( this.boundingSphere === null ) {
  19159. this.boundingSphere = new Sphere();
  19160. }
  19161. if ( geometry.boundingSphere === null ) {
  19162. geometry.computeBoundingSphere();
  19163. }
  19164. this.boundingSphere.makeEmpty();
  19165. for ( let i = 0; i < count; i ++ ) {
  19166. this.getMatrixAt( i, _instanceLocalMatrix );
  19167. _sphere$4.copy( geometry.boundingSphere ).applyMatrix4( _instanceLocalMatrix );
  19168. this.boundingSphere.union( _sphere$4 );
  19169. }
  19170. }
  19171. copy( source, recursive ) {
  19172. super.copy( source, recursive );
  19173. this.instanceMatrix.copy( source.instanceMatrix );
  19174. if ( source.morphTexture !== null ) this.morphTexture = source.morphTexture.clone();
  19175. if ( source.instanceColor !== null ) this.instanceColor = source.instanceColor.clone();
  19176. this.count = source.count;
  19177. if ( source.boundingBox !== null ) this.boundingBox = source.boundingBox.clone();
  19178. if ( source.boundingSphere !== null ) this.boundingSphere = source.boundingSphere.clone();
  19179. return this;
  19180. }
  19181. /**
  19182. * Gets the color of the defined instance.
  19183. *
  19184. * @param {number} index - The instance index.
  19185. * @param {Color} color - The target object that is used to store the method's result.
  19186. */
  19187. getColorAt( index, color ) {
  19188. color.fromArray( this.instanceColor.array, index * 3 );
  19189. }
  19190. /**
  19191. * Gets the local transformation matrix of the defined instance.
  19192. *
  19193. * @param {number} index - The instance index.
  19194. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  19195. */
  19196. getMatrixAt( index, matrix ) {
  19197. matrix.fromArray( this.instanceMatrix.array, index * 16 );
  19198. }
  19199. /**
  19200. * Gets the morph target weights of the defined instance.
  19201. *
  19202. * @param {number} index - The instance index.
  19203. * @param {Mesh} object - The target object that is used to store the method's result.
  19204. */
  19205. getMorphAt( index, object ) {
  19206. const objectInfluences = object.morphTargetInfluences;
  19207. const array = this.morphTexture.source.data.data;
  19208. const len = objectInfluences.length + 1; // All influences + the baseInfluenceSum
  19209. const dataIndex = index * len + 1; // Skip the baseInfluenceSum at the beginning
  19210. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19211. objectInfluences[ i ] = array[ dataIndex + i ];
  19212. }
  19213. }
  19214. raycast( raycaster, intersects ) {
  19215. const matrixWorld = this.matrixWorld;
  19216. const raycastTimes = this.count;
  19217. _mesh$1.geometry = this.geometry;
  19218. _mesh$1.material = this.material;
  19219. if ( _mesh$1.material === undefined ) return;
  19220. // test with bounding sphere first
  19221. if ( this.boundingSphere === null ) this.computeBoundingSphere();
  19222. _sphere$4.copy( this.boundingSphere );
  19223. _sphere$4.applyMatrix4( matrixWorld );
  19224. if ( raycaster.ray.intersectsSphere( _sphere$4 ) === false ) return;
  19225. // now test each instance
  19226. for ( let instanceId = 0; instanceId < raycastTimes; instanceId ++ ) {
  19227. // calculate the world matrix for each instance
  19228. this.getMatrixAt( instanceId, _instanceLocalMatrix );
  19229. _instanceWorldMatrix.multiplyMatrices( matrixWorld, _instanceLocalMatrix );
  19230. // the mesh represents this single instance
  19231. _mesh$1.matrixWorld = _instanceWorldMatrix;
  19232. _mesh$1.raycast( raycaster, _instanceIntersects );
  19233. // process the result of raycast
  19234. for ( let i = 0, l = _instanceIntersects.length; i < l; i ++ ) {
  19235. const intersect = _instanceIntersects[ i ];
  19236. intersect.instanceId = instanceId;
  19237. intersect.object = this;
  19238. intersects.push( intersect );
  19239. }
  19240. _instanceIntersects.length = 0;
  19241. }
  19242. }
  19243. /**
  19244. * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of
  19245. * {@link InstancedMesh#instanceColor} to `true` after updating all the colors.
  19246. *
  19247. * @param {number} index - The instance index.
  19248. * @param {Color} color - The instance color.
  19249. */
  19250. setColorAt( index, color ) {
  19251. if ( this.instanceColor === null ) {
  19252. this.instanceColor = new InstancedBufferAttribute( new Float32Array( this.instanceMatrix.count * 3 ).fill( 1 ), 3 );
  19253. }
  19254. color.toArray( this.instanceColor.array, index * 3 );
  19255. }
  19256. /**
  19257. * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of
  19258. * {@link InstancedMesh#instanceMatrix} to `true` after updating all the colors.
  19259. *
  19260. * @param {number} index - The instance index.
  19261. * @param {Matrix4} matrix - The local transformation.
  19262. */
  19263. setMatrixAt( index, matrix ) {
  19264. matrix.toArray( this.instanceMatrix.array, index * 16 );
  19265. }
  19266. /**
  19267. * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of
  19268. * {@link InstancedMesh#morphTexture} to `true` after updating all the influences.
  19269. *
  19270. * @param {number} index - The instance index.
  19271. * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights
  19272. * of a single instance.
  19273. */
  19274. setMorphAt( index, object ) {
  19275. const objectInfluences = object.morphTargetInfluences;
  19276. const len = objectInfluences.length + 1; // morphBaseInfluence + all influences
  19277. if ( this.morphTexture === null ) {
  19278. this.morphTexture = new DataTexture( new Float32Array( len * this.count ), len, this.count, RedFormat, FloatType );
  19279. }
  19280. const array = this.morphTexture.source.data.data;
  19281. let morphInfluencesSum = 0;
  19282. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  19283. morphInfluencesSum += objectInfluences[ i ];
  19284. }
  19285. const morphBaseInfluence = this.geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  19286. const dataIndex = len * index;
  19287. array[ dataIndex ] = morphBaseInfluence;
  19288. array.set( objectInfluences, dataIndex + 1 );
  19289. }
  19290. updateMorphTargets() {
  19291. }
  19292. /**
  19293. * Frees the GPU-related resources allocated by this instance. Call this
  19294. * method whenever this instance is no longer used in your app.
  19295. */
  19296. dispose() {
  19297. this.dispatchEvent( { type: 'dispose' } );
  19298. if ( this.morphTexture !== null ) {
  19299. this.morphTexture.dispose();
  19300. this.morphTexture = null;
  19301. }
  19302. }
  19303. }
  19304. const _vector1 = /*@__PURE__*/ new Vector3();
  19305. const _vector2 = /*@__PURE__*/ new Vector3();
  19306. const _normalMatrix = /*@__PURE__*/ new Matrix3();
  19307. /**
  19308. * A two dimensional surface that extends infinitely in 3D space, represented
  19309. * in [Hessian normal form](http://mathworld.wolfram.com/HessianNormalForm.html)
  19310. * by a unit length normal vector and a constant.
  19311. */
  19312. class Plane {
  19313. /**
  19314. * Constructs a new plane.
  19315. *
  19316. * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane.
  19317. * @param {number} [constant=0] - The signed distance from the origin to the plane.
  19318. */
  19319. constructor( normal = new Vector3( 1, 0, 0 ), constant = 0 ) {
  19320. /**
  19321. * This flag can be used for type testing.
  19322. *
  19323. * @type {boolean}
  19324. * @readonly
  19325. * @default true
  19326. */
  19327. this.isPlane = true;
  19328. /**
  19329. * A unit length vector defining the normal of the plane.
  19330. *
  19331. * @type {Vector3}
  19332. */
  19333. this.normal = normal;
  19334. /**
  19335. * The signed distance from the origin to the plane.
  19336. *
  19337. * @type {number}
  19338. * @default 0
  19339. */
  19340. this.constant = constant;
  19341. }
  19342. /**
  19343. * Sets the plane components by copying the given values.
  19344. *
  19345. * @param {Vector3} normal - The normal.
  19346. * @param {number} constant - The constant.
  19347. * @return {Plane} A reference to this plane.
  19348. */
  19349. set( normal, constant ) {
  19350. this.normal.copy( normal );
  19351. this.constant = constant;
  19352. return this;
  19353. }
  19354. /**
  19355. * Sets the plane components by defining `x`, `y`, `z` as the
  19356. * plane normal and `w` as the constant.
  19357. *
  19358. * @param {number} x - The value for the normal's x component.
  19359. * @param {number} y - The value for the normal's y component.
  19360. * @param {number} z - The value for the normal's z component.
  19361. * @param {number} w - The constant value.
  19362. * @return {Plane} A reference to this plane.
  19363. */
  19364. setComponents( x, y, z, w ) {
  19365. this.normal.set( x, y, z );
  19366. this.constant = w;
  19367. return this;
  19368. }
  19369. /**
  19370. * Sets the plane from the given normal and coplanar point (that is a point
  19371. * that lies onto the plane).
  19372. *
  19373. * @param {Vector3} normal - The normal.
  19374. * @param {Vector3} point - A coplanar point.
  19375. * @return {Plane} A reference to this plane.
  19376. */
  19377. setFromNormalAndCoplanarPoint( normal, point ) {
  19378. this.normal.copy( normal );
  19379. this.constant = - point.dot( this.normal );
  19380. return this;
  19381. }
  19382. /**
  19383. * Sets the plane from three coplanar points. The winding order is
  19384. * assumed to be counter-clockwise, and determines the direction of
  19385. * the plane normal.
  19386. *
  19387. * @param {Vector3} a - The first coplanar point.
  19388. * @param {Vector3} b - The second coplanar point.
  19389. * @param {Vector3} c - The third coplanar point.
  19390. * @return {Plane} A reference to this plane.
  19391. */
  19392. setFromCoplanarPoints( a, b, c ) {
  19393. const normal = _vector1.subVectors( c, b ).cross( _vector2.subVectors( a, b ) ).normalize();
  19394. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  19395. this.setFromNormalAndCoplanarPoint( normal, a );
  19396. return this;
  19397. }
  19398. /**
  19399. * Copies the values of the given plane to this instance.
  19400. *
  19401. * @param {Plane} plane - The plane to copy.
  19402. * @return {Plane} A reference to this plane.
  19403. */
  19404. copy( plane ) {
  19405. this.normal.copy( plane.normal );
  19406. this.constant = plane.constant;
  19407. return this;
  19408. }
  19409. /**
  19410. * Normalizes the plane normal and adjusts the constant accordingly.
  19411. *
  19412. * @return {Plane} A reference to this plane.
  19413. */
  19414. normalize() {
  19415. // Note: will lead to a divide by zero if the plane is invalid.
  19416. const inverseNormalLength = 1.0 / this.normal.length();
  19417. this.normal.multiplyScalar( inverseNormalLength );
  19418. this.constant *= inverseNormalLength;
  19419. return this;
  19420. }
  19421. /**
  19422. * Negates both the plane normal and the constant.
  19423. *
  19424. * @return {Plane} A reference to this plane.
  19425. */
  19426. negate() {
  19427. this.constant *= -1;
  19428. this.normal.negate();
  19429. return this;
  19430. }
  19431. /**
  19432. * Returns the signed distance from the given point to this plane.
  19433. *
  19434. * @param {Vector3} point - The point to compute the distance for.
  19435. * @return {number} The signed distance.
  19436. */
  19437. distanceToPoint( point ) {
  19438. return this.normal.dot( point ) + this.constant;
  19439. }
  19440. /**
  19441. * Returns the signed distance from the given sphere to this plane.
  19442. *
  19443. * @param {Sphere} sphere - The sphere to compute the distance for.
  19444. * @return {number} The signed distance.
  19445. */
  19446. distanceToSphere( sphere ) {
  19447. return this.distanceToPoint( sphere.center ) - sphere.radius;
  19448. }
  19449. /**
  19450. * Projects a the given point onto the plane.
  19451. *
  19452. * @param {Vector3} point - The point to project.
  19453. * @param {Vector3} target - The target vector that is used to store the method's result.
  19454. * @return {Vector3} The projected point on the plane.
  19455. */
  19456. projectPoint( point, target ) {
  19457. return target.copy( point ).addScaledVector( this.normal, - this.distanceToPoint( point ) );
  19458. }
  19459. /**
  19460. * Returns the intersection point of the passed line and the plane. Returns
  19461. * `null` if the line does not intersect. Returns the line's starting point if
  19462. * the line is coplanar with the plane.
  19463. *
  19464. * @param {Line3} line - The line to compute the intersection for.
  19465. * @param {Vector3} target - The target vector that is used to store the method's result.
  19466. * @return {?Vector3} The intersection point.
  19467. */
  19468. intersectLine( line, target ) {
  19469. const direction = line.delta( _vector1 );
  19470. const denominator = this.normal.dot( direction );
  19471. if ( denominator === 0 ) {
  19472. // line is coplanar, return origin
  19473. if ( this.distanceToPoint( line.start ) === 0 ) {
  19474. return target.copy( line.start );
  19475. }
  19476. // Unsure if this is the correct method to handle this case.
  19477. return null;
  19478. }
  19479. const t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  19480. if ( t < 0 || t > 1 ) {
  19481. return null;
  19482. }
  19483. return target.copy( line.start ).addScaledVector( direction, t );
  19484. }
  19485. /**
  19486. * Returns `true` if the given line segment intersects with (passes through) the plane.
  19487. *
  19488. * @param {Line3} line - The line to test.
  19489. * @return {boolean} Whether the given line segment intersects with the plane or not.
  19490. */
  19491. intersectsLine( line ) {
  19492. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  19493. const startSign = this.distanceToPoint( line.start );
  19494. const endSign = this.distanceToPoint( line.end );
  19495. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  19496. }
  19497. /**
  19498. * Returns `true` if the given bounding box intersects with the plane.
  19499. *
  19500. * @param {Box3} box - The bounding box to test.
  19501. * @return {boolean} Whether the given bounding box intersects with the plane or not.
  19502. */
  19503. intersectsBox( box ) {
  19504. return box.intersectsPlane( this );
  19505. }
  19506. /**
  19507. * Returns `true` if the given bounding sphere intersects with the plane.
  19508. *
  19509. * @param {Sphere} sphere - The bounding sphere to test.
  19510. * @return {boolean} Whether the given bounding sphere intersects with the plane or not.
  19511. */
  19512. intersectsSphere( sphere ) {
  19513. return sphere.intersectsPlane( this );
  19514. }
  19515. /**
  19516. * Returns a coplanar vector to the plane, by calculating the
  19517. * projection of the normal at the origin onto the plane.
  19518. *
  19519. * @param {Vector3} target - The target vector that is used to store the method's result.
  19520. * @return {Vector3} The coplanar point.
  19521. */
  19522. coplanarPoint( target ) {
  19523. return target.copy( this.normal ).multiplyScalar( - this.constant );
  19524. }
  19525. /**
  19526. * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform.
  19527. *
  19528. * The optional normal matrix can be pre-computed like so:
  19529. * ```js
  19530. * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  19531. * ```
  19532. *
  19533. * @param {Matrix4} matrix - The transformation matrix.
  19534. * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix.
  19535. * @return {Plane} A reference to this plane.
  19536. */
  19537. applyMatrix4( matrix, optionalNormalMatrix ) {
  19538. const normalMatrix = optionalNormalMatrix || _normalMatrix.getNormalMatrix( matrix );
  19539. const referencePoint = this.coplanarPoint( _vector1 ).applyMatrix4( matrix );
  19540. const normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  19541. this.constant = - referencePoint.dot( normal );
  19542. return this;
  19543. }
  19544. /**
  19545. * Translates the plane by the distance defined by the given offset vector.
  19546. * Note that this only affects the plane constant and will not affect the normal vector.
  19547. *
  19548. * @param {Vector3} offset - The offset vector.
  19549. * @return {Plane} A reference to this plane.
  19550. */
  19551. translate( offset ) {
  19552. this.constant -= offset.dot( this.normal );
  19553. return this;
  19554. }
  19555. /**
  19556. * Returns `true` if this plane is equal with the given one.
  19557. *
  19558. * @param {Plane} plane - The plane to test for equality.
  19559. * @return {boolean} Whether this plane is equal with the given one.
  19560. */
  19561. equals( plane ) {
  19562. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  19563. }
  19564. /**
  19565. * Returns a new plane with copied values from this instance.
  19566. *
  19567. * @return {Plane} A clone of this instance.
  19568. */
  19569. clone() {
  19570. return new this.constructor().copy( this );
  19571. }
  19572. }
  19573. const _sphere$3 = /*@__PURE__*/ new Sphere();
  19574. const _defaultSpriteCenter = /*@__PURE__*/ new Vector2( 0.5, 0.5 );
  19575. const _vector$6 = /*@__PURE__*/ new Vector3();
  19576. /**
  19577. * Frustums are used to determine what is inside the camera's field of view.
  19578. * They help speed up the rendering process - objects which lie outside a camera's
  19579. * frustum can safely be excluded from rendering.
  19580. *
  19581. * This class is mainly intended for use internally by a renderer.
  19582. */
  19583. class Frustum {
  19584. /**
  19585. * Constructs a new frustum.
  19586. *
  19587. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19588. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19589. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19590. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19591. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19592. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19593. */
  19594. constructor( p0 = new Plane(), p1 = new Plane(), p2 = new Plane(), p3 = new Plane(), p4 = new Plane(), p5 = new Plane() ) {
  19595. /**
  19596. * This array holds the planes that enclose the frustum.
  19597. *
  19598. * @type {Array<Plane>}
  19599. */
  19600. this.planes = [ p0, p1, p2, p3, p4, p5 ];
  19601. }
  19602. /**
  19603. * Sets the frustum planes by copying the given planes.
  19604. *
  19605. * @param {Plane} [p0] - The first plane that encloses the frustum.
  19606. * @param {Plane} [p1] - The second plane that encloses the frustum.
  19607. * @param {Plane} [p2] - The third plane that encloses the frustum.
  19608. * @param {Plane} [p3] - The fourth plane that encloses the frustum.
  19609. * @param {Plane} [p4] - The fifth plane that encloses the frustum.
  19610. * @param {Plane} [p5] - The sixth plane that encloses the frustum.
  19611. * @return {Frustum} A reference to this frustum.
  19612. */
  19613. set( p0, p1, p2, p3, p4, p5 ) {
  19614. const planes = this.planes;
  19615. planes[ 0 ].copy( p0 );
  19616. planes[ 1 ].copy( p1 );
  19617. planes[ 2 ].copy( p2 );
  19618. planes[ 3 ].copy( p3 );
  19619. planes[ 4 ].copy( p4 );
  19620. planes[ 5 ].copy( p5 );
  19621. return this;
  19622. }
  19623. /**
  19624. * Copies the values of the given frustum to this instance.
  19625. *
  19626. * @param {Frustum} frustum - The frustum to copy.
  19627. * @return {Frustum} A reference to this frustum.
  19628. */
  19629. copy( frustum ) {
  19630. const planes = this.planes;
  19631. for ( let i = 0; i < 6; i ++ ) {
  19632. planes[ i ].copy( frustum.planes[ i ] );
  19633. }
  19634. return this;
  19635. }
  19636. /**
  19637. * Sets the frustum planes from the given projection matrix.
  19638. *
  19639. * @param {Matrix4} m - The projection matrix.
  19640. * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system.
  19641. * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth.
  19642. * @return {Frustum} A reference to this frustum.
  19643. */
  19644. setFromProjectionMatrix( m, coordinateSystem = WebGLCoordinateSystem, reversedDepth = false ) {
  19645. const planes = this.planes;
  19646. const me = m.elements;
  19647. const me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  19648. const me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  19649. const me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  19650. const me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  19651. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  19652. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  19653. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  19654. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  19655. if ( reversedDepth ) {
  19656. planes[ 4 ].setComponents( me2, me6, me10, me14 ).normalize(); // far
  19657. planes[ 5 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // near
  19658. } else {
  19659. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize(); // far
  19660. if ( coordinateSystem === WebGLCoordinateSystem ) {
  19661. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize(); // near
  19662. } else if ( coordinateSystem === WebGPUCoordinateSystem ) {
  19663. planes[ 5 ].setComponents( me2, me6, me10, me14 ).normalize(); // near
  19664. } else {
  19665. throw new Error( 'THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: ' + coordinateSystem );
  19666. }
  19667. }
  19668. return this;
  19669. }
  19670. /**
  19671. * Returns `true` if the 3D object's bounding sphere is intersecting this frustum.
  19672. *
  19673. * Note that the 3D object must have a geometry so that the bounding sphere can be calculated.
  19674. *
  19675. * @param {Object3D} object - The 3D object to test.
  19676. * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not.
  19677. */
  19678. intersectsObject( object ) {
  19679. if ( object.boundingSphere !== undefined ) {
  19680. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  19681. _sphere$3.copy( object.boundingSphere ).applyMatrix4( object.matrixWorld );
  19682. } else {
  19683. const geometry = object.geometry;
  19684. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19685. _sphere$3.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  19686. }
  19687. return this.intersectsSphere( _sphere$3 );
  19688. }
  19689. /**
  19690. * Returns `true` if the given sprite is intersecting this frustum.
  19691. *
  19692. * @param {Sprite} sprite - The sprite to test.
  19693. * @return {boolean} Whether the sprite is intersecting this frustum or not.
  19694. */
  19695. intersectsSprite( sprite ) {
  19696. _sphere$3.center.set( 0, 0, 0 );
  19697. const offset = _defaultSpriteCenter.distanceTo( sprite.center );
  19698. _sphere$3.radius = 0.7071067811865476 + offset;
  19699. _sphere$3.applyMatrix4( sprite.matrixWorld );
  19700. return this.intersectsSphere( _sphere$3 );
  19701. }
  19702. /**
  19703. * Returns `true` if the given bounding sphere is intersecting this frustum.
  19704. *
  19705. * @param {Sphere} sphere - The bounding sphere to test.
  19706. * @return {boolean} Whether the bounding sphere is intersecting this frustum or not.
  19707. */
  19708. intersectsSphere( sphere ) {
  19709. const planes = this.planes;
  19710. const center = sphere.center;
  19711. const negRadius = - sphere.radius;
  19712. for ( let i = 0; i < 6; i ++ ) {
  19713. const distance = planes[ i ].distanceToPoint( center );
  19714. if ( distance < negRadius ) {
  19715. return false;
  19716. }
  19717. }
  19718. return true;
  19719. }
  19720. /**
  19721. * Returns `true` if the given bounding box is intersecting this frustum.
  19722. *
  19723. * @param {Box3} box - The bounding box to test.
  19724. * @return {boolean} Whether the bounding box is intersecting this frustum or not.
  19725. */
  19726. intersectsBox( box ) {
  19727. const planes = this.planes;
  19728. for ( let i = 0; i < 6; i ++ ) {
  19729. const plane = planes[ i ];
  19730. // corner at max distance
  19731. _vector$6.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  19732. _vector$6.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  19733. _vector$6.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  19734. if ( plane.distanceToPoint( _vector$6 ) < 0 ) {
  19735. return false;
  19736. }
  19737. }
  19738. return true;
  19739. }
  19740. /**
  19741. * Returns `true` if the given point lies within the frustum.
  19742. *
  19743. * @param {Vector3} point - The point to test.
  19744. * @return {boolean} Whether the point lies within this frustum or not.
  19745. */
  19746. containsPoint( point ) {
  19747. const planes = this.planes;
  19748. for ( let i = 0; i < 6; i ++ ) {
  19749. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  19750. return false;
  19751. }
  19752. }
  19753. return true;
  19754. }
  19755. /**
  19756. * Returns a new frustum with copied values from this instance.
  19757. *
  19758. * @return {Frustum} A clone of this instance.
  19759. */
  19760. clone() {
  19761. return new this.constructor().copy( this );
  19762. }
  19763. }
  19764. const _projScreenMatrix$2 = /*@__PURE__*/ new Matrix4();
  19765. const _frustum$1 = /*@__PURE__*/ new Frustum();
  19766. /**
  19767. * FrustumArray is used to determine if an object is visible in at least one camera
  19768. * from an array of cameras. This is particularly useful for multi-view renderers.
  19769. */
  19770. class FrustumArray {
  19771. /**
  19772. * Constructs a new frustum array.
  19773. *
  19774. */
  19775. constructor() {
  19776. /**
  19777. * The coordinate system to use.
  19778. *
  19779. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  19780. * @default WebGLCoordinateSystem
  19781. */
  19782. this.coordinateSystem = WebGLCoordinateSystem;
  19783. }
  19784. /**
  19785. * Returns `true` if the 3D object's bounding sphere is intersecting any frustum
  19786. * from the camera array.
  19787. *
  19788. * @param {Object3D} object - The 3D object to test.
  19789. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19790. * @return {boolean} Whether the 3D object is visible in any camera.
  19791. */
  19792. intersectsObject( object, cameraArray ) {
  19793. if ( ! cameraArray.isArrayCamera || cameraArray.cameras.length === 0 ) {
  19794. return false;
  19795. }
  19796. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19797. const camera = cameraArray.cameras[ i ];
  19798. _projScreenMatrix$2.multiplyMatrices(
  19799. camera.projectionMatrix,
  19800. camera.matrixWorldInverse
  19801. );
  19802. _frustum$1.setFromProjectionMatrix(
  19803. _projScreenMatrix$2,
  19804. camera.coordinateSystem,
  19805. camera.reversedDepth
  19806. );
  19807. if ( _frustum$1.intersectsObject( object ) ) {
  19808. return true; // Object is visible in at least one camera
  19809. }
  19810. }
  19811. return false; // Not visible in any camera
  19812. }
  19813. /**
  19814. * Returns `true` if the given sprite is intersecting any frustum
  19815. * from the camera array.
  19816. *
  19817. * @param {Sprite} sprite - The sprite to test.
  19818. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19819. * @return {boolean} Whether the sprite is visible in any camera.
  19820. */
  19821. intersectsSprite( sprite, cameraArray ) {
  19822. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19823. return false;
  19824. }
  19825. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19826. const camera = cameraArray.cameras[ i ];
  19827. _projScreenMatrix$2.multiplyMatrices(
  19828. camera.projectionMatrix,
  19829. camera.matrixWorldInverse
  19830. );
  19831. _frustum$1.setFromProjectionMatrix(
  19832. _projScreenMatrix$2,
  19833. camera.coordinateSystem,
  19834. camera.reversedDepth
  19835. );
  19836. if ( _frustum$1.intersectsSprite( sprite ) ) {
  19837. return true; // Sprite is visible in at least one camera
  19838. }
  19839. }
  19840. return false; // Not visible in any camera
  19841. }
  19842. /**
  19843. * Returns `true` if the given bounding sphere is intersecting any frustum
  19844. * from the camera array.
  19845. *
  19846. * @param {Sphere} sphere - The bounding sphere to test.
  19847. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19848. * @return {boolean} Whether the sphere is visible in any camera.
  19849. */
  19850. intersectsSphere( sphere, cameraArray ) {
  19851. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19852. return false;
  19853. }
  19854. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19855. const camera = cameraArray.cameras[ i ];
  19856. _projScreenMatrix$2.multiplyMatrices(
  19857. camera.projectionMatrix,
  19858. camera.matrixWorldInverse
  19859. );
  19860. _frustum$1.setFromProjectionMatrix(
  19861. _projScreenMatrix$2,
  19862. camera.coordinateSystem,
  19863. camera.reversedDepth
  19864. );
  19865. if ( _frustum$1.intersectsSphere( sphere ) ) {
  19866. return true; // Sphere is visible in at least one camera
  19867. }
  19868. }
  19869. return false; // Not visible in any camera
  19870. }
  19871. /**
  19872. * Returns `true` if the given bounding box is intersecting any frustum
  19873. * from the camera array.
  19874. *
  19875. * @param {Box3} box - The bounding box to test.
  19876. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19877. * @return {boolean} Whether the box is visible in any camera.
  19878. */
  19879. intersectsBox( box, cameraArray ) {
  19880. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19881. return false;
  19882. }
  19883. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19884. const camera = cameraArray.cameras[ i ];
  19885. _projScreenMatrix$2.multiplyMatrices(
  19886. camera.projectionMatrix,
  19887. camera.matrixWorldInverse
  19888. );
  19889. _frustum$1.setFromProjectionMatrix(
  19890. _projScreenMatrix$2,
  19891. camera.coordinateSystem,
  19892. camera.reversedDepth
  19893. );
  19894. if ( _frustum$1.intersectsBox( box ) ) {
  19895. return true; // Box is visible in at least one camera
  19896. }
  19897. }
  19898. return false; // Not visible in any camera
  19899. }
  19900. /**
  19901. * Returns `true` if the given point lies within any frustum
  19902. * from the camera array.
  19903. *
  19904. * @param {Vector3} point - The point to test.
  19905. * @param {Object} cameraArray - An object with a cameras property containing an array of cameras.
  19906. * @return {boolean} Whether the point is visible in any camera.
  19907. */
  19908. containsPoint( point, cameraArray ) {
  19909. if ( ! cameraArray || ! cameraArray.cameras || cameraArray.cameras.length === 0 ) {
  19910. return false;
  19911. }
  19912. for ( let i = 0; i < cameraArray.cameras.length; i ++ ) {
  19913. const camera = cameraArray.cameras[ i ];
  19914. _projScreenMatrix$2.multiplyMatrices(
  19915. camera.projectionMatrix,
  19916. camera.matrixWorldInverse
  19917. );
  19918. _frustum$1.setFromProjectionMatrix(
  19919. _projScreenMatrix$2,
  19920. camera.coordinateSystem,
  19921. camera.reversedDepth
  19922. );
  19923. if ( _frustum$1.containsPoint( point ) ) {
  19924. return true; // Point is visible in at least one camera
  19925. }
  19926. }
  19927. return false; // Not visible in any camera
  19928. }
  19929. /**
  19930. * Returns a new frustum array with copied values from this instance.
  19931. *
  19932. * @return {FrustumArray} A clone of this instance.
  19933. */
  19934. clone() {
  19935. return new FrustumArray();
  19936. }
  19937. }
  19938. function ascIdSort( a, b ) {
  19939. return a - b;
  19940. }
  19941. function sortOpaque( a, b ) {
  19942. return a.z - b.z;
  19943. }
  19944. function sortTransparent( a, b ) {
  19945. return b.z - a.z;
  19946. }
  19947. class MultiDrawRenderList {
  19948. constructor() {
  19949. this.index = 0;
  19950. this.pool = [];
  19951. this.list = [];
  19952. }
  19953. push( start, count, z, index ) {
  19954. const pool = this.pool;
  19955. const list = this.list;
  19956. if ( this.index >= pool.length ) {
  19957. pool.push( {
  19958. start: -1,
  19959. count: -1,
  19960. z: -1,
  19961. index: -1,
  19962. } );
  19963. }
  19964. const item = pool[ this.index ];
  19965. list.push( item );
  19966. this.index ++;
  19967. item.start = start;
  19968. item.count = count;
  19969. item.z = z;
  19970. item.index = index;
  19971. }
  19972. reset() {
  19973. this.list.length = 0;
  19974. this.index = 0;
  19975. }
  19976. }
  19977. const _matrix$1 = /*@__PURE__*/ new Matrix4();
  19978. const _whiteColor = /*@__PURE__*/ new Color( 1, 1, 1 );
  19979. const _frustum = /*@__PURE__*/ new Frustum();
  19980. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  19981. const _box$1 = /*@__PURE__*/ new Box3();
  19982. const _sphere$2 = /*@__PURE__*/ new Sphere();
  19983. const _vector$5 = /*@__PURE__*/ new Vector3();
  19984. const _forward$1 = /*@__PURE__*/ new Vector3();
  19985. const _temp = /*@__PURE__*/ new Vector3();
  19986. const _renderList = /*@__PURE__*/ new MultiDrawRenderList();
  19987. const _mesh = /*@__PURE__*/ new Mesh();
  19988. const _batchIntersects = [];
  19989. // copies data from attribute "src" into "target" starting at "targetOffset"
  19990. function copyAttributeData( src, target, targetOffset = 0 ) {
  19991. const itemSize = target.itemSize;
  19992. if ( src.isInterleavedBufferAttribute || src.array.constructor !== target.array.constructor ) {
  19993. // use the component getters and setters if the array data cannot
  19994. // be copied directly
  19995. const vertexCount = src.count;
  19996. for ( let i = 0; i < vertexCount; i ++ ) {
  19997. for ( let c = 0; c < itemSize; c ++ ) {
  19998. target.setComponent( i + targetOffset, c, src.getComponent( i, c ) );
  19999. }
  20000. }
  20001. } else {
  20002. // faster copy approach using typed array set function
  20003. target.array.set( src.array, targetOffset * itemSize );
  20004. }
  20005. target.needsUpdate = true;
  20006. }
  20007. // safely copies array contents to a potentially smaller array
  20008. function copyArrayContents( src, target ) {
  20009. if ( src.constructor !== target.constructor ) {
  20010. // if arrays are of a different type (eg due to index size increasing) then data must be per-element copied
  20011. const len = Math.min( src.length, target.length );
  20012. for ( let i = 0; i < len; i ++ ) {
  20013. target[ i ] = src[ i ];
  20014. }
  20015. } else {
  20016. // if the arrays use the same data layout we can use a fast block copy
  20017. const len = Math.min( src.length, target.length );
  20018. target.set( new src.constructor( src.buffer, 0, len ) );
  20019. }
  20020. }
  20021. /**
  20022. * A special version of a mesh with multi draw batch rendering support. Use
  20023. * this class if you have to render a large number of objects with the same
  20024. * material but with different geometries or world transformations. The usage of
  20025. * `BatchedMesh` will help you to reduce the number of draw calls and thus improve the overall
  20026. * rendering performance in your application.
  20027. *
  20028. * ```js
  20029. * const box = new THREE.BoxGeometry( 1, 1, 1 );
  20030. * const sphere = new THREE.SphereGeometry( 1, 12, 12 );
  20031. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  20032. *
  20033. * // initialize and add geometries into the batched mesh
  20034. * const batchedMesh = new BatchedMesh( 10, 5000, 10000, material );
  20035. * const boxGeometryId = batchedMesh.addGeometry( box );
  20036. * const sphereGeometryId = batchedMesh.addGeometry( sphere );
  20037. *
  20038. * // create instances of those geometries
  20039. * const boxInstancedId1 = batchedMesh.addInstance( boxGeometryId );
  20040. * const boxInstancedId2 = batchedMesh.addInstance( boxGeometryId );
  20041. *
  20042. * const sphereInstancedId1 = batchedMesh.addInstance( sphereGeometryId );
  20043. * const sphereInstancedId2 = batchedMesh.addInstance( sphereGeometryId );
  20044. *
  20045. * // position the geometries
  20046. * batchedMesh.setMatrixAt( boxInstancedId1, boxMatrix1 );
  20047. * batchedMesh.setMatrixAt( boxInstancedId2, boxMatrix2 );
  20048. *
  20049. * batchedMesh.setMatrixAt( sphereInstancedId1, sphereMatrix1 );
  20050. * batchedMesh.setMatrixAt( sphereInstancedId2, sphereMatrix2 );
  20051. *
  20052. * scene.add( batchedMesh );
  20053. * ```
  20054. *
  20055. * @augments Mesh
  20056. */
  20057. class BatchedMesh extends Mesh {
  20058. /**
  20059. * Constructs a new batched mesh.
  20060. *
  20061. * @param {number} maxInstanceCount - The maximum number of individual instances planned to be added and rendered.
  20062. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries.
  20063. * @param {number} [maxIndexCount=maxVertexCount*2] - The maximum number of indices to be used by all unique geometries
  20064. * @param {Material|Array<Material>} [material] - The mesh material.
  20065. */
  20066. constructor( maxInstanceCount, maxVertexCount, maxIndexCount = maxVertexCount * 2, material ) {
  20067. super( new BufferGeometry(), material );
  20068. /**
  20069. * This flag can be used for type testing.
  20070. *
  20071. * @type {boolean}
  20072. * @readonly
  20073. * @default true
  20074. */
  20075. this.isBatchedMesh = true;
  20076. /**
  20077. * When set ot `true`, the individual objects of a batch are frustum culled.
  20078. *
  20079. * @type {boolean}
  20080. * @default true
  20081. */
  20082. this.perObjectFrustumCulled = true;
  20083. /**
  20084. * When set to `true`, the individual objects of a batch are sorted to improve overdraw-related artifacts.
  20085. * If the material is marked as "transparent" objects are rendered back to front and if not then they are
  20086. * rendered front to back.
  20087. *
  20088. * @type {boolean}
  20089. * @default true
  20090. */
  20091. this.sortObjects = true;
  20092. /**
  20093. * The bounding box of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingBox}.
  20094. *
  20095. * @type {?Box3}
  20096. * @default null
  20097. */
  20098. this.boundingBox = null;
  20099. /**
  20100. * The bounding sphere of the batched mesh. Can be computed via {@link BatchedMesh#computeBoundingSphere}.
  20101. *
  20102. * @type {?Sphere}
  20103. * @default null
  20104. */
  20105. this.boundingSphere = null;
  20106. /**
  20107. * Takes a sort a function that is run before render. The function takes a list of instances to
  20108. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered
  20109. * sort with.
  20110. *
  20111. * @type {?Function}
  20112. * @default null
  20113. */
  20114. this.customSort = null;
  20115. // stores visible, active, and geometry id per instance and reserved buffer ranges for geometries
  20116. this._instanceInfo = [];
  20117. this._geometryInfo = [];
  20118. // instance, geometry ids that have been set as inactive, and are available to be overwritten
  20119. this._availableInstanceIds = [];
  20120. this._availableGeometryIds = [];
  20121. // used to track where the next point is that geometry should be inserted
  20122. this._nextIndexStart = 0;
  20123. this._nextVertexStart = 0;
  20124. this._geometryCount = 0;
  20125. // flags
  20126. this._visibilityChanged = true;
  20127. this._geometryInitialized = false;
  20128. // cached user options
  20129. this._maxInstanceCount = maxInstanceCount;
  20130. this._maxVertexCount = maxVertexCount;
  20131. this._maxIndexCount = maxIndexCount;
  20132. // buffers for multi draw
  20133. this._multiDrawCounts = new Int32Array( maxInstanceCount );
  20134. this._multiDrawStarts = new Int32Array( maxInstanceCount );
  20135. this._multiDrawCount = 0;
  20136. this._multiDrawInstances = null;
  20137. // Local matrix per geometry by using data texture
  20138. this._matricesTexture = null;
  20139. this._indirectTexture = null;
  20140. this._colorsTexture = null;
  20141. this._initMatricesTexture();
  20142. this._initIndirectTexture();
  20143. }
  20144. /**
  20145. * The maximum number of individual instances that can be stored in the batch.
  20146. *
  20147. * @type {number}
  20148. * @readonly
  20149. */
  20150. get maxInstanceCount() {
  20151. return this._maxInstanceCount;
  20152. }
  20153. /**
  20154. * The instance count.
  20155. *
  20156. * @type {number}
  20157. * @readonly
  20158. */
  20159. get instanceCount() {
  20160. return this._instanceInfo.length - this._availableInstanceIds.length;
  20161. }
  20162. /**
  20163. * The number of unused vertices.
  20164. *
  20165. * @type {number}
  20166. * @readonly
  20167. */
  20168. get unusedVertexCount() {
  20169. return this._maxVertexCount - this._nextVertexStart;
  20170. }
  20171. /**
  20172. * The number of unused indices.
  20173. *
  20174. * @type {number}
  20175. * @readonly
  20176. */
  20177. get unusedIndexCount() {
  20178. return this._maxIndexCount - this._nextIndexStart;
  20179. }
  20180. _initMatricesTexture() {
  20181. // layout (1 matrix = 4 pixels)
  20182. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  20183. // with 8x8 pixel texture max 16 matrices * 4 pixels = (8 * 8)
  20184. // 16x16 pixel texture max 64 matrices * 4 pixels = (16 * 16)
  20185. // 32x32 pixel texture max 256 matrices * 4 pixels = (32 * 32)
  20186. // 64x64 pixel texture max 1024 matrices * 4 pixels = (64 * 64)
  20187. let size = Math.sqrt( this._maxInstanceCount * 4 ); // 4 pixels needed for 1 matrix
  20188. size = Math.ceil( size / 4 ) * 4;
  20189. size = Math.max( size, 4 );
  20190. const matricesArray = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  20191. const matricesTexture = new DataTexture( matricesArray, size, size, RGBAFormat, FloatType );
  20192. this._matricesTexture = matricesTexture;
  20193. }
  20194. _initIndirectTexture() {
  20195. let size = Math.sqrt( this._maxInstanceCount );
  20196. size = Math.ceil( size );
  20197. const indirectArray = new Uint32Array( size * size );
  20198. const indirectTexture = new DataTexture( indirectArray, size, size, RedIntegerFormat, UnsignedIntType );
  20199. this._indirectTexture = indirectTexture;
  20200. }
  20201. _initColorsTexture() {
  20202. let size = Math.sqrt( this._maxInstanceCount );
  20203. size = Math.ceil( size );
  20204. // 4 floats per RGBA pixel initialized to white
  20205. const colorsArray = new Float32Array( size * size * 4 ).fill( 1 );
  20206. const colorsTexture = new DataTexture( colorsArray, size, size, RGBAFormat, FloatType );
  20207. colorsTexture.colorSpace = ColorManagement.workingColorSpace;
  20208. this._colorsTexture = colorsTexture;
  20209. }
  20210. _initializeGeometry( reference ) {
  20211. const geometry = this.geometry;
  20212. const maxVertexCount = this._maxVertexCount;
  20213. const maxIndexCount = this._maxIndexCount;
  20214. if ( this._geometryInitialized === false ) {
  20215. for ( const attributeName in reference.attributes ) {
  20216. const srcAttribute = reference.getAttribute( attributeName );
  20217. const { array, itemSize, normalized } = srcAttribute;
  20218. const dstArray = new array.constructor( maxVertexCount * itemSize );
  20219. const dstAttribute = new BufferAttribute( dstArray, itemSize, normalized );
  20220. geometry.setAttribute( attributeName, dstAttribute );
  20221. }
  20222. if ( reference.getIndex() !== null ) {
  20223. // Reserve last u16 index for primitive restart.
  20224. const indexArray = maxVertexCount > 65535
  20225. ? new Uint32Array( maxIndexCount )
  20226. : new Uint16Array( maxIndexCount );
  20227. geometry.setIndex( new BufferAttribute( indexArray, 1 ) );
  20228. }
  20229. this._geometryInitialized = true;
  20230. }
  20231. }
  20232. // Make sure the geometry is compatible with the existing combined geometry attributes
  20233. _validateGeometry( geometry ) {
  20234. // check to ensure the geometries are using consistent attributes and indices
  20235. const batchGeometry = this.geometry;
  20236. if ( Boolean( geometry.getIndex() ) !== Boolean( batchGeometry.getIndex() ) ) {
  20237. throw new Error( 'THREE.BatchedMesh: All geometries must consistently have "index".' );
  20238. }
  20239. for ( const attributeName in batchGeometry.attributes ) {
  20240. if ( ! geometry.hasAttribute( attributeName ) ) {
  20241. throw new Error( `THREE.BatchedMesh: Added geometry missing "${ attributeName }". All geometries must have consistent attributes.` );
  20242. }
  20243. const srcAttribute = geometry.getAttribute( attributeName );
  20244. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20245. if ( srcAttribute.itemSize !== dstAttribute.itemSize || srcAttribute.normalized !== dstAttribute.normalized ) {
  20246. throw new Error( 'THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.' );
  20247. }
  20248. }
  20249. }
  20250. /**
  20251. * Validates the instance defined by the given ID.
  20252. *
  20253. * @param {number} instanceId - The instance to validate.
  20254. */
  20255. validateInstanceId( instanceId ) {
  20256. const instanceInfo = this._instanceInfo;
  20257. if ( instanceId < 0 || instanceId >= instanceInfo.length || instanceInfo[ instanceId ].active === false ) {
  20258. throw new Error( `THREE.BatchedMesh: Invalid instanceId ${instanceId}. Instance is either out of range or has been deleted.` );
  20259. }
  20260. }
  20261. /**
  20262. * Validates the geometry defined by the given ID.
  20263. *
  20264. * @param {number} geometryId - The geometry to validate.
  20265. */
  20266. validateGeometryId( geometryId ) {
  20267. const geometryInfoList = this._geometryInfo;
  20268. if ( geometryId < 0 || geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20269. throw new Error( `THREE.BatchedMesh: Invalid geometryId ${geometryId}. Geometry is either out of range or has been deleted.` );
  20270. }
  20271. }
  20272. /**
  20273. * Takes a sort a function that is run before render. The function takes a list of instances to
  20274. * sort and a camera. The objects in the list include a "z" field to perform a depth-ordered sort with.
  20275. *
  20276. * @param {Function} func - The custom sort function.
  20277. * @return {BatchedMesh} A reference to this batched mesh.
  20278. */
  20279. setCustomSort( func ) {
  20280. this.customSort = func;
  20281. return this;
  20282. }
  20283. /**
  20284. * Computes the bounding box, updating {@link BatchedMesh#boundingBox}.
  20285. * Bounding boxes aren't computed by default. They need to be explicitly computed,
  20286. * otherwise they are `null`.
  20287. */
  20288. computeBoundingBox() {
  20289. if ( this.boundingBox === null ) {
  20290. this.boundingBox = new Box3();
  20291. }
  20292. const boundingBox = this.boundingBox;
  20293. const instanceInfo = this._instanceInfo;
  20294. boundingBox.makeEmpty();
  20295. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20296. if ( instanceInfo[ i ].active === false ) continue;
  20297. const geometryId = instanceInfo[ i ].geometryIndex;
  20298. this.getMatrixAt( i, _matrix$1 );
  20299. this.getBoundingBoxAt( geometryId, _box$1 ).applyMatrix4( _matrix$1 );
  20300. boundingBox.union( _box$1 );
  20301. }
  20302. }
  20303. /**
  20304. * Computes the bounding sphere, updating {@link BatchedMesh#boundingSphere}.
  20305. * Bounding spheres aren't computed by default. They need to be explicitly computed,
  20306. * otherwise they are `null`.
  20307. */
  20308. computeBoundingSphere() {
  20309. if ( this.boundingSphere === null ) {
  20310. this.boundingSphere = new Sphere();
  20311. }
  20312. const boundingSphere = this.boundingSphere;
  20313. const instanceInfo = this._instanceInfo;
  20314. boundingSphere.makeEmpty();
  20315. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20316. if ( instanceInfo[ i ].active === false ) continue;
  20317. const geometryId = instanceInfo[ i ].geometryIndex;
  20318. this.getMatrixAt( i, _matrix$1 );
  20319. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  20320. boundingSphere.union( _sphere$2 );
  20321. }
  20322. }
  20323. /**
  20324. * Adds a new instance to the batch using the geometry of the given ID and returns
  20325. * a new id referring to the new instance to be used by other functions.
  20326. *
  20327. * @param {number} geometryId - The ID of a previously added geometry via {@link BatchedMesh#addGeometry}.
  20328. * @return {number} The instance ID.
  20329. */
  20330. addInstance( geometryId ) {
  20331. const atCapacity = this._instanceInfo.length >= this.maxInstanceCount;
  20332. // ensure we're not over geometry
  20333. if ( atCapacity && this._availableInstanceIds.length === 0 ) {
  20334. throw new Error( 'THREE.BatchedMesh: Maximum item count reached.' );
  20335. }
  20336. const instanceInfo = {
  20337. visible: true,
  20338. active: true,
  20339. geometryIndex: geometryId,
  20340. };
  20341. let drawId = null;
  20342. // Prioritize using previously freed instance ids
  20343. if ( this._availableInstanceIds.length > 0 ) {
  20344. this._availableInstanceIds.sort( ascIdSort );
  20345. drawId = this._availableInstanceIds.shift();
  20346. this._instanceInfo[ drawId ] = instanceInfo;
  20347. } else {
  20348. drawId = this._instanceInfo.length;
  20349. this._instanceInfo.push( instanceInfo );
  20350. }
  20351. const matricesTexture = this._matricesTexture;
  20352. _matrix$1.identity().toArray( matricesTexture.image.data, drawId * 16 );
  20353. matricesTexture.needsUpdate = true;
  20354. const colorsTexture = this._colorsTexture;
  20355. if ( colorsTexture ) {
  20356. _whiteColor.toArray( colorsTexture.image.data, drawId * 4 );
  20357. colorsTexture.needsUpdate = true;
  20358. }
  20359. this._visibilityChanged = true;
  20360. return drawId;
  20361. }
  20362. /**
  20363. * Adds the given geometry to the batch and returns the associated
  20364. * geometry id referring to it to be used in other functions.
  20365. *
  20366. * @param {BufferGeometry} geometry - The geometry to add.
  20367. * @param {number} [reservedVertexCount=-1] - Optional parameter specifying the amount of
  20368. * vertex buffer space to reserve for the added geometry. This is necessary if it is planned
  20369. * to set a new geometry at this index at a later time that is larger than the original geometry.
  20370. * Defaults to the length of the given geometry vertex buffer.
  20371. * @param {number} [reservedIndexCount=-1] - Optional parameter specifying the amount of index
  20372. * buffer space to reserve for the added geometry. This is necessary if it is planned to set a
  20373. * new geometry at this index at a later time that is larger than the original geometry. Defaults to
  20374. * the length of the given geometry index buffer.
  20375. * @return {number} The geometry ID.
  20376. */
  20377. addGeometry( geometry, reservedVertexCount = -1, reservedIndexCount = -1 ) {
  20378. this._initializeGeometry( geometry );
  20379. this._validateGeometry( geometry );
  20380. const geometryInfo = {
  20381. // geometry information
  20382. vertexStart: -1,
  20383. vertexCount: -1,
  20384. reservedVertexCount: -1,
  20385. indexStart: -1,
  20386. indexCount: -1,
  20387. reservedIndexCount: -1,
  20388. // draw range information
  20389. start: -1,
  20390. count: -1,
  20391. // state
  20392. boundingBox: null,
  20393. boundingSphere: null,
  20394. active: true,
  20395. };
  20396. const geometryInfoList = this._geometryInfo;
  20397. geometryInfo.vertexStart = this._nextVertexStart;
  20398. geometryInfo.reservedVertexCount = reservedVertexCount === -1 ? geometry.getAttribute( 'position' ).count : reservedVertexCount;
  20399. const index = geometry.getIndex();
  20400. const hasIndex = index !== null;
  20401. if ( hasIndex ) {
  20402. geometryInfo.indexStart = this._nextIndexStart;
  20403. geometryInfo.reservedIndexCount = reservedIndexCount === -1 ? index.count : reservedIndexCount;
  20404. }
  20405. if (
  20406. geometryInfo.indexStart !== -1 &&
  20407. geometryInfo.indexStart + geometryInfo.reservedIndexCount > this._maxIndexCount ||
  20408. geometryInfo.vertexStart + geometryInfo.reservedVertexCount > this._maxVertexCount
  20409. ) {
  20410. throw new Error( 'THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.' );
  20411. }
  20412. // update id
  20413. let geometryId;
  20414. if ( this._availableGeometryIds.length > 0 ) {
  20415. this._availableGeometryIds.sort( ascIdSort );
  20416. geometryId = this._availableGeometryIds.shift();
  20417. geometryInfoList[ geometryId ] = geometryInfo;
  20418. } else {
  20419. geometryId = this._geometryCount;
  20420. this._geometryCount ++;
  20421. geometryInfoList.push( geometryInfo );
  20422. }
  20423. // update the geometry
  20424. this.setGeometryAt( geometryId, geometry );
  20425. // increment the next geometry position
  20426. this._nextIndexStart = geometryInfo.indexStart + geometryInfo.reservedIndexCount;
  20427. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20428. return geometryId;
  20429. }
  20430. /**
  20431. * Replaces the geometry at the given ID with the provided geometry. Throws an error if there
  20432. * is not enough space reserved for geometry. Calling this will change all instances that are
  20433. * rendering that geometry.
  20434. *
  20435. * @param {number} geometryId - The ID of the geometry that should be replaced with the given geometry.
  20436. * @param {BufferGeometry} geometry - The new geometry.
  20437. * @return {number} The geometry ID.
  20438. */
  20439. setGeometryAt( geometryId, geometry ) {
  20440. if ( geometryId >= this._geometryCount ) {
  20441. throw new Error( 'THREE.BatchedMesh: Maximum geometry count reached.' );
  20442. }
  20443. this._validateGeometry( geometry );
  20444. const batchGeometry = this.geometry;
  20445. const hasIndex = batchGeometry.getIndex() !== null;
  20446. const dstIndex = batchGeometry.getIndex();
  20447. const srcIndex = geometry.getIndex();
  20448. const geometryInfo = this._geometryInfo[ geometryId ];
  20449. if (
  20450. hasIndex &&
  20451. srcIndex.count > geometryInfo.reservedIndexCount ||
  20452. geometry.attributes.position.count > geometryInfo.reservedVertexCount
  20453. ) {
  20454. throw new Error( 'THREE.BatchedMesh: Reserved space not large enough for provided geometry.' );
  20455. }
  20456. // copy geometry buffer data over
  20457. const vertexStart = geometryInfo.vertexStart;
  20458. const reservedVertexCount = geometryInfo.reservedVertexCount;
  20459. geometryInfo.vertexCount = geometry.getAttribute( 'position' ).count;
  20460. for ( const attributeName in batchGeometry.attributes ) {
  20461. // copy attribute data
  20462. const srcAttribute = geometry.getAttribute( attributeName );
  20463. const dstAttribute = batchGeometry.getAttribute( attributeName );
  20464. copyAttributeData( srcAttribute, dstAttribute, vertexStart );
  20465. // fill the rest in with zeroes
  20466. const itemSize = srcAttribute.itemSize;
  20467. for ( let i = srcAttribute.count, l = reservedVertexCount; i < l; i ++ ) {
  20468. const index = vertexStart + i;
  20469. for ( let c = 0; c < itemSize; c ++ ) {
  20470. dstAttribute.setComponent( index, c, 0 );
  20471. }
  20472. }
  20473. dstAttribute.needsUpdate = true;
  20474. dstAttribute.addUpdateRange( vertexStart * itemSize, reservedVertexCount * itemSize );
  20475. }
  20476. // copy index
  20477. if ( hasIndex ) {
  20478. const indexStart = geometryInfo.indexStart;
  20479. const reservedIndexCount = geometryInfo.reservedIndexCount;
  20480. geometryInfo.indexCount = geometry.getIndex().count;
  20481. // copy index data over
  20482. for ( let i = 0; i < srcIndex.count; i ++ ) {
  20483. dstIndex.setX( indexStart + i, vertexStart + srcIndex.getX( i ) );
  20484. }
  20485. // fill the rest in with zeroes
  20486. for ( let i = srcIndex.count, l = reservedIndexCount; i < l; i ++ ) {
  20487. dstIndex.setX( indexStart + i, vertexStart );
  20488. }
  20489. dstIndex.needsUpdate = true;
  20490. dstIndex.addUpdateRange( indexStart, geometryInfo.reservedIndexCount );
  20491. }
  20492. // update the draw range
  20493. geometryInfo.start = hasIndex ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20494. geometryInfo.count = hasIndex ? geometryInfo.indexCount : geometryInfo.vertexCount;
  20495. // store the bounding boxes
  20496. geometryInfo.boundingBox = null;
  20497. if ( geometry.boundingBox !== null ) {
  20498. geometryInfo.boundingBox = geometry.boundingBox.clone();
  20499. }
  20500. geometryInfo.boundingSphere = null;
  20501. if ( geometry.boundingSphere !== null ) {
  20502. geometryInfo.boundingSphere = geometry.boundingSphere.clone();
  20503. }
  20504. this._visibilityChanged = true;
  20505. return geometryId;
  20506. }
  20507. /**
  20508. * Deletes the geometry defined by the given ID from this batch. Any instances referencing
  20509. * this geometry will also be removed as a side effect.
  20510. *
  20511. * @param {number} geometryId - The ID of the geometry to remove from the batch.
  20512. * @return {BatchedMesh} A reference to this batched mesh.
  20513. */
  20514. deleteGeometry( geometryId ) {
  20515. const geometryInfoList = this._geometryInfo;
  20516. if ( geometryId >= geometryInfoList.length || geometryInfoList[ geometryId ].active === false ) {
  20517. return this;
  20518. }
  20519. // delete any instances associated with this geometry
  20520. const instanceInfo = this._instanceInfo;
  20521. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20522. if ( instanceInfo[ i ].active && instanceInfo[ i ].geometryIndex === geometryId ) {
  20523. this.deleteInstance( i );
  20524. }
  20525. }
  20526. geometryInfoList[ geometryId ].active = false;
  20527. this._availableGeometryIds.push( geometryId );
  20528. this._visibilityChanged = true;
  20529. return this;
  20530. }
  20531. /**
  20532. * Deletes an existing instance from the batch using the given ID.
  20533. *
  20534. * @param {number} instanceId - The ID of the instance to remove from the batch.
  20535. * @return {BatchedMesh} A reference to this batched mesh.
  20536. */
  20537. deleteInstance( instanceId ) {
  20538. this.validateInstanceId( instanceId );
  20539. this._instanceInfo[ instanceId ].active = false;
  20540. this._availableInstanceIds.push( instanceId );
  20541. this._visibilityChanged = true;
  20542. return this;
  20543. }
  20544. /**
  20545. * Repacks the sub geometries in BatchedMesh to remove any unused space remaining from
  20546. * previously deleted geometry, freeing up space to add new geometry.
  20547. *
  20548. * @return {BatchedMesh} A reference to this batched mesh.
  20549. */
  20550. optimize() {
  20551. // track the next indices to copy data to
  20552. let nextVertexStart = 0;
  20553. let nextIndexStart = 0;
  20554. // Iterate over all geometry ranges in order sorted from earliest in the geometry buffer to latest
  20555. // in the geometry buffer. Because draw range objects can be reused there is no guarantee of their order.
  20556. const geometryInfoList = this._geometryInfo;
  20557. const indices = geometryInfoList
  20558. .map( ( e, i ) => i )
  20559. .sort( ( a, b ) => {
  20560. return geometryInfoList[ a ].vertexStart - geometryInfoList[ b ].vertexStart;
  20561. } );
  20562. const geometry = this.geometry;
  20563. for ( let i = 0, l = geometryInfoList.length; i < l; i ++ ) {
  20564. // if a geometry range is inactive then don't copy anything
  20565. const index = indices[ i ];
  20566. const geometryInfo = geometryInfoList[ index ];
  20567. if ( geometryInfo.active === false ) {
  20568. continue;
  20569. }
  20570. // if a geometry contains an index buffer then shift it, as well
  20571. if ( geometry.index !== null ) {
  20572. if ( geometryInfo.indexStart !== nextIndexStart ) {
  20573. const { indexStart, vertexStart, reservedIndexCount } = geometryInfo;
  20574. const index = geometry.index;
  20575. const array = index.array;
  20576. // shift the index pointers based on how the vertex data will shift
  20577. // adjusting the index must happen first so the original vertex start value is available
  20578. const elementDelta = nextVertexStart - vertexStart;
  20579. for ( let j = indexStart; j < indexStart + reservedIndexCount; j ++ ) {
  20580. array[ j ] = array[ j ] + elementDelta;
  20581. }
  20582. index.array.copyWithin( nextIndexStart, indexStart, indexStart + reservedIndexCount );
  20583. index.addUpdateRange( nextIndexStart, reservedIndexCount );
  20584. index.needsUpdate = true;
  20585. geometryInfo.indexStart = nextIndexStart;
  20586. }
  20587. nextIndexStart += geometryInfo.reservedIndexCount;
  20588. }
  20589. // if a geometry needs to be moved then copy attribute data to overwrite unused space
  20590. if ( geometryInfo.vertexStart !== nextVertexStart ) {
  20591. const { vertexStart, reservedVertexCount } = geometryInfo;
  20592. const attributes = geometry.attributes;
  20593. for ( const key in attributes ) {
  20594. const attribute = attributes[ key ];
  20595. const { array, itemSize } = attribute;
  20596. array.copyWithin( nextVertexStart * itemSize, vertexStart * itemSize, ( vertexStart + reservedVertexCount ) * itemSize );
  20597. attribute.addUpdateRange( nextVertexStart * itemSize, reservedVertexCount * itemSize );
  20598. attribute.needsUpdate = true;
  20599. }
  20600. geometryInfo.vertexStart = nextVertexStart;
  20601. }
  20602. nextVertexStart += geometryInfo.reservedVertexCount;
  20603. geometryInfo.start = geometry.index ? geometryInfo.indexStart : geometryInfo.vertexStart;
  20604. // step the next geometry points to the shifted position
  20605. this._nextIndexStart = geometry.index ? geometryInfo.indexStart + geometryInfo.reservedIndexCount : 0;
  20606. this._nextVertexStart = geometryInfo.vertexStart + geometryInfo.reservedVertexCount;
  20607. }
  20608. this._visibilityChanged = true;
  20609. return this;
  20610. }
  20611. /**
  20612. * Returns the bounding box for the given geometry.
  20613. *
  20614. * @param {number} geometryId - The ID of the geometry to return the bounding box for.
  20615. * @param {Box3} target - The target object that is used to store the method's result.
  20616. * @return {?Box3} The geometry's bounding box. Returns `null` if no geometry has been found for the given ID.
  20617. */
  20618. getBoundingBoxAt( geometryId, target ) {
  20619. if ( geometryId >= this._geometryCount ) {
  20620. return null;
  20621. }
  20622. // compute bounding box
  20623. const geometry = this.geometry;
  20624. const geometryInfo = this._geometryInfo[ geometryId ];
  20625. if ( geometryInfo.boundingBox === null ) {
  20626. const box = new Box3();
  20627. const index = geometry.index;
  20628. const position = geometry.attributes.position;
  20629. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20630. let iv = i;
  20631. if ( index ) {
  20632. iv = index.getX( iv );
  20633. }
  20634. box.expandByPoint( _vector$5.fromBufferAttribute( position, iv ) );
  20635. }
  20636. geometryInfo.boundingBox = box;
  20637. }
  20638. target.copy( geometryInfo.boundingBox );
  20639. return target;
  20640. }
  20641. /**
  20642. * Returns the bounding sphere for the given geometry.
  20643. *
  20644. * @param {number} geometryId - The ID of the geometry to return the bounding sphere for.
  20645. * @param {Sphere} target - The target object that is used to store the method's result.
  20646. * @return {?Sphere} The geometry's bounding sphere. Returns `null` if no geometry has been found for the given ID.
  20647. */
  20648. getBoundingSphereAt( geometryId, target ) {
  20649. if ( geometryId >= this._geometryCount ) {
  20650. return null;
  20651. }
  20652. // compute bounding sphere
  20653. const geometry = this.geometry;
  20654. const geometryInfo = this._geometryInfo[ geometryId ];
  20655. if ( geometryInfo.boundingSphere === null ) {
  20656. const sphere = new Sphere();
  20657. this.getBoundingBoxAt( geometryId, _box$1 );
  20658. _box$1.getCenter( sphere.center );
  20659. const index = geometry.index;
  20660. const position = geometry.attributes.position;
  20661. let maxRadiusSq = 0;
  20662. for ( let i = geometryInfo.start, l = geometryInfo.start + geometryInfo.count; i < l; i ++ ) {
  20663. let iv = i;
  20664. if ( index ) {
  20665. iv = index.getX( iv );
  20666. }
  20667. _vector$5.fromBufferAttribute( position, iv );
  20668. maxRadiusSq = Math.max( maxRadiusSq, sphere.center.distanceToSquared( _vector$5 ) );
  20669. }
  20670. sphere.radius = Math.sqrt( maxRadiusSq );
  20671. geometryInfo.boundingSphere = sphere;
  20672. }
  20673. target.copy( geometryInfo.boundingSphere );
  20674. return target;
  20675. }
  20676. /**
  20677. * Sets the given local transformation matrix to the defined instance.
  20678. * Negatively scaled matrices are not supported.
  20679. *
  20680. * @param {number} instanceId - The ID of an instance to set the matrix of.
  20681. * @param {Matrix4} matrix - A 4x4 matrix representing the local transformation of a single instance.
  20682. * @return {BatchedMesh} A reference to this batched mesh.
  20683. */
  20684. setMatrixAt( instanceId, matrix ) {
  20685. this.validateInstanceId( instanceId );
  20686. const matricesTexture = this._matricesTexture;
  20687. const matricesArray = this._matricesTexture.image.data;
  20688. matrix.toArray( matricesArray, instanceId * 16 );
  20689. matricesTexture.needsUpdate = true;
  20690. return this;
  20691. }
  20692. /**
  20693. * Returns the local transformation matrix of the defined instance.
  20694. *
  20695. * @param {number} instanceId - The ID of an instance to get the matrix of.
  20696. * @param {Matrix4} matrix - The target object that is used to store the method's result.
  20697. * @return {Matrix4} The instance's local transformation matrix.
  20698. */
  20699. getMatrixAt( instanceId, matrix ) {
  20700. this.validateInstanceId( instanceId );
  20701. return matrix.fromArray( this._matricesTexture.image.data, instanceId * 16 );
  20702. }
  20703. /**
  20704. * Sets the given color to the defined instance.
  20705. *
  20706. * @param {number} instanceId - The ID of an instance to set the color of.
  20707. * @param {Color} color - The color to set the instance to.
  20708. * @return {BatchedMesh} A reference to this batched mesh.
  20709. */
  20710. setColorAt( instanceId, color ) {
  20711. this.validateInstanceId( instanceId );
  20712. if ( this._colorsTexture === null ) {
  20713. this._initColorsTexture();
  20714. }
  20715. color.toArray( this._colorsTexture.image.data, instanceId * 4 );
  20716. this._colorsTexture.needsUpdate = true;
  20717. return this;
  20718. }
  20719. /**
  20720. * Returns the color of the defined instance.
  20721. *
  20722. * @param {number} instanceId - The ID of an instance to get the color of.
  20723. * @param {Color} color - The target object that is used to store the method's result.
  20724. * @return {Color} The instance's color.
  20725. */
  20726. getColorAt( instanceId, color ) {
  20727. this.validateInstanceId( instanceId );
  20728. return color.fromArray( this._colorsTexture.image.data, instanceId * 4 );
  20729. }
  20730. /**
  20731. * Sets the visibility of the instance.
  20732. *
  20733. * @param {number} instanceId - The id of the instance to set the visibility of.
  20734. * @param {boolean} visible - Whether the instance is visible or not.
  20735. * @return {BatchedMesh} A reference to this batched mesh.
  20736. */
  20737. setVisibleAt( instanceId, visible ) {
  20738. this.validateInstanceId( instanceId );
  20739. if ( this._instanceInfo[ instanceId ].visible === visible ) {
  20740. return this;
  20741. }
  20742. this._instanceInfo[ instanceId ].visible = visible;
  20743. this._visibilityChanged = true;
  20744. return this;
  20745. }
  20746. /**
  20747. * Returns the visibility state of the defined instance.
  20748. *
  20749. * @param {number} instanceId - The ID of an instance to get the visibility state of.
  20750. * @return {boolean} Whether the instance is visible or not.
  20751. */
  20752. getVisibleAt( instanceId ) {
  20753. this.validateInstanceId( instanceId );
  20754. return this._instanceInfo[ instanceId ].visible;
  20755. }
  20756. /**
  20757. * Sets the geometry ID of the instance at the given index.
  20758. *
  20759. * @param {number} instanceId - The ID of the instance to set the geometry ID of.
  20760. * @param {number} geometryId - The geometry ID to be use by the instance.
  20761. * @return {BatchedMesh} A reference to this batched mesh.
  20762. */
  20763. setGeometryIdAt( instanceId, geometryId ) {
  20764. this.validateInstanceId( instanceId );
  20765. this.validateGeometryId( geometryId );
  20766. this._instanceInfo[ instanceId ].geometryIndex = geometryId;
  20767. return this;
  20768. }
  20769. /**
  20770. * Returns the geometry ID of the defined instance.
  20771. *
  20772. * @param {number} instanceId - The ID of an instance to get the geometry ID of.
  20773. * @return {number} The instance's geometry ID.
  20774. */
  20775. getGeometryIdAt( instanceId ) {
  20776. this.validateInstanceId( instanceId );
  20777. return this._instanceInfo[ instanceId ].geometryIndex;
  20778. }
  20779. /**
  20780. * Get the range representing the subset of triangles related to the attached geometry,
  20781. * indicating the starting offset and count, or `null` if invalid.
  20782. *
  20783. * @param {number} geometryId - The id of the geometry to get the range of.
  20784. * @param {Object} [target] - The target object that is used to store the method's result.
  20785. * @return {{
  20786. * vertexStart:number,vertexCount:number,reservedVertexCount:number,
  20787. * indexStart:number,indexCount:number,reservedIndexCount:number,
  20788. * start:number,count:number
  20789. * }} The result object with range data.
  20790. */
  20791. getGeometryRangeAt( geometryId, target = {} ) {
  20792. this.validateGeometryId( geometryId );
  20793. const geometryInfo = this._geometryInfo[ geometryId ];
  20794. target.vertexStart = geometryInfo.vertexStart;
  20795. target.vertexCount = geometryInfo.vertexCount;
  20796. target.reservedVertexCount = geometryInfo.reservedVertexCount;
  20797. target.indexStart = geometryInfo.indexStart;
  20798. target.indexCount = geometryInfo.indexCount;
  20799. target.reservedIndexCount = geometryInfo.reservedIndexCount;
  20800. target.start = geometryInfo.start;
  20801. target.count = geometryInfo.count;
  20802. return target;
  20803. }
  20804. /**
  20805. * Resizes the necessary buffers to support the provided number of instances.
  20806. * If the provided arguments shrink the number of instances but there are not enough
  20807. * unused Ids at the end of the list then an error is thrown.
  20808. *
  20809. * @param {number} maxInstanceCount - The max number of individual instances that can be added and rendered by the batch.
  20810. */
  20811. setInstanceCount( maxInstanceCount ) {
  20812. // shrink the available instances as much as possible
  20813. const availableInstanceIds = this._availableInstanceIds;
  20814. const instanceInfo = this._instanceInfo;
  20815. availableInstanceIds.sort( ascIdSort );
  20816. while ( availableInstanceIds[ availableInstanceIds.length - 1 ] === instanceInfo.length - 1 ) {
  20817. instanceInfo.pop();
  20818. availableInstanceIds.pop();
  20819. }
  20820. // throw an error if it can't be shrunk to the desired size
  20821. if ( maxInstanceCount < instanceInfo.length ) {
  20822. throw new Error( `BatchedMesh: Instance ids outside the range ${ maxInstanceCount } are being used. Cannot shrink instance count.` );
  20823. }
  20824. // copy the multi draw counts
  20825. const multiDrawCounts = new Int32Array( maxInstanceCount );
  20826. const multiDrawStarts = new Int32Array( maxInstanceCount );
  20827. copyArrayContents( this._multiDrawCounts, multiDrawCounts );
  20828. copyArrayContents( this._multiDrawStarts, multiDrawStarts );
  20829. this._multiDrawCounts = multiDrawCounts;
  20830. this._multiDrawStarts = multiDrawStarts;
  20831. this._maxInstanceCount = maxInstanceCount;
  20832. // update texture data for instance sampling
  20833. const indirectTexture = this._indirectTexture;
  20834. const matricesTexture = this._matricesTexture;
  20835. const colorsTexture = this._colorsTexture;
  20836. indirectTexture.dispose();
  20837. this._initIndirectTexture();
  20838. copyArrayContents( indirectTexture.image.data, this._indirectTexture.image.data );
  20839. matricesTexture.dispose();
  20840. this._initMatricesTexture();
  20841. copyArrayContents( matricesTexture.image.data, this._matricesTexture.image.data );
  20842. if ( colorsTexture ) {
  20843. colorsTexture.dispose();
  20844. this._initColorsTexture();
  20845. copyArrayContents( colorsTexture.image.data, this._colorsTexture.image.data );
  20846. }
  20847. }
  20848. /**
  20849. * Resizes the available space in the batch's vertex and index buffer attributes to the provided sizes.
  20850. * If the provided arguments shrink the geometry buffers but there is not enough unused space at the
  20851. * end of the geometry attributes then an error is thrown.
  20852. *
  20853. * @param {number} maxVertexCount - The maximum number of vertices to be used by all unique geometries to resize to.
  20854. * @param {number} maxIndexCount - The maximum number of indices to be used by all unique geometries to resize to.
  20855. */
  20856. setGeometrySize( maxVertexCount, maxIndexCount ) {
  20857. // Check if we can shrink to the requested vertex attribute size
  20858. const validRanges = [ ...this._geometryInfo ].filter( info => info.active );
  20859. const requiredVertexLength = Math.max( ...validRanges.map( range => range.vertexStart + range.reservedVertexCount ) );
  20860. if ( requiredVertexLength > maxVertexCount ) {
  20861. throw new Error( `BatchedMesh: Geometry vertex values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20862. }
  20863. // Check if we can shrink to the requested index attribute size
  20864. if ( this.geometry.index ) {
  20865. const requiredIndexLength = Math.max( ...validRanges.map( range => range.indexStart + range.reservedIndexCount ) );
  20866. if ( requiredIndexLength > maxIndexCount ) {
  20867. throw new Error( `BatchedMesh: Geometry index values are being used outside the range ${ maxIndexCount }. Cannot shrink further.` );
  20868. }
  20869. }
  20870. //
  20871. // dispose of the previous geometry
  20872. const oldGeometry = this.geometry;
  20873. oldGeometry.dispose();
  20874. // recreate the geometry needed based on the previous variant
  20875. this._maxVertexCount = maxVertexCount;
  20876. this._maxIndexCount = maxIndexCount;
  20877. if ( this._geometryInitialized ) {
  20878. this._geometryInitialized = false;
  20879. this.geometry = new BufferGeometry();
  20880. this._initializeGeometry( oldGeometry );
  20881. }
  20882. // copy data from the previous geometry
  20883. const geometry = this.geometry;
  20884. if ( oldGeometry.index ) {
  20885. copyArrayContents( oldGeometry.index.array, geometry.index.array );
  20886. }
  20887. for ( const key in oldGeometry.attributes ) {
  20888. copyArrayContents( oldGeometry.attributes[ key ].array, geometry.attributes[ key ].array );
  20889. }
  20890. }
  20891. raycast( raycaster, intersects ) {
  20892. const instanceInfo = this._instanceInfo;
  20893. const geometryInfoList = this._geometryInfo;
  20894. const matrixWorld = this.matrixWorld;
  20895. const batchGeometry = this.geometry;
  20896. // iterate over each geometry
  20897. _mesh.material = this.material;
  20898. _mesh.geometry.index = batchGeometry.index;
  20899. _mesh.geometry.attributes = batchGeometry.attributes;
  20900. if ( _mesh.geometry.boundingBox === null ) {
  20901. _mesh.geometry.boundingBox = new Box3();
  20902. }
  20903. if ( _mesh.geometry.boundingSphere === null ) {
  20904. _mesh.geometry.boundingSphere = new Sphere();
  20905. }
  20906. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  20907. if ( ! instanceInfo[ i ].visible || ! instanceInfo[ i ].active ) {
  20908. continue;
  20909. }
  20910. const geometryId = instanceInfo[ i ].geometryIndex;
  20911. const geometryInfo = geometryInfoList[ geometryId ];
  20912. _mesh.geometry.setDrawRange( geometryInfo.start, geometryInfo.count );
  20913. // get the intersects
  20914. this.getMatrixAt( i, _mesh.matrixWorld ).premultiply( matrixWorld );
  20915. this.getBoundingBoxAt( geometryId, _mesh.geometry.boundingBox );
  20916. this.getBoundingSphereAt( geometryId, _mesh.geometry.boundingSphere );
  20917. _mesh.raycast( raycaster, _batchIntersects );
  20918. // add batch id to the intersects
  20919. for ( let j = 0, l = _batchIntersects.length; j < l; j ++ ) {
  20920. const intersect = _batchIntersects[ j ];
  20921. intersect.object = this;
  20922. intersect.batchId = i;
  20923. intersects.push( intersect );
  20924. }
  20925. _batchIntersects.length = 0;
  20926. }
  20927. _mesh.material = null;
  20928. _mesh.geometry.index = null;
  20929. _mesh.geometry.attributes = {};
  20930. _mesh.geometry.setDrawRange( 0, Infinity );
  20931. }
  20932. copy( source ) {
  20933. super.copy( source );
  20934. this.geometry = source.geometry.clone();
  20935. this.perObjectFrustumCulled = source.perObjectFrustumCulled;
  20936. this.sortObjects = source.sortObjects;
  20937. this.boundingBox = source.boundingBox !== null ? source.boundingBox.clone() : null;
  20938. this.boundingSphere = source.boundingSphere !== null ? source.boundingSphere.clone() : null;
  20939. this._geometryInfo = source._geometryInfo.map( info => ( {
  20940. ...info,
  20941. boundingBox: info.boundingBox !== null ? info.boundingBox.clone() : null,
  20942. boundingSphere: info.boundingSphere !== null ? info.boundingSphere.clone() : null,
  20943. } ) );
  20944. this._instanceInfo = source._instanceInfo.map( info => ( { ...info } ) );
  20945. this._availableInstanceIds = source._availableInstanceIds.slice();
  20946. this._availableGeometryIds = source._availableGeometryIds.slice();
  20947. this._nextIndexStart = source._nextIndexStart;
  20948. this._nextVertexStart = source._nextVertexStart;
  20949. this._geometryCount = source._geometryCount;
  20950. this._maxInstanceCount = source._maxInstanceCount;
  20951. this._maxVertexCount = source._maxVertexCount;
  20952. this._maxIndexCount = source._maxIndexCount;
  20953. this._geometryInitialized = source._geometryInitialized;
  20954. this._multiDrawCounts = source._multiDrawCounts.slice();
  20955. this._multiDrawStarts = source._multiDrawStarts.slice();
  20956. this._indirectTexture = source._indirectTexture.clone();
  20957. this._indirectTexture.image.data = this._indirectTexture.image.data.slice();
  20958. this._matricesTexture = source._matricesTexture.clone();
  20959. this._matricesTexture.image.data = this._matricesTexture.image.data.slice();
  20960. if ( this._colorsTexture !== null ) {
  20961. this._colorsTexture = source._colorsTexture.clone();
  20962. this._colorsTexture.image.data = this._colorsTexture.image.data.slice();
  20963. }
  20964. return this;
  20965. }
  20966. /**
  20967. * Frees the GPU-related resources allocated by this instance. Call this
  20968. * method whenever this instance is no longer used in your app.
  20969. */
  20970. dispose() {
  20971. // Assuming the geometry is not shared with other meshes
  20972. this.geometry.dispose();
  20973. this._matricesTexture.dispose();
  20974. this._matricesTexture = null;
  20975. this._indirectTexture.dispose();
  20976. this._indirectTexture = null;
  20977. if ( this._colorsTexture !== null ) {
  20978. this._colorsTexture.dispose();
  20979. this._colorsTexture = null;
  20980. }
  20981. }
  20982. onBeforeRender( renderer, scene, camera, geometry, material/*, _group*/ ) {
  20983. // if visibility has not changed and frustum culling and object sorting is not required
  20984. // then skip iterating over all items
  20985. if ( ! this._visibilityChanged && ! this.perObjectFrustumCulled && ! this.sortObjects ) {
  20986. return;
  20987. }
  20988. // the indexed version of the multi draw function requires specifying the start
  20989. // offset in bytes.
  20990. const index = geometry.getIndex();
  20991. const bytesPerElement = index === null ? 1 : index.array.BYTES_PER_ELEMENT;
  20992. const instanceInfo = this._instanceInfo;
  20993. const multiDrawStarts = this._multiDrawStarts;
  20994. const multiDrawCounts = this._multiDrawCounts;
  20995. const geometryInfoList = this._geometryInfo;
  20996. const perObjectFrustumCulled = this.perObjectFrustumCulled;
  20997. const indirectTexture = this._indirectTexture;
  20998. const indirectArray = indirectTexture.image.data;
  20999. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  21000. // prepare the frustum in the local frame
  21001. if ( perObjectFrustumCulled && ! camera.isArrayCamera ) {
  21002. _matrix$1
  21003. .multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse )
  21004. .multiply( this.matrixWorld );
  21005. _frustum.setFromProjectionMatrix(
  21006. _matrix$1,
  21007. camera.coordinateSystem,
  21008. camera.reversedDepth
  21009. );
  21010. }
  21011. let multiDrawCount = 0;
  21012. if ( this.sortObjects ) {
  21013. // get the camera position in the local frame
  21014. _matrix$1.copy( this.matrixWorld ).invert();
  21015. _vector$5.setFromMatrixPosition( camera.matrixWorld ).applyMatrix4( _matrix$1 );
  21016. _forward$1.set( 0, 0, -1 ).transformDirection( camera.matrixWorld ).transformDirection( _matrix$1 );
  21017. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21018. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21019. const geometryId = instanceInfo[ i ].geometryIndex;
  21020. // get the bounds in world space
  21021. this.getMatrixAt( i, _matrix$1 );
  21022. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21023. // determine whether the batched geometry is within the frustum
  21024. let culled = false;
  21025. if ( perObjectFrustumCulled ) {
  21026. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21027. }
  21028. if ( ! culled ) {
  21029. // get the distance from camera used for sorting
  21030. const geometryInfo = geometryInfoList[ geometryId ];
  21031. const z = _temp.subVectors( _sphere$2.center, _vector$5 ).dot( _forward$1 );
  21032. _renderList.push( geometryInfo.start, geometryInfo.count, z, i );
  21033. }
  21034. }
  21035. }
  21036. // Sort the draw ranges and prep for rendering
  21037. const list = _renderList.list;
  21038. const customSort = this.customSort;
  21039. if ( customSort === null ) {
  21040. list.sort( material.transparent ? sortTransparent : sortOpaque );
  21041. } else {
  21042. customSort.call( this, list, camera );
  21043. }
  21044. for ( let i = 0, l = list.length; i < l; i ++ ) {
  21045. const item = list[ i ];
  21046. multiDrawStarts[ multiDrawCount ] = item.start * bytesPerElement;
  21047. multiDrawCounts[ multiDrawCount ] = item.count;
  21048. indirectArray[ multiDrawCount ] = item.index;
  21049. multiDrawCount ++;
  21050. }
  21051. _renderList.reset();
  21052. } else {
  21053. for ( let i = 0, l = instanceInfo.length; i < l; i ++ ) {
  21054. if ( instanceInfo[ i ].visible && instanceInfo[ i ].active ) {
  21055. const geometryId = instanceInfo[ i ].geometryIndex;
  21056. // determine whether the batched geometry is within the frustum
  21057. let culled = false;
  21058. if ( perObjectFrustumCulled ) {
  21059. // get the bounds in world space
  21060. this.getMatrixAt( i, _matrix$1 );
  21061. this.getBoundingSphereAt( geometryId, _sphere$2 ).applyMatrix4( _matrix$1 );
  21062. culled = ! frustum.intersectsSphere( _sphere$2, camera );
  21063. }
  21064. if ( ! culled ) {
  21065. const geometryInfo = geometryInfoList[ geometryId ];
  21066. multiDrawStarts[ multiDrawCount ] = geometryInfo.start * bytesPerElement;
  21067. multiDrawCounts[ multiDrawCount ] = geometryInfo.count;
  21068. indirectArray[ multiDrawCount ] = i;
  21069. multiDrawCount ++;
  21070. }
  21071. }
  21072. }
  21073. }
  21074. indirectTexture.needsUpdate = true;
  21075. this._multiDrawCount = multiDrawCount;
  21076. this._visibilityChanged = false;
  21077. }
  21078. onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial/* , group */ ) {
  21079. this.onBeforeRender( renderer, null, shadowCamera, geometry, depthMaterial );
  21080. }
  21081. }
  21082. /**
  21083. * A material for rendering line primitives.
  21084. *
  21085. * Materials define the appearance of renderable 3D objects.
  21086. *
  21087. * ```js
  21088. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  21089. * ```
  21090. *
  21091. * @augments Material
  21092. */
  21093. class LineBasicMaterial extends Material {
  21094. /**
  21095. * Constructs a new line basic material.
  21096. *
  21097. * @param {Object} [parameters] - An object with one or more properties
  21098. * defining the material's appearance. Any property of the material
  21099. * (including any property from inherited materials) can be passed
  21100. * in here. Color values can be passed any type of value accepted
  21101. * by {@link Color#set}.
  21102. */
  21103. constructor( parameters ) {
  21104. super();
  21105. /**
  21106. * This flag can be used for type testing.
  21107. *
  21108. * @type {boolean}
  21109. * @readonly
  21110. * @default true
  21111. */
  21112. this.isLineBasicMaterial = true;
  21113. this.type = 'LineBasicMaterial';
  21114. /**
  21115. * Color of the material.
  21116. *
  21117. * @type {Color}
  21118. * @default (1,1,1)
  21119. */
  21120. this.color = new Color( 0xffffff );
  21121. /**
  21122. * Sets the color of the lines using data from a texture. The texture map
  21123. * color is modulated by the diffuse `color`.
  21124. *
  21125. * @type {?Texture}
  21126. * @default null
  21127. */
  21128. this.map = null;
  21129. /**
  21130. * Controls line thickness or lines.
  21131. *
  21132. * Can only be used with {@link SVGRenderer}. WebGL and WebGPU
  21133. * ignore this setting and always render line primitives with a
  21134. * width of one pixel.
  21135. *
  21136. * @type {number}
  21137. * @default 1
  21138. */
  21139. this.linewidth = 1;
  21140. /**
  21141. * Defines appearance of line ends.
  21142. *
  21143. * Can only be used with {@link SVGRenderer}.
  21144. *
  21145. * @type {('butt'|'round'|'square')}
  21146. * @default 'round'
  21147. */
  21148. this.linecap = 'round';
  21149. /**
  21150. * Defines appearance of line joints.
  21151. *
  21152. * Can only be used with {@link SVGRenderer}.
  21153. *
  21154. * @type {('round'|'bevel'|'miter')}
  21155. * @default 'round'
  21156. */
  21157. this.linejoin = 'round';
  21158. /**
  21159. * Whether the material is affected by fog or not.
  21160. *
  21161. * @type {boolean}
  21162. * @default true
  21163. */
  21164. this.fog = true;
  21165. this.setValues( parameters );
  21166. }
  21167. copy( source ) {
  21168. super.copy( source );
  21169. this.color.copy( source.color );
  21170. this.map = source.map;
  21171. this.linewidth = source.linewidth;
  21172. this.linecap = source.linecap;
  21173. this.linejoin = source.linejoin;
  21174. this.fog = source.fog;
  21175. return this;
  21176. }
  21177. }
  21178. const _vStart = /*@__PURE__*/ new Vector3();
  21179. const _vEnd = /*@__PURE__*/ new Vector3();
  21180. const _inverseMatrix$1 = /*@__PURE__*/ new Matrix4();
  21181. const _ray$1 = /*@__PURE__*/ new Ray();
  21182. const _sphere$1 = /*@__PURE__*/ new Sphere();
  21183. const _intersectPointOnRay = /*@__PURE__*/ new Vector3();
  21184. const _intersectPointOnSegment = /*@__PURE__*/ new Vector3();
  21185. /**
  21186. * A continuous line. The line are rendered by connecting consecutive
  21187. * vertices with straight lines.
  21188. *
  21189. * ```js
  21190. * const material = new THREE.LineBasicMaterial( { color: 0x0000ff } );
  21191. *
  21192. * const points = [];
  21193. * points.push( new THREE.Vector3( - 10, 0, 0 ) );
  21194. * points.push( new THREE.Vector3( 0, 10, 0 ) );
  21195. * points.push( new THREE.Vector3( 10, 0, 0 ) );
  21196. *
  21197. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  21198. *
  21199. * const line = new THREE.Line( geometry, material );
  21200. * scene.add( line );
  21201. * ```
  21202. *
  21203. * @augments Object3D
  21204. */
  21205. class Line extends Object3D {
  21206. /**
  21207. * Constructs a new line.
  21208. *
  21209. * @param {BufferGeometry} [geometry] - The line geometry.
  21210. * @param {Material|Array<Material>} [material] - The line material.
  21211. */
  21212. constructor( geometry = new BufferGeometry(), material = new LineBasicMaterial() ) {
  21213. super();
  21214. /**
  21215. * This flag can be used for type testing.
  21216. *
  21217. * @type {boolean}
  21218. * @readonly
  21219. * @default true
  21220. */
  21221. this.isLine = true;
  21222. this.type = 'Line';
  21223. /**
  21224. * The line geometry.
  21225. *
  21226. * @type {BufferGeometry}
  21227. */
  21228. this.geometry = geometry;
  21229. /**
  21230. * The line material.
  21231. *
  21232. * @type {Material|Array<Material>}
  21233. * @default LineBasicMaterial
  21234. */
  21235. this.material = material;
  21236. /**
  21237. * A dictionary representing the morph targets in the geometry. The key is the
  21238. * morph targets name, the value its attribute index. This member is `undefined`
  21239. * by default and only set when morph targets are detected in the geometry.
  21240. *
  21241. * @type {Object<String,number>|undefined}
  21242. * @default undefined
  21243. */
  21244. this.morphTargetDictionary = undefined;
  21245. /**
  21246. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21247. * is applied. This member is `undefined` by default and only set when morph targets are
  21248. * detected in the geometry.
  21249. *
  21250. * @type {Array<number>|undefined}
  21251. * @default undefined
  21252. */
  21253. this.morphTargetInfluences = undefined;
  21254. this.updateMorphTargets();
  21255. }
  21256. copy( source, recursive ) {
  21257. super.copy( source, recursive );
  21258. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21259. this.geometry = source.geometry;
  21260. return this;
  21261. }
  21262. /**
  21263. * Computes an array of distance values which are necessary for rendering dashed lines.
  21264. * For each vertex in the geometry, the method calculates the cumulative length from the
  21265. * current point to the very beginning of the line.
  21266. *
  21267. * @return {Line} A reference to this line.
  21268. */
  21269. computeLineDistances() {
  21270. const geometry = this.geometry;
  21271. // we assume non-indexed geometry
  21272. if ( geometry.index === null ) {
  21273. const positionAttribute = geometry.attributes.position;
  21274. const lineDistances = [ 0 ];
  21275. for ( let i = 1, l = positionAttribute.count; i < l; i ++ ) {
  21276. _vStart.fromBufferAttribute( positionAttribute, i - 1 );
  21277. _vEnd.fromBufferAttribute( positionAttribute, i );
  21278. lineDistances[ i ] = lineDistances[ i - 1 ];
  21279. lineDistances[ i ] += _vStart.distanceTo( _vEnd );
  21280. }
  21281. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21282. } else {
  21283. warn( 'Line.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21284. }
  21285. return this;
  21286. }
  21287. /**
  21288. * Computes intersection points between a casted ray and this line.
  21289. *
  21290. * @param {Raycaster} raycaster - The raycaster.
  21291. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21292. */
  21293. raycast( raycaster, intersects ) {
  21294. const geometry = this.geometry;
  21295. const matrixWorld = this.matrixWorld;
  21296. const threshold = raycaster.params.Line.threshold;
  21297. const drawRange = geometry.drawRange;
  21298. // Checking boundingSphere distance to ray
  21299. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21300. _sphere$1.copy( geometry.boundingSphere );
  21301. _sphere$1.applyMatrix4( matrixWorld );
  21302. _sphere$1.radius += threshold;
  21303. if ( raycaster.ray.intersectsSphere( _sphere$1 ) === false ) return;
  21304. //
  21305. _inverseMatrix$1.copy( matrixWorld ).invert();
  21306. _ray$1.copy( raycaster.ray ).applyMatrix4( _inverseMatrix$1 );
  21307. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21308. const localThresholdSq = localThreshold * localThreshold;
  21309. const step = this.isLineSegments ? 2 : 1;
  21310. const index = geometry.index;
  21311. const attributes = geometry.attributes;
  21312. const positionAttribute = attributes.position;
  21313. if ( index !== null ) {
  21314. const start = Math.max( 0, drawRange.start );
  21315. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21316. for ( let i = start, l = end - 1; i < l; i += step ) {
  21317. const a = index.getX( i );
  21318. const b = index.getX( i + 1 );
  21319. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, i );
  21320. if ( intersect ) {
  21321. intersects.push( intersect );
  21322. }
  21323. }
  21324. if ( this.isLineLoop ) {
  21325. const a = index.getX( end - 1 );
  21326. const b = index.getX( start );
  21327. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, a, b, end - 1 );
  21328. if ( intersect ) {
  21329. intersects.push( intersect );
  21330. }
  21331. }
  21332. } else {
  21333. const start = Math.max( 0, drawRange.start );
  21334. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21335. for ( let i = start, l = end - 1; i < l; i += step ) {
  21336. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, i, i + 1, i );
  21337. if ( intersect ) {
  21338. intersects.push( intersect );
  21339. }
  21340. }
  21341. if ( this.isLineLoop ) {
  21342. const intersect = checkIntersection( this, raycaster, _ray$1, localThresholdSq, end - 1, start, end - 1 );
  21343. if ( intersect ) {
  21344. intersects.push( intersect );
  21345. }
  21346. }
  21347. }
  21348. }
  21349. /**
  21350. * Sets the values of {@link Line#morphTargetDictionary} and {@link Line#morphTargetInfluences}
  21351. * to make sure existing morph targets can influence this 3D object.
  21352. */
  21353. updateMorphTargets() {
  21354. const geometry = this.geometry;
  21355. const morphAttributes = geometry.morphAttributes;
  21356. const keys = Object.keys( morphAttributes );
  21357. if ( keys.length > 0 ) {
  21358. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21359. if ( morphAttribute !== undefined ) {
  21360. this.morphTargetInfluences = [];
  21361. this.morphTargetDictionary = {};
  21362. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21363. const name = morphAttribute[ m ].name || String( m );
  21364. this.morphTargetInfluences.push( 0 );
  21365. this.morphTargetDictionary[ name ] = m;
  21366. }
  21367. }
  21368. }
  21369. }
  21370. }
  21371. function checkIntersection( object, raycaster, ray, thresholdSq, a, b, i ) {
  21372. const positionAttribute = object.geometry.attributes.position;
  21373. _vStart.fromBufferAttribute( positionAttribute, a );
  21374. _vEnd.fromBufferAttribute( positionAttribute, b );
  21375. const distSq = ray.distanceSqToSegment( _vStart, _vEnd, _intersectPointOnRay, _intersectPointOnSegment );
  21376. if ( distSq > thresholdSq ) return;
  21377. _intersectPointOnRay.applyMatrix4( object.matrixWorld ); // Move back to world space for distance calculation
  21378. const distance = raycaster.ray.origin.distanceTo( _intersectPointOnRay );
  21379. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21380. return {
  21381. distance: distance,
  21382. // What do we want? intersection point on the ray or on the segment??
  21383. // point: raycaster.ray.at( distance ),
  21384. point: _intersectPointOnSegment.clone().applyMatrix4( object.matrixWorld ),
  21385. index: i,
  21386. face: null,
  21387. faceIndex: null,
  21388. barycoord: null,
  21389. object: object
  21390. };
  21391. }
  21392. const _start = /*@__PURE__*/ new Vector3();
  21393. const _end = /*@__PURE__*/ new Vector3();
  21394. /**
  21395. * A series of lines drawn between pairs of vertices.
  21396. *
  21397. * @augments Line
  21398. */
  21399. class LineSegments extends Line {
  21400. /**
  21401. * Constructs a new line segments.
  21402. *
  21403. * @param {BufferGeometry} [geometry] - The line geometry.
  21404. * @param {Material|Array<Material>} [material] - The line material.
  21405. */
  21406. constructor( geometry, material ) {
  21407. super( geometry, material );
  21408. /**
  21409. * This flag can be used for type testing.
  21410. *
  21411. * @type {boolean}
  21412. * @readonly
  21413. * @default true
  21414. */
  21415. this.isLineSegments = true;
  21416. this.type = 'LineSegments';
  21417. }
  21418. computeLineDistances() {
  21419. const geometry = this.geometry;
  21420. // we assume non-indexed geometry
  21421. if ( geometry.index === null ) {
  21422. const positionAttribute = geometry.attributes.position;
  21423. const lineDistances = [];
  21424. for ( let i = 0, l = positionAttribute.count; i < l; i += 2 ) {
  21425. _start.fromBufferAttribute( positionAttribute, i );
  21426. _end.fromBufferAttribute( positionAttribute, i + 1 );
  21427. lineDistances[ i ] = ( i === 0 ) ? 0 : lineDistances[ i - 1 ];
  21428. lineDistances[ i + 1 ] = lineDistances[ i ] + _start.distanceTo( _end );
  21429. }
  21430. geometry.setAttribute( 'lineDistance', new Float32BufferAttribute( lineDistances, 1 ) );
  21431. } else {
  21432. warn( 'LineSegments.computeLineDistances(): Computation only possible with non-indexed BufferGeometry.' );
  21433. }
  21434. return this;
  21435. }
  21436. }
  21437. /**
  21438. * A continuous line. This is nearly the same as {@link Line} the only difference
  21439. * is that the last vertex is connected with the first vertex in order to close
  21440. * the line to form a loop.
  21441. *
  21442. * @augments Line
  21443. */
  21444. class LineLoop extends Line {
  21445. /**
  21446. * Constructs a new line loop.
  21447. *
  21448. * @param {BufferGeometry} [geometry] - The line geometry.
  21449. * @param {Material|Array<Material>} [material] - The line material.
  21450. */
  21451. constructor( geometry, material ) {
  21452. super( geometry, material );
  21453. /**
  21454. * This flag can be used for type testing.
  21455. *
  21456. * @type {boolean}
  21457. * @readonly
  21458. * @default true
  21459. */
  21460. this.isLineLoop = true;
  21461. this.type = 'LineLoop';
  21462. }
  21463. }
  21464. /**
  21465. * A material for rendering point primitives.
  21466. *
  21467. * Materials define the appearance of renderable 3D objects.
  21468. *
  21469. * ```js
  21470. * const vertices = [];
  21471. *
  21472. * for ( let i = 0; i < 10000; i ++ ) {
  21473. * const x = THREE.MathUtils.randFloatSpread( 2000 );
  21474. * const y = THREE.MathUtils.randFloatSpread( 2000 );
  21475. * const z = THREE.MathUtils.randFloatSpread( 2000 );
  21476. *
  21477. * vertices.push( x, y, z );
  21478. * }
  21479. *
  21480. * const geometry = new THREE.BufferGeometry();
  21481. * geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  21482. * const material = new THREE.PointsMaterial( { color: 0x888888 } );
  21483. * const points = new THREE.Points( geometry, material );
  21484. * scene.add( points );
  21485. * ```
  21486. *
  21487. * @augments Material
  21488. */
  21489. class PointsMaterial extends Material {
  21490. /**
  21491. * Constructs a new points material.
  21492. *
  21493. * @param {Object} [parameters] - An object with one or more properties
  21494. * defining the material's appearance. Any property of the material
  21495. * (including any property from inherited materials) can be passed
  21496. * in here. Color values can be passed any type of value accepted
  21497. * by {@link Color#set}.
  21498. */
  21499. constructor( parameters ) {
  21500. super();
  21501. /**
  21502. * This flag can be used for type testing.
  21503. *
  21504. * @type {boolean}
  21505. * @readonly
  21506. * @default true
  21507. */
  21508. this.isPointsMaterial = true;
  21509. this.type = 'PointsMaterial';
  21510. /**
  21511. * Color of the material.
  21512. *
  21513. * @type {Color}
  21514. * @default (1,1,1)
  21515. */
  21516. this.color = new Color( 0xffffff );
  21517. /**
  21518. * The color map. May optionally include an alpha channel, typically combined
  21519. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  21520. * color is modulated by the diffuse `color`.
  21521. *
  21522. * @type {?Texture}
  21523. * @default null
  21524. */
  21525. this.map = null;
  21526. /**
  21527. * The alpha map is a grayscale texture that controls the opacity across the
  21528. * surface (black: fully transparent; white: fully opaque).
  21529. *
  21530. * Only the color of the texture is used, ignoring the alpha channel if one
  21531. * exists. For RGB and RGBA textures, the renderer will use the green channel
  21532. * when sampling this texture due to the extra bit of precision provided for
  21533. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  21534. * luminance/alpha textures will also still work as expected.
  21535. *
  21536. * @type {?Texture}
  21537. * @default null
  21538. */
  21539. this.alphaMap = null;
  21540. /**
  21541. * Defines the size of the points in pixels.
  21542. *
  21543. * 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).
  21544. *
  21545. * @type {number}
  21546. * @default 1
  21547. */
  21548. this.size = 1;
  21549. /**
  21550. * Specifies whether size of individual points is attenuated by the camera depth (perspective camera only).
  21551. *
  21552. * @type {boolean}
  21553. * @default true
  21554. */
  21555. this.sizeAttenuation = true;
  21556. /**
  21557. * Whether the material is affected by fog or not.
  21558. *
  21559. * @type {boolean}
  21560. * @default true
  21561. */
  21562. this.fog = true;
  21563. this.setValues( parameters );
  21564. }
  21565. copy( source ) {
  21566. super.copy( source );
  21567. this.color.copy( source.color );
  21568. this.map = source.map;
  21569. this.alphaMap = source.alphaMap;
  21570. this.size = source.size;
  21571. this.sizeAttenuation = source.sizeAttenuation;
  21572. this.fog = source.fog;
  21573. return this;
  21574. }
  21575. }
  21576. const _inverseMatrix = /*@__PURE__*/ new Matrix4();
  21577. const _ray = /*@__PURE__*/ new Ray();
  21578. const _sphere = /*@__PURE__*/ new Sphere();
  21579. const _position$2 = /*@__PURE__*/ new Vector3();
  21580. /**
  21581. * A class for displaying points or point clouds.
  21582. *
  21583. * @augments Object3D
  21584. */
  21585. class Points extends Object3D {
  21586. /**
  21587. * Constructs a new point cloud.
  21588. *
  21589. * @param {BufferGeometry} [geometry] - The points geometry.
  21590. * @param {Material|Array<Material>} [material] - The points material.
  21591. */
  21592. constructor( geometry = new BufferGeometry(), material = new PointsMaterial() ) {
  21593. super();
  21594. /**
  21595. * This flag can be used for type testing.
  21596. *
  21597. * @type {boolean}
  21598. * @readonly
  21599. * @default true
  21600. */
  21601. this.isPoints = true;
  21602. this.type = 'Points';
  21603. /**
  21604. * The points geometry.
  21605. *
  21606. * @type {BufferGeometry}
  21607. */
  21608. this.geometry = geometry;
  21609. /**
  21610. * The line material.
  21611. *
  21612. * @type {Material|Array<Material>}
  21613. * @default PointsMaterial
  21614. */
  21615. this.material = material;
  21616. /**
  21617. * A dictionary representing the morph targets in the geometry. The key is the
  21618. * morph targets name, the value its attribute index. This member is `undefined`
  21619. * by default and only set when morph targets are detected in the geometry.
  21620. *
  21621. * @type {Object<String,number>|undefined}
  21622. * @default undefined
  21623. */
  21624. this.morphTargetDictionary = undefined;
  21625. /**
  21626. * An array of weights typically in the range `[0,1]` that specify how much of the morph
  21627. * is applied. This member is `undefined` by default and only set when morph targets are
  21628. * detected in the geometry.
  21629. *
  21630. * @type {Array<number>|undefined}
  21631. * @default undefined
  21632. */
  21633. this.morphTargetInfluences = undefined;
  21634. this.updateMorphTargets();
  21635. }
  21636. copy( source, recursive ) {
  21637. super.copy( source, recursive );
  21638. this.material = Array.isArray( source.material ) ? source.material.slice() : source.material;
  21639. this.geometry = source.geometry;
  21640. return this;
  21641. }
  21642. /**
  21643. * Computes intersection points between a casted ray and this point cloud.
  21644. *
  21645. * @param {Raycaster} raycaster - The raycaster.
  21646. * @param {Array<Object>} intersects - The target array that holds the intersection points.
  21647. */
  21648. raycast( raycaster, intersects ) {
  21649. const geometry = this.geometry;
  21650. const matrixWorld = this.matrixWorld;
  21651. const threshold = raycaster.params.Points.threshold;
  21652. const drawRange = geometry.drawRange;
  21653. // Checking boundingSphere distance to ray
  21654. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  21655. _sphere.copy( geometry.boundingSphere );
  21656. _sphere.applyMatrix4( matrixWorld );
  21657. _sphere.radius += threshold;
  21658. if ( raycaster.ray.intersectsSphere( _sphere ) === false ) return;
  21659. //
  21660. _inverseMatrix.copy( matrixWorld ).invert();
  21661. _ray.copy( raycaster.ray ).applyMatrix4( _inverseMatrix );
  21662. const localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  21663. const localThresholdSq = localThreshold * localThreshold;
  21664. const index = geometry.index;
  21665. const attributes = geometry.attributes;
  21666. const positionAttribute = attributes.position;
  21667. if ( index !== null ) {
  21668. const start = Math.max( 0, drawRange.start );
  21669. const end = Math.min( index.count, ( drawRange.start + drawRange.count ) );
  21670. for ( let i = start, il = end; i < il; i ++ ) {
  21671. const a = index.getX( i );
  21672. _position$2.fromBufferAttribute( positionAttribute, a );
  21673. testPoint( _position$2, a, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21674. }
  21675. } else {
  21676. const start = Math.max( 0, drawRange.start );
  21677. const end = Math.min( positionAttribute.count, ( drawRange.start + drawRange.count ) );
  21678. for ( let i = start, l = end; i < l; i ++ ) {
  21679. _position$2.fromBufferAttribute( positionAttribute, i );
  21680. testPoint( _position$2, i, localThresholdSq, matrixWorld, raycaster, intersects, this );
  21681. }
  21682. }
  21683. }
  21684. /**
  21685. * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences}
  21686. * to make sure existing morph targets can influence this 3D object.
  21687. */
  21688. updateMorphTargets() {
  21689. const geometry = this.geometry;
  21690. const morphAttributes = geometry.morphAttributes;
  21691. const keys = Object.keys( morphAttributes );
  21692. if ( keys.length > 0 ) {
  21693. const morphAttribute = morphAttributes[ keys[ 0 ] ];
  21694. if ( morphAttribute !== undefined ) {
  21695. this.morphTargetInfluences = [];
  21696. this.morphTargetDictionary = {};
  21697. for ( let m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  21698. const name = morphAttribute[ m ].name || String( m );
  21699. this.morphTargetInfluences.push( 0 );
  21700. this.morphTargetDictionary[ name ] = m;
  21701. }
  21702. }
  21703. }
  21704. }
  21705. }
  21706. function testPoint( point, index, localThresholdSq, matrixWorld, raycaster, intersects, object ) {
  21707. const rayPointDistanceSq = _ray.distanceSqToPoint( point );
  21708. if ( rayPointDistanceSq < localThresholdSq ) {
  21709. const intersectPoint = new Vector3();
  21710. _ray.closestPointToPoint( point, intersectPoint );
  21711. intersectPoint.applyMatrix4( matrixWorld );
  21712. const distance = raycaster.ray.origin.distanceTo( intersectPoint );
  21713. if ( distance < raycaster.near || distance > raycaster.far ) return;
  21714. intersects.push( {
  21715. distance: distance,
  21716. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  21717. point: intersectPoint,
  21718. index: index,
  21719. face: null,
  21720. faceIndex: null,
  21721. barycoord: null,
  21722. object: object
  21723. } );
  21724. }
  21725. }
  21726. /**
  21727. * A texture for use with a video.
  21728. *
  21729. * ```js
  21730. * // assuming you have created a HTML video element with id="video"
  21731. * const video = document.getElementById( 'video' );
  21732. * const texture = new THREE.VideoTexture( video );
  21733. * ```
  21734. *
  21735. * Note: When using video textures with {@link WebGPURenderer}, {@link Texture#colorSpace} must be
  21736. * set to THREE.SRGBColorSpace.
  21737. *
  21738. * Note: After the initial use of a texture, its dimensions, format, and type
  21739. * cannot be changed. Instead, call {@link Texture#dispose} on the texture and instantiate a new one.
  21740. *
  21741. * @augments Texture
  21742. */
  21743. class VideoTexture extends Texture {
  21744. /**
  21745. * Constructs a new video texture.
  21746. *
  21747. * @param {HTMLVideoElement} video - The video element to use as a data source for the texture.
  21748. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21749. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21750. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21751. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21752. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21753. * @param {number} [format=RGBAFormat] - The texture format.
  21754. * @param {number} [type=UnsignedByteType] - The texture type.
  21755. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21756. */
  21757. constructor( video, mapping, wrapS, wrapT, magFilter = LinearFilter, minFilter = LinearFilter, format, type, anisotropy ) {
  21758. super( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21759. /**
  21760. * This flag can be used for type testing.
  21761. *
  21762. * @type {boolean}
  21763. * @readonly
  21764. * @default true
  21765. */
  21766. this.isVideoTexture = true;
  21767. /**
  21768. * Whether to generate mipmaps (if possible) for a texture.
  21769. *
  21770. * Overwritten and set to `false` by default.
  21771. *
  21772. * @type {boolean}
  21773. * @default false
  21774. */
  21775. this.generateMipmaps = false;
  21776. /**
  21777. * The video frame request callback identifier, which is a positive integer.
  21778. *
  21779. * Value of 0 represents no scheduled rVFC.
  21780. *
  21781. * @private
  21782. * @type {number}
  21783. */
  21784. this._requestVideoFrameCallbackId = 0;
  21785. const scope = this;
  21786. function updateVideo() {
  21787. scope.needsUpdate = true;
  21788. scope._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21789. }
  21790. if ( 'requestVideoFrameCallback' in video ) {
  21791. this._requestVideoFrameCallbackId = video.requestVideoFrameCallback( updateVideo );
  21792. }
  21793. }
  21794. clone() {
  21795. return new this.constructor( this.image ).copy( this );
  21796. }
  21797. /**
  21798. * This method is called automatically by the renderer and sets {@link Texture#needsUpdate}
  21799. * to `true` every time a new frame is available.
  21800. *
  21801. * Only relevant if `requestVideoFrameCallback` is not supported in the browser.
  21802. */
  21803. update() {
  21804. const video = this.image;
  21805. const hasVideoFrameCallback = 'requestVideoFrameCallback' in video;
  21806. if ( hasVideoFrameCallback === false && video.readyState >= video.HAVE_CURRENT_DATA ) {
  21807. this.needsUpdate = true;
  21808. }
  21809. }
  21810. dispose() {
  21811. if ( this._requestVideoFrameCallbackId !== 0 ) {
  21812. this.source.data.cancelVideoFrameCallback( this._requestVideoFrameCallbackId );
  21813. this._requestVideoFrameCallbackId = 0;
  21814. }
  21815. super.dispose();
  21816. }
  21817. }
  21818. /**
  21819. * This class can be used as an alternative way to define video data. Instead of using
  21820. * an instance of `HTMLVideoElement` like with `VideoTexture`, `VideoFrameTexture` expects each frame is
  21821. * defined manually via {@link VideoFrameTexture#setFrame}. A typical use case for this module is when
  21822. * video frames are decoded with the WebCodecs API.
  21823. *
  21824. * ```js
  21825. * const texture = new THREE.VideoFrameTexture();
  21826. * texture.setFrame( frame );
  21827. * ```
  21828. *
  21829. * @augments VideoTexture
  21830. */
  21831. class VideoFrameTexture extends VideoTexture {
  21832. /**
  21833. * Constructs a new video frame texture.
  21834. *
  21835. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21836. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21837. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21838. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21839. * @param {number} [minFilter=LinearFilter] - The min filter value.
  21840. * @param {number} [format=RGBAFormat] - The texture format.
  21841. * @param {number} [type=UnsignedByteType] - The texture type.
  21842. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21843. */
  21844. constructor( mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  21845. super( {}, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  21846. /**
  21847. * This flag can be used for type testing.
  21848. *
  21849. * @type {boolean}
  21850. * @readonly
  21851. * @default true
  21852. */
  21853. this.isVideoFrameTexture = true;
  21854. }
  21855. /**
  21856. * This method overwritten with an empty implementation since
  21857. * this type of texture is updated via `setFrame()`.
  21858. */
  21859. update() {}
  21860. clone() {
  21861. return new this.constructor().copy( this ); // restoring Texture.clone()
  21862. }
  21863. /**
  21864. * Sets the current frame of the video. This will automatically update the texture
  21865. * so the data can be used for rendering.
  21866. *
  21867. * @param {VideoFrame} frame - The video frame.
  21868. */
  21869. setFrame( frame ) {
  21870. this.image = frame;
  21871. this.needsUpdate = true;
  21872. }
  21873. }
  21874. /**
  21875. * This class can only be used in combination with `copyFramebufferToTexture()` methods
  21876. * of renderers. It extracts the contents of the current bound framebuffer and provides it
  21877. * as a texture for further usage.
  21878. *
  21879. * ```js
  21880. * const pixelRatio = window.devicePixelRatio;
  21881. * const textureSize = 128 * pixelRatio;
  21882. *
  21883. * const frameTexture = new FramebufferTexture( textureSize, textureSize );
  21884. *
  21885. * // calculate start position for copying part of the frame data
  21886. * const vector = new Vector2();
  21887. * vector.x = ( window.innerWidth * pixelRatio / 2 ) - ( textureSize / 2 );
  21888. * vector.y = ( window.innerHeight * pixelRatio / 2 ) - ( textureSize / 2 );
  21889. *
  21890. * renderer.render( scene, camera );
  21891. *
  21892. * // copy part of the rendered frame into the framebuffer texture
  21893. * renderer.copyFramebufferToTexture( frameTexture, vector );
  21894. * ```
  21895. *
  21896. * @augments Texture
  21897. */
  21898. class FramebufferTexture extends Texture {
  21899. /**
  21900. * Constructs a new framebuffer texture.
  21901. *
  21902. * @param {number} [width] - The width of the texture.
  21903. * @param {number} [height] - The height of the texture.
  21904. */
  21905. constructor( width, height ) {
  21906. super( { width, height } );
  21907. /**
  21908. * This flag can be used for type testing.
  21909. *
  21910. * @type {boolean}
  21911. * @readonly
  21912. * @default true
  21913. */
  21914. this.isFramebufferTexture = true;
  21915. /**
  21916. * How the texture is sampled when a texel covers more than one pixel.
  21917. *
  21918. * Overwritten and set to `NearestFilter` by default to disable filtering.
  21919. *
  21920. * @type {(NearestFilter|NearestMipmapNearestFilter|NearestMipmapLinearFilter|LinearFilter|LinearMipmapNearestFilter|LinearMipmapLinearFilter)}
  21921. * @default NearestFilter
  21922. */
  21923. this.magFilter = NearestFilter;
  21924. /**
  21925. * How the texture is sampled when a texel covers less 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.minFilter = NearestFilter;
  21933. /**
  21934. * Whether to generate mipmaps (if possible) for a texture.
  21935. *
  21936. * Overwritten and set to `false` by default.
  21937. *
  21938. * @type {boolean}
  21939. * @default false
  21940. */
  21941. this.generateMipmaps = false;
  21942. this.needsUpdate = true;
  21943. }
  21944. }
  21945. /**
  21946. * Creates a texture based on data in compressed form.
  21947. *
  21948. * These texture are usually loaded with {@link CompressedTextureLoader}.
  21949. *
  21950. * @augments Texture
  21951. */
  21952. class CompressedTexture extends Texture {
  21953. /**
  21954. * Constructs a new compressed texture.
  21955. *
  21956. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  21957. * the data and dimensions.
  21958. * @param {number} width - The width of the texture.
  21959. * @param {number} height - The height of the texture.
  21960. * @param {number} [format=RGBAFormat] - The texture format.
  21961. * @param {number} [type=UnsignedByteType] - The texture type.
  21962. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  21963. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  21964. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  21965. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  21966. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  21967. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  21968. * @param {string} [colorSpace=NoColorSpace] - The color space.
  21969. */
  21970. constructor( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, colorSpace ) {
  21971. super( null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, colorSpace );
  21972. /**
  21973. * This flag can be used for type testing.
  21974. *
  21975. * @type {boolean}
  21976. * @readonly
  21977. * @default true
  21978. */
  21979. this.isCompressedTexture = true;
  21980. /**
  21981. * The image property of a compressed texture just defines its dimensions.
  21982. *
  21983. * @type {{width:number,height:number}}
  21984. */
  21985. this.image = { width: width, height: height };
  21986. /**
  21987. * This array holds for all mipmaps (including the bases mip) the data and dimensions.
  21988. *
  21989. * @type {Array<Object>}
  21990. */
  21991. this.mipmaps = mipmaps;
  21992. /**
  21993. * If set to `true`, the texture is flipped along the vertical axis when
  21994. * uploaded to the GPU.
  21995. *
  21996. * Overwritten and set to `false` by default since it is not possible to
  21997. * flip compressed textures.
  21998. *
  21999. * @type {boolean}
  22000. * @default false
  22001. * @readonly
  22002. */
  22003. this.flipY = false;
  22004. /**
  22005. * Whether to generate mipmaps (if possible) for a texture.
  22006. *
  22007. * Overwritten and set to `false` by default since it is not
  22008. * possible to generate mipmaps for compressed data. Mipmaps
  22009. * must be embedded in the compressed texture file.
  22010. *
  22011. * @type {boolean}
  22012. * @default false
  22013. * @readonly
  22014. */
  22015. this.generateMipmaps = false;
  22016. }
  22017. }
  22018. /**
  22019. * Creates a texture 2D array based on data in compressed form.
  22020. *
  22021. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22022. *
  22023. * @augments CompressedTexture
  22024. */
  22025. class CompressedArrayTexture extends CompressedTexture {
  22026. /**
  22027. * Constructs a new compressed array texture.
  22028. *
  22029. * @param {Array<Object>} mipmaps - This array holds for all mipmaps (including the bases mip)
  22030. * the data and dimensions.
  22031. * @param {number} width - The width of the texture.
  22032. * @param {number} height - The height of the texture.
  22033. * @param {number} depth - The depth of the texture.
  22034. * @param {number} [format=RGBAFormat] - The min filter value.
  22035. * @param {number} [type=UnsignedByteType] - The min filter value.
  22036. */
  22037. constructor( mipmaps, width, height, depth, format, type ) {
  22038. super( mipmaps, width, height, format, type );
  22039. /**
  22040. * This flag can be used for type testing.
  22041. *
  22042. * @type {boolean}
  22043. * @readonly
  22044. * @default true
  22045. */
  22046. this.isCompressedArrayTexture = true;
  22047. /**
  22048. * The image property of a compressed texture just defines its dimensions.
  22049. *
  22050. * @name CompressedArrayTexture#image
  22051. * @type {{width:number,height:number,depth:number}}
  22052. */
  22053. this.image.depth = depth;
  22054. /**
  22055. * This defines how the texture is wrapped in the depth and corresponds to
  22056. * *W* in UVW mapping.
  22057. *
  22058. * @type {(RepeatWrapping|ClampToEdgeWrapping|MirroredRepeatWrapping)}
  22059. * @default ClampToEdgeWrapping
  22060. */
  22061. this.wrapR = ClampToEdgeWrapping;
  22062. /**
  22063. * A set of all layers which need to be updated in the texture.
  22064. *
  22065. * @type {Set<number>}
  22066. */
  22067. this.layerUpdates = new Set();
  22068. }
  22069. /**
  22070. * Describes that a specific layer of the texture needs to be updated.
  22071. * Normally when {@link Texture#needsUpdate} is set to `true`, the
  22072. * entire compressed texture array is sent to the GPU. Marking specific
  22073. * layers will only transmit subsets of all mipmaps associated with a
  22074. * specific depth in the array which is often much more performant.
  22075. *
  22076. * @param {number} layerIndex - The layer index that should be updated.
  22077. */
  22078. addLayerUpdate( layerIndex ) {
  22079. this.layerUpdates.add( layerIndex );
  22080. }
  22081. /**
  22082. * Resets the layer updates registry.
  22083. */
  22084. clearLayerUpdates() {
  22085. this.layerUpdates.clear();
  22086. }
  22087. }
  22088. /**
  22089. * Creates a cube texture based on data in compressed form.
  22090. *
  22091. * These texture are usually loaded with {@link CompressedTextureLoader}.
  22092. *
  22093. * @augments CompressedTexture
  22094. */
  22095. class CompressedCubeTexture extends CompressedTexture {
  22096. /**
  22097. * Constructs a new compressed texture.
  22098. *
  22099. * @param {Array<CompressedTexture>} images - An array of compressed textures.
  22100. * @param {number} [format=RGBAFormat] - The texture format.
  22101. * @param {number} [type=UnsignedByteType] - The texture type.
  22102. */
  22103. constructor( images, format, type ) {
  22104. super( undefined, images[ 0 ].width, images[ 0 ].height, format, type, CubeReflectionMapping );
  22105. /**
  22106. * This flag can be used for type testing.
  22107. *
  22108. * @type {boolean}
  22109. * @readonly
  22110. * @default true
  22111. */
  22112. this.isCompressedCubeTexture = true;
  22113. /**
  22114. * This flag can be used for type testing.
  22115. *
  22116. * @type {boolean}
  22117. * @readonly
  22118. * @default true
  22119. */
  22120. this.isCubeTexture = true;
  22121. this.image = images;
  22122. }
  22123. }
  22124. /**
  22125. * Creates a texture from a canvas element.
  22126. *
  22127. * This is almost the same as the base texture class, except that it sets {@link Texture#needsUpdate}
  22128. * to `true` immediately since a canvas can directly be used for rendering.
  22129. *
  22130. * @augments Texture
  22131. */
  22132. class CanvasTexture extends Texture {
  22133. /**
  22134. * Constructs a new texture.
  22135. *
  22136. * @param {HTMLCanvasElement} [canvas] - The HTML canvas element.
  22137. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22138. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22139. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22140. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22141. * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value.
  22142. * @param {number} [format=RGBAFormat] - The texture format.
  22143. * @param {number} [type=UnsignedByteType] - The texture type.
  22144. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22145. */
  22146. constructor( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  22147. super( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22148. /**
  22149. * This flag can be used for type testing.
  22150. *
  22151. * @type {boolean}
  22152. * @readonly
  22153. * @default true
  22154. */
  22155. this.isCanvasTexture = true;
  22156. this.needsUpdate = true;
  22157. }
  22158. }
  22159. /**
  22160. * This class can be used to automatically save the depth information of a
  22161. * rendering into a texture.
  22162. *
  22163. * @augments Texture
  22164. */
  22165. class DepthTexture extends Texture {
  22166. /**
  22167. * Constructs a new depth texture.
  22168. *
  22169. * @param {number} width - The width of the texture.
  22170. * @param {number} height - The height of the texture.
  22171. * @param {number} [type=UnsignedIntType] - The texture type.
  22172. * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping.
  22173. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22174. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22175. * @param {number} [magFilter=LinearFilter] - The mag filter value.
  22176. * @param {number} [minFilter=LinearFilter] - The min filter value.
  22177. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22178. * @param {number} [format=DepthFormat] - The texture format.
  22179. * @param {number} [depth=1] - The depth of the texture.
  22180. */
  22181. constructor( width, height, type = UnsignedIntType, mapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat, depth = 1 ) {
  22182. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  22183. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  22184. }
  22185. const image = { width: width, height: height, depth: depth };
  22186. super( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  22187. /**
  22188. * This flag can be used for type testing.
  22189. *
  22190. * @type {boolean}
  22191. * @readonly
  22192. * @default true
  22193. */
  22194. this.isDepthTexture = true;
  22195. /**
  22196. * If set to `true`, the texture is flipped along the vertical axis when
  22197. * uploaded to the GPU.
  22198. *
  22199. * Overwritten and set to `false` by default.
  22200. *
  22201. * @type {boolean}
  22202. * @default false
  22203. */
  22204. this.flipY = false;
  22205. /**
  22206. * Whether to generate mipmaps (if possible) for a texture.
  22207. *
  22208. * Overwritten and set to `false` by default.
  22209. *
  22210. * @type {boolean}
  22211. * @default false
  22212. */
  22213. this.generateMipmaps = false;
  22214. /**
  22215. * Code corresponding to the depth compare function.
  22216. *
  22217. * @type {?(NeverCompare|LessCompare|EqualCompare|LessEqualCompare|GreaterCompare|NotEqualCompare|GreaterEqualCompare|AlwaysCompare)}
  22218. * @default null
  22219. */
  22220. this.compareFunction = null;
  22221. }
  22222. copy( source ) {
  22223. super.copy( source );
  22224. this.source = new Source( Object.assign( {}, source.image ) ); // see #30540
  22225. this.compareFunction = source.compareFunction;
  22226. return this;
  22227. }
  22228. toJSON( meta ) {
  22229. const data = super.toJSON( meta );
  22230. if ( this.compareFunction !== null ) data.compareFunction = this.compareFunction;
  22231. return data;
  22232. }
  22233. }
  22234. /**
  22235. * This class can be used to automatically save the depth information of a
  22236. * cube rendering into a cube texture with depth format. Used for PointLight shadows.
  22237. *
  22238. * @augments DepthTexture
  22239. */
  22240. class CubeDepthTexture extends DepthTexture {
  22241. /**
  22242. * Constructs a new cube depth texture.
  22243. *
  22244. * @param {number} size - The size (width and height) of each cube face.
  22245. * @param {number} [type=UnsignedIntType] - The texture type.
  22246. * @param {number} [mapping=CubeReflectionMapping] - The texture mapping.
  22247. * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value.
  22248. * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value.
  22249. * @param {number} [magFilter=NearestFilter] - The mag filter value.
  22250. * @param {number} [minFilter=NearestFilter] - The min filter value.
  22251. * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value.
  22252. * @param {number} [format=DepthFormat] - The texture format.
  22253. */
  22254. constructor( size, type = UnsignedIntType, mapping = CubeReflectionMapping, wrapS, wrapT, magFilter = NearestFilter, minFilter = NearestFilter, anisotropy, format = DepthFormat ) {
  22255. // Create 6 identical image descriptors for the cube faces
  22256. const image = { width: size, height: size, depth: 1 };
  22257. const images = [ image, image, image, image, image, image ];
  22258. // Call DepthTexture constructor with width, height
  22259. super( size, size, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format );
  22260. // Replace the single image with the array of 6 images
  22261. this.image = images;
  22262. /**
  22263. * This flag can be used for type testing.
  22264. *
  22265. * @type {boolean}
  22266. * @readonly
  22267. * @default true
  22268. */
  22269. this.isCubeDepthTexture = true;
  22270. /**
  22271. * Set to true for cube texture handling in WebGLTextures.
  22272. *
  22273. * @type {boolean}
  22274. * @readonly
  22275. * @default true
  22276. */
  22277. this.isCubeTexture = true;
  22278. }
  22279. /**
  22280. * Alias for {@link CubeDepthTexture#image}.
  22281. *
  22282. * @type {Array<Image>}
  22283. */
  22284. get images() {
  22285. return this.image;
  22286. }
  22287. set images( value ) {
  22288. this.image = value;
  22289. }
  22290. }
  22291. /**
  22292. * Represents a texture created externally with the same renderer context.
  22293. *
  22294. * This may be a texture from a protected media stream, device camera feed,
  22295. * or other data feeds like a depth sensor.
  22296. *
  22297. * Note that this class is only supported in {@link WebGLRenderer}, and in
  22298. * the {@link WebGPURenderer} WebGPU backend.
  22299. *
  22300. * @augments Texture
  22301. */
  22302. class ExternalTexture extends Texture {
  22303. /**
  22304. * Creates a new raw texture.
  22305. *
  22306. * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture.
  22307. */
  22308. constructor( sourceTexture = null ) {
  22309. super();
  22310. /**
  22311. * The external source texture.
  22312. *
  22313. * @type {?(WebGLTexture|GPUTexture)}
  22314. * @default null
  22315. */
  22316. this.sourceTexture = sourceTexture;
  22317. /**
  22318. * This flag can be used for type testing.
  22319. *
  22320. * @type {boolean}
  22321. * @readonly
  22322. * @default true
  22323. */
  22324. this.isExternalTexture = true;
  22325. }
  22326. copy( source ) {
  22327. super.copy( source );
  22328. this.sourceTexture = source.sourceTexture;
  22329. return this;
  22330. }
  22331. }
  22332. /**
  22333. * A geometry class for representing a capsule.
  22334. *
  22335. * ```js
  22336. * const geometry = new THREE.CapsuleGeometry( 1, 1, 4, 8, 1 );
  22337. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  22338. * const capsule = new THREE.Mesh( geometry, material );
  22339. * scene.add( capsule );
  22340. * ```
  22341. *
  22342. * @augments BufferGeometry
  22343. * @demo scenes/geometry-browser.html#CapsuleGeometry
  22344. */
  22345. class CapsuleGeometry extends BufferGeometry {
  22346. /**
  22347. * Constructs a new capsule geometry.
  22348. *
  22349. * @param {number} [radius=1] - Radius of the capsule.
  22350. * @param {number} [height=1] - Height of the middle section.
  22351. * @param {number} [capSegments=4] - Number of curve segments used to build each cap.
  22352. * @param {number} [radialSegments=8] - Number of segmented faces around the circumference of the capsule. Must be an integer >= 3.
  22353. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the middle section. Must be an integer >= 1.
  22354. */
  22355. constructor( radius = 1, height = 1, capSegments = 4, radialSegments = 8, heightSegments = 1 ) {
  22356. super();
  22357. this.type = 'CapsuleGeometry';
  22358. /**
  22359. * Holds the constructor parameters that have been
  22360. * used to generate the geometry. Any modification
  22361. * after instantiation does not change the geometry.
  22362. *
  22363. * @type {Object}
  22364. */
  22365. this.parameters = {
  22366. radius: radius,
  22367. height: height,
  22368. capSegments: capSegments,
  22369. radialSegments: radialSegments,
  22370. heightSegments: heightSegments,
  22371. };
  22372. height = Math.max( 0, height );
  22373. capSegments = Math.max( 1, Math.floor( capSegments ) );
  22374. radialSegments = Math.max( 3, Math.floor( radialSegments ) );
  22375. heightSegments = Math.max( 1, Math.floor( heightSegments ) );
  22376. // buffers
  22377. const indices = [];
  22378. const vertices = [];
  22379. const normals = [];
  22380. const uvs = [];
  22381. // helper variables
  22382. const halfHeight = height / 2;
  22383. const capArcLength = ( Math.PI / 2 ) * radius;
  22384. const cylinderPartLength = height;
  22385. const totalArcLength = 2 * capArcLength + cylinderPartLength;
  22386. const numVerticalSegments = capSegments * 2 + heightSegments;
  22387. const verticesPerRow = radialSegments + 1;
  22388. const normal = new Vector3();
  22389. const vertex = new Vector3();
  22390. // generate vertices, normals, and uvs
  22391. for ( let iy = 0; iy <= numVerticalSegments; iy ++ ) {
  22392. let currentArcLength = 0;
  22393. let profileY = 0;
  22394. let profileRadius = 0;
  22395. let normalYComponent = 0;
  22396. if ( iy <= capSegments ) {
  22397. // bottom cap
  22398. const segmentProgress = iy / capSegments;
  22399. const angle = ( segmentProgress * Math.PI ) / 2;
  22400. profileY = - halfHeight - radius * Math.cos( angle );
  22401. profileRadius = radius * Math.sin( angle );
  22402. normalYComponent = - radius * Math.cos( angle );
  22403. currentArcLength = segmentProgress * capArcLength;
  22404. } else if ( iy <= capSegments + heightSegments ) {
  22405. // middle section
  22406. const segmentProgress = ( iy - capSegments ) / heightSegments;
  22407. profileY = - halfHeight + segmentProgress * height;
  22408. profileRadius = radius;
  22409. normalYComponent = 0;
  22410. currentArcLength = capArcLength + segmentProgress * cylinderPartLength;
  22411. } else {
  22412. // top cap
  22413. const segmentProgress =
  22414. ( iy - capSegments - heightSegments ) / capSegments;
  22415. const angle = ( segmentProgress * Math.PI ) / 2;
  22416. profileY = halfHeight + radius * Math.sin( angle );
  22417. profileRadius = radius * Math.cos( angle );
  22418. normalYComponent = radius * Math.sin( angle );
  22419. currentArcLength =
  22420. capArcLength + cylinderPartLength + segmentProgress * capArcLength;
  22421. }
  22422. const v = Math.max( 0, Math.min( 1, currentArcLength / totalArcLength ) );
  22423. // special case for the poles
  22424. let uOffset = 0;
  22425. if ( iy === 0 ) {
  22426. uOffset = 0.5 / radialSegments;
  22427. } else if ( iy === numVerticalSegments ) {
  22428. uOffset = -0.5 / radialSegments;
  22429. }
  22430. for ( let ix = 0; ix <= radialSegments; ix ++ ) {
  22431. const u = ix / radialSegments;
  22432. const theta = u * Math.PI * 2;
  22433. const sinTheta = Math.sin( theta );
  22434. const cosTheta = Math.cos( theta );
  22435. // vertex
  22436. vertex.x = - profileRadius * cosTheta;
  22437. vertex.y = profileY;
  22438. vertex.z = profileRadius * sinTheta;
  22439. vertices.push( vertex.x, vertex.y, vertex.z );
  22440. // normal
  22441. normal.set(
  22442. - profileRadius * cosTheta,
  22443. normalYComponent,
  22444. profileRadius * sinTheta
  22445. );
  22446. normal.normalize();
  22447. normals.push( normal.x, normal.y, normal.z );
  22448. // uv
  22449. uvs.push( u + uOffset, v );
  22450. }
  22451. if ( iy > 0 ) {
  22452. const prevIndexRow = ( iy - 1 ) * verticesPerRow;
  22453. for ( let ix = 0; ix < radialSegments; ix ++ ) {
  22454. const i1 = prevIndexRow + ix;
  22455. const i2 = prevIndexRow + ix + 1;
  22456. const i3 = iy * verticesPerRow + ix;
  22457. const i4 = iy * verticesPerRow + ix + 1;
  22458. indices.push( i1, i2, i3 );
  22459. indices.push( i2, i4, i3 );
  22460. }
  22461. }
  22462. }
  22463. // build geometry
  22464. this.setIndex( indices );
  22465. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22466. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22467. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22468. }
  22469. copy( source ) {
  22470. super.copy( source );
  22471. this.parameters = Object.assign( {}, source.parameters );
  22472. return this;
  22473. }
  22474. /**
  22475. * Factory method for creating an instance of this class from the given
  22476. * JSON object.
  22477. *
  22478. * @param {Object} data - A JSON object representing the serialized geometry.
  22479. * @return {CapsuleGeometry} A new instance.
  22480. */
  22481. static fromJSON( data ) {
  22482. return new CapsuleGeometry( data.radius, data.height, data.capSegments, data.radialSegments, data.heightSegments );
  22483. }
  22484. }
  22485. /**
  22486. * A simple shape of Euclidean geometry. It is constructed from a
  22487. * number of triangular segments that are oriented around a central point and
  22488. * extend as far out as a given radius. It is built counter-clockwise from a
  22489. * start angle and a given central angle. It can also be used to create
  22490. * regular polygons, where the number of segments determines the number of
  22491. * sides.
  22492. *
  22493. * ```js
  22494. * const geometry = new THREE.CircleGeometry( 5, 32 );
  22495. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22496. * const circle = new THREE.Mesh( geometry, material );
  22497. * scene.add( circle )
  22498. * ```
  22499. *
  22500. * @augments BufferGeometry
  22501. * @demo scenes/geometry-browser.html#CircleGeometry
  22502. */
  22503. class CircleGeometry extends BufferGeometry {
  22504. /**
  22505. * Constructs a new circle geometry.
  22506. *
  22507. * @param {number} [radius=1] - Radius of the circle.
  22508. * @param {number} [segments=32] - Number of segments (triangles), minimum = `3`.
  22509. * @param {number} [thetaStart=0] - Start angle for first segment in radians.
  22510. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta,
  22511. * of the circular sector in radians. The default value results in a complete circle.
  22512. */
  22513. constructor( radius = 1, segments = 32, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22514. super();
  22515. this.type = 'CircleGeometry';
  22516. /**
  22517. * Holds the constructor parameters that have been
  22518. * used to generate the geometry. Any modification
  22519. * after instantiation does not change the geometry.
  22520. *
  22521. * @type {Object}
  22522. */
  22523. this.parameters = {
  22524. radius: radius,
  22525. segments: segments,
  22526. thetaStart: thetaStart,
  22527. thetaLength: thetaLength
  22528. };
  22529. segments = Math.max( 3, segments );
  22530. // buffers
  22531. const indices = [];
  22532. const vertices = [];
  22533. const normals = [];
  22534. const uvs = [];
  22535. // helper variables
  22536. const vertex = new Vector3();
  22537. const uv = new Vector2();
  22538. // center point
  22539. vertices.push( 0, 0, 0 );
  22540. normals.push( 0, 0, 1 );
  22541. uvs.push( 0.5, 0.5 );
  22542. for ( let s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22543. const segment = thetaStart + s / segments * thetaLength;
  22544. // vertex
  22545. vertex.x = radius * Math.cos( segment );
  22546. vertex.y = radius * Math.sin( segment );
  22547. vertices.push( vertex.x, vertex.y, vertex.z );
  22548. // normal
  22549. normals.push( 0, 0, 1 );
  22550. // uvs
  22551. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22552. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22553. uvs.push( uv.x, uv.y );
  22554. }
  22555. // indices
  22556. for ( let i = 1; i <= segments; i ++ ) {
  22557. indices.push( i, i + 1, 0 );
  22558. }
  22559. // build geometry
  22560. this.setIndex( indices );
  22561. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22562. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22563. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22564. }
  22565. copy( source ) {
  22566. super.copy( source );
  22567. this.parameters = Object.assign( {}, source.parameters );
  22568. return this;
  22569. }
  22570. /**
  22571. * Factory method for creating an instance of this class from the given
  22572. * JSON object.
  22573. *
  22574. * @param {Object} data - A JSON object representing the serialized geometry.
  22575. * @return {CircleGeometry} A new instance.
  22576. */
  22577. static fromJSON( data ) {
  22578. return new CircleGeometry( data.radius, data.segments, data.thetaStart, data.thetaLength );
  22579. }
  22580. }
  22581. /**
  22582. * A geometry class for representing a cylinder.
  22583. *
  22584. * ```js
  22585. * const geometry = new THREE.CylinderGeometry( 5, 5, 20, 32 );
  22586. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22587. * const cylinder = new THREE.Mesh( geometry, material );
  22588. * scene.add( cylinder );
  22589. * ```
  22590. *
  22591. * @augments BufferGeometry
  22592. * @demo scenes/geometry-browser.html#CylinderGeometry
  22593. */
  22594. class CylinderGeometry extends BufferGeometry {
  22595. /**
  22596. * Constructs a new cylinder geometry.
  22597. *
  22598. * @param {number} [radiusTop=1] - Radius of the cylinder at the top.
  22599. * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom.
  22600. * @param {number} [height=1] - Height of the cylinder.
  22601. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder.
  22602. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder.
  22603. * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped.
  22604. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22605. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22606. * The default value results in a complete cylinder.
  22607. */
  22608. constructor( radiusTop = 1, radiusBottom = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22609. super();
  22610. this.type = 'CylinderGeometry';
  22611. /**
  22612. * Holds the constructor parameters that have been
  22613. * used to generate the geometry. Any modification
  22614. * after instantiation does not change the geometry.
  22615. *
  22616. * @type {Object}
  22617. */
  22618. this.parameters = {
  22619. radiusTop: radiusTop,
  22620. radiusBottom: radiusBottom,
  22621. height: height,
  22622. radialSegments: radialSegments,
  22623. heightSegments: heightSegments,
  22624. openEnded: openEnded,
  22625. thetaStart: thetaStart,
  22626. thetaLength: thetaLength
  22627. };
  22628. const scope = this;
  22629. radialSegments = Math.floor( radialSegments );
  22630. heightSegments = Math.floor( heightSegments );
  22631. // buffers
  22632. const indices = [];
  22633. const vertices = [];
  22634. const normals = [];
  22635. const uvs = [];
  22636. // helper variables
  22637. let index = 0;
  22638. const indexArray = [];
  22639. const halfHeight = height / 2;
  22640. let groupStart = 0;
  22641. // generate geometry
  22642. generateTorso();
  22643. if ( openEnded === false ) {
  22644. if ( radiusTop > 0 ) generateCap( true );
  22645. if ( radiusBottom > 0 ) generateCap( false );
  22646. }
  22647. // build geometry
  22648. this.setIndex( indices );
  22649. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22650. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22651. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22652. function generateTorso() {
  22653. const normal = new Vector3();
  22654. const vertex = new Vector3();
  22655. let groupCount = 0;
  22656. // this will be used to calculate the normal
  22657. const slope = ( radiusBottom - radiusTop ) / height;
  22658. // generate vertices, normals and uvs
  22659. for ( let y = 0; y <= heightSegments; y ++ ) {
  22660. const indexRow = [];
  22661. const v = y / heightSegments;
  22662. // calculate the radius of the current row
  22663. const radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  22664. for ( let x = 0; x <= radialSegments; x ++ ) {
  22665. const u = x / radialSegments;
  22666. const theta = u * thetaLength + thetaStart;
  22667. const sinTheta = Math.sin( theta );
  22668. const cosTheta = Math.cos( theta );
  22669. // vertex
  22670. vertex.x = radius * sinTheta;
  22671. vertex.y = - v * height + halfHeight;
  22672. vertex.z = radius * cosTheta;
  22673. vertices.push( vertex.x, vertex.y, vertex.z );
  22674. // normal
  22675. normal.set( sinTheta, slope, cosTheta ).normalize();
  22676. normals.push( normal.x, normal.y, normal.z );
  22677. // uv
  22678. uvs.push( u, 1 - v );
  22679. // save index of vertex in respective row
  22680. indexRow.push( index ++ );
  22681. }
  22682. // now save vertices of the row in our index array
  22683. indexArray.push( indexRow );
  22684. }
  22685. // generate indices
  22686. for ( let x = 0; x < radialSegments; x ++ ) {
  22687. for ( let y = 0; y < heightSegments; y ++ ) {
  22688. // we use the index array to access the correct indices
  22689. const a = indexArray[ y ][ x ];
  22690. const b = indexArray[ y + 1 ][ x ];
  22691. const c = indexArray[ y + 1 ][ x + 1 ];
  22692. const d = indexArray[ y ][ x + 1 ];
  22693. // faces
  22694. if ( radiusTop > 0 || y !== 0 ) {
  22695. indices.push( a, b, d );
  22696. groupCount += 3;
  22697. }
  22698. if ( radiusBottom > 0 || y !== heightSegments - 1 ) {
  22699. indices.push( b, c, d );
  22700. groupCount += 3;
  22701. }
  22702. }
  22703. }
  22704. // add a group to the geometry. this will ensure multi material support
  22705. scope.addGroup( groupStart, groupCount, 0 );
  22706. // calculate new start value for groups
  22707. groupStart += groupCount;
  22708. }
  22709. function generateCap( top ) {
  22710. // save the index of the first center vertex
  22711. const centerIndexStart = index;
  22712. const uv = new Vector2();
  22713. const vertex = new Vector3();
  22714. let groupCount = 0;
  22715. const radius = ( top === true ) ? radiusTop : radiusBottom;
  22716. const sign = ( top === true ) ? 1 : -1;
  22717. // first we generate the center vertex data of the cap.
  22718. // because the geometry needs one set of uvs per face,
  22719. // we must generate a center vertex per face/segment
  22720. for ( let x = 1; x <= radialSegments; x ++ ) {
  22721. // vertex
  22722. vertices.push( 0, halfHeight * sign, 0 );
  22723. // normal
  22724. normals.push( 0, sign, 0 );
  22725. // uv
  22726. uvs.push( 0.5, 0.5 );
  22727. // increase index
  22728. index ++;
  22729. }
  22730. // save the index of the last center vertex
  22731. const centerIndexEnd = index;
  22732. // now we generate the surrounding vertices, normals and uvs
  22733. for ( let x = 0; x <= radialSegments; x ++ ) {
  22734. const u = x / radialSegments;
  22735. const theta = u * thetaLength + thetaStart;
  22736. const cosTheta = Math.cos( theta );
  22737. const sinTheta = Math.sin( theta );
  22738. // vertex
  22739. vertex.x = radius * sinTheta;
  22740. vertex.y = halfHeight * sign;
  22741. vertex.z = radius * cosTheta;
  22742. vertices.push( vertex.x, vertex.y, vertex.z );
  22743. // normal
  22744. normals.push( 0, sign, 0 );
  22745. // uv
  22746. uv.x = ( cosTheta * 0.5 ) + 0.5;
  22747. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  22748. uvs.push( uv.x, uv.y );
  22749. // increase index
  22750. index ++;
  22751. }
  22752. // generate indices
  22753. for ( let x = 0; x < radialSegments; x ++ ) {
  22754. const c = centerIndexStart + x;
  22755. const i = centerIndexEnd + x;
  22756. if ( top === true ) {
  22757. // face top
  22758. indices.push( i, i + 1, c );
  22759. } else {
  22760. // face bottom
  22761. indices.push( i + 1, i, c );
  22762. }
  22763. groupCount += 3;
  22764. }
  22765. // add a group to the geometry. this will ensure multi material support
  22766. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  22767. // calculate new start value for groups
  22768. groupStart += groupCount;
  22769. }
  22770. }
  22771. copy( source ) {
  22772. super.copy( source );
  22773. this.parameters = Object.assign( {}, source.parameters );
  22774. return this;
  22775. }
  22776. /**
  22777. * Factory method for creating an instance of this class from the given
  22778. * JSON object.
  22779. *
  22780. * @param {Object} data - A JSON object representing the serialized geometry.
  22781. * @return {CylinderGeometry} A new instance.
  22782. */
  22783. static fromJSON( data ) {
  22784. return new CylinderGeometry( data.radiusTop, data.radiusBottom, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22785. }
  22786. }
  22787. /**
  22788. * A geometry class for representing a cone.
  22789. *
  22790. * ```js
  22791. * const geometry = new THREE.ConeGeometry( 5, 20, 32 );
  22792. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  22793. * const cone = new THREE.Mesh(geometry, material );
  22794. * scene.add( cone );
  22795. * ```
  22796. *
  22797. * @augments CylinderGeometry
  22798. * @demo scenes/geometry-browser.html#ConeGeometry
  22799. */
  22800. class ConeGeometry extends CylinderGeometry {
  22801. /**
  22802. * Constructs a new cone geometry.
  22803. *
  22804. * @param {number} [radius=1] - Radius of the cone base.
  22805. * @param {number} [height=1] - Height of the cone.
  22806. * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone.
  22807. * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone.
  22808. * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped.
  22809. * @param {number} [thetaStart=0] - Start angle for first segment, in radians.
  22810. * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians.
  22811. * The default value results in a complete cone.
  22812. */
  22813. constructor( radius = 1, height = 1, radialSegments = 32, heightSegments = 1, openEnded = false, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  22814. super( 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  22815. this.type = 'ConeGeometry';
  22816. /**
  22817. * Holds the constructor parameters that have been
  22818. * used to generate the geometry. Any modification
  22819. * after instantiation does not change the geometry.
  22820. *
  22821. * @type {Object}
  22822. */
  22823. this.parameters = {
  22824. radius: radius,
  22825. height: height,
  22826. radialSegments: radialSegments,
  22827. heightSegments: heightSegments,
  22828. openEnded: openEnded,
  22829. thetaStart: thetaStart,
  22830. thetaLength: thetaLength
  22831. };
  22832. }
  22833. /**
  22834. * Factory method for creating an instance of this class from the given
  22835. * JSON object.
  22836. *
  22837. * @param {Object} data - A JSON object representing the serialized geometry.
  22838. * @return {ConeGeometry} A new instance.
  22839. */
  22840. static fromJSON( data ) {
  22841. return new ConeGeometry( data.radius, data.height, data.radialSegments, data.heightSegments, data.openEnded, data.thetaStart, data.thetaLength );
  22842. }
  22843. }
  22844. /**
  22845. * A polyhedron is a solid in three dimensions with flat faces. This class
  22846. * will take an array of vertices, project them onto a sphere, and then
  22847. * divide them up to the desired level of detail.
  22848. *
  22849. * @augments BufferGeometry
  22850. */
  22851. class PolyhedronGeometry extends BufferGeometry {
  22852. /**
  22853. * Constructs a new polyhedron geometry.
  22854. *
  22855. * @param {Array<number>} [vertices] - A flat array of vertices describing the base shape.
  22856. * @param {Array<number>} [indices] - A flat array of indices describing the base shape.
  22857. * @param {number} [radius=1] - The radius of the shape.
  22858. * @param {number} [detail=0] - How many levels to subdivide the geometry. The more detail, the smoother the shape.
  22859. */
  22860. constructor( vertices = [], indices = [], radius = 1, detail = 0 ) {
  22861. super();
  22862. this.type = 'PolyhedronGeometry';
  22863. /**
  22864. * Holds the constructor parameters that have been
  22865. * used to generate the geometry. Any modification
  22866. * after instantiation does not change the geometry.
  22867. *
  22868. * @type {Object}
  22869. */
  22870. this.parameters = {
  22871. vertices: vertices,
  22872. indices: indices,
  22873. radius: radius,
  22874. detail: detail
  22875. };
  22876. // default buffer data
  22877. const vertexBuffer = [];
  22878. const uvBuffer = [];
  22879. // the subdivision creates the vertex buffer data
  22880. subdivide( detail );
  22881. // all vertices should lie on a conceptual sphere with a given radius
  22882. applyRadius( radius );
  22883. // finally, create the uv data
  22884. generateUVs();
  22885. // build non-indexed geometry
  22886. this.setAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  22887. this.setAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  22888. this.setAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  22889. if ( detail === 0 ) {
  22890. this.computeVertexNormals(); // flat normals
  22891. } else {
  22892. this.normalizeNormals(); // smooth normals
  22893. }
  22894. // helper functions
  22895. function subdivide( detail ) {
  22896. const a = new Vector3();
  22897. const b = new Vector3();
  22898. const c = new Vector3();
  22899. // iterate over all faces and apply a subdivision with the given detail value
  22900. for ( let i = 0; i < indices.length; i += 3 ) {
  22901. // get the vertices of the face
  22902. getVertexByIndex( indices[ i + 0 ], a );
  22903. getVertexByIndex( indices[ i + 1 ], b );
  22904. getVertexByIndex( indices[ i + 2 ], c );
  22905. // perform subdivision
  22906. subdivideFace( a, b, c, detail );
  22907. }
  22908. }
  22909. function subdivideFace( a, b, c, detail ) {
  22910. const cols = detail + 1;
  22911. // we use this multidimensional array as a data structure for creating the subdivision
  22912. const v = [];
  22913. // construct all of the vertices for this subdivision
  22914. for ( let i = 0; i <= cols; i ++ ) {
  22915. v[ i ] = [];
  22916. const aj = a.clone().lerp( c, i / cols );
  22917. const bj = b.clone().lerp( c, i / cols );
  22918. const rows = cols - i;
  22919. for ( let j = 0; j <= rows; j ++ ) {
  22920. if ( j === 0 && i === cols ) {
  22921. v[ i ][ j ] = aj;
  22922. } else {
  22923. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  22924. }
  22925. }
  22926. }
  22927. // construct all of the faces
  22928. for ( let i = 0; i < cols; i ++ ) {
  22929. for ( let j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  22930. const k = Math.floor( j / 2 );
  22931. if ( j % 2 === 0 ) {
  22932. pushVertex( v[ i ][ k + 1 ] );
  22933. pushVertex( v[ i + 1 ][ k ] );
  22934. pushVertex( v[ i ][ k ] );
  22935. } else {
  22936. pushVertex( v[ i ][ k + 1 ] );
  22937. pushVertex( v[ i + 1 ][ k + 1 ] );
  22938. pushVertex( v[ i + 1 ][ k ] );
  22939. }
  22940. }
  22941. }
  22942. }
  22943. function applyRadius( radius ) {
  22944. const vertex = new Vector3();
  22945. // iterate over the entire buffer and apply the radius to each vertex
  22946. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22947. vertex.x = vertexBuffer[ i + 0 ];
  22948. vertex.y = vertexBuffer[ i + 1 ];
  22949. vertex.z = vertexBuffer[ i + 2 ];
  22950. vertex.normalize().multiplyScalar( radius );
  22951. vertexBuffer[ i + 0 ] = vertex.x;
  22952. vertexBuffer[ i + 1 ] = vertex.y;
  22953. vertexBuffer[ i + 2 ] = vertex.z;
  22954. }
  22955. }
  22956. function generateUVs() {
  22957. const vertex = new Vector3();
  22958. for ( let i = 0; i < vertexBuffer.length; i += 3 ) {
  22959. vertex.x = vertexBuffer[ i + 0 ];
  22960. vertex.y = vertexBuffer[ i + 1 ];
  22961. vertex.z = vertexBuffer[ i + 2 ];
  22962. const u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  22963. const v = inclination( vertex ) / Math.PI + 0.5;
  22964. uvBuffer.push( u, 1 - v );
  22965. }
  22966. correctUVs();
  22967. correctSeam();
  22968. }
  22969. function correctSeam() {
  22970. // handle case when face straddles the seam, see #3269
  22971. for ( let i = 0; i < uvBuffer.length; i += 6 ) {
  22972. // uv data of a single face
  22973. const x0 = uvBuffer[ i + 0 ];
  22974. const x1 = uvBuffer[ i + 2 ];
  22975. const x2 = uvBuffer[ i + 4 ];
  22976. const max = Math.max( x0, x1, x2 );
  22977. const min = Math.min( x0, x1, x2 );
  22978. // 0.9 is somewhat arbitrary
  22979. if ( max > 0.9 && min < 0.1 ) {
  22980. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  22981. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  22982. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  22983. }
  22984. }
  22985. }
  22986. function pushVertex( vertex ) {
  22987. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  22988. }
  22989. function getVertexByIndex( index, vertex ) {
  22990. const stride = index * 3;
  22991. vertex.x = vertices[ stride + 0 ];
  22992. vertex.y = vertices[ stride + 1 ];
  22993. vertex.z = vertices[ stride + 2 ];
  22994. }
  22995. function correctUVs() {
  22996. const a = new Vector3();
  22997. const b = new Vector3();
  22998. const c = new Vector3();
  22999. const centroid = new Vector3();
  23000. const uvA = new Vector2();
  23001. const uvB = new Vector2();
  23002. const uvC = new Vector2();
  23003. for ( let i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  23004. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  23005. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  23006. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  23007. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  23008. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  23009. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  23010. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  23011. const azi = azimuth( centroid );
  23012. correctUV( uvA, j + 0, a, azi );
  23013. correctUV( uvB, j + 2, b, azi );
  23014. correctUV( uvC, j + 4, c, azi );
  23015. }
  23016. }
  23017. function correctUV( uv, stride, vector, azimuth ) {
  23018. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  23019. uvBuffer[ stride ] = uv.x - 1;
  23020. }
  23021. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  23022. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  23023. }
  23024. }
  23025. // Angle around the Y axis, counter-clockwise when looking from above.
  23026. function azimuth( vector ) {
  23027. return Math.atan2( vector.z, - vector.x );
  23028. }
  23029. // Angle above the XZ plane.
  23030. function inclination( vector ) {
  23031. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  23032. }
  23033. }
  23034. copy( source ) {
  23035. super.copy( source );
  23036. this.parameters = Object.assign( {}, source.parameters );
  23037. return this;
  23038. }
  23039. /**
  23040. * Factory method for creating an instance of this class from the given
  23041. * JSON object.
  23042. *
  23043. * @param {Object} data - A JSON object representing the serialized geometry.
  23044. * @return {PolyhedronGeometry} A new instance.
  23045. */
  23046. static fromJSON( data ) {
  23047. return new PolyhedronGeometry( data.vertices, data.indices, data.radius, data.details );
  23048. }
  23049. }
  23050. /**
  23051. * A geometry class for representing a dodecahedron.
  23052. *
  23053. * ```js
  23054. * const geometry = new THREE.DodecahedronGeometry();
  23055. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  23056. * const dodecahedron = new THREE.Mesh( geometry, material );
  23057. * scene.add( dodecahedron );
  23058. * ```
  23059. *
  23060. * @augments PolyhedronGeometry
  23061. * @demo scenes/geometry-browser.html#DodecahedronGeometry
  23062. */
  23063. class DodecahedronGeometry extends PolyhedronGeometry {
  23064. /**
  23065. * Constructs a new dodecahedron geometry.
  23066. *
  23067. * @param {number} [radius=1] - Radius of the dodecahedron.
  23068. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a dodecahedron.
  23069. */
  23070. constructor( radius = 1, detail = 0 ) {
  23071. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  23072. const r = 1 / t;
  23073. const vertices = [
  23074. // (±1, ±1, ±1)
  23075. -1, -1, -1, -1, -1, 1,
  23076. -1, 1, -1, -1, 1, 1,
  23077. 1, -1, -1, 1, -1, 1,
  23078. 1, 1, -1, 1, 1, 1,
  23079. // (0, ±1/φ, ±φ)
  23080. 0, - r, - t, 0, - r, t,
  23081. 0, r, - t, 0, r, t,
  23082. // (±1/φ, ±φ, 0)
  23083. - r, - t, 0, - r, t, 0,
  23084. r, - t, 0, r, t, 0,
  23085. // (±φ, 0, ±1/φ)
  23086. - t, 0, - r, t, 0, - r,
  23087. - t, 0, r, t, 0, r
  23088. ];
  23089. const indices = [
  23090. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  23091. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  23092. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  23093. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  23094. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  23095. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  23096. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  23097. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  23098. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  23099. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  23100. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  23101. 1, 12, 14, 1, 14, 5, 1, 5, 9
  23102. ];
  23103. super( vertices, indices, radius, detail );
  23104. this.type = 'DodecahedronGeometry';
  23105. /**
  23106. * Holds the constructor parameters that have been
  23107. * used to generate the geometry. Any modification
  23108. * after instantiation does not change the geometry.
  23109. *
  23110. * @type {Object}
  23111. */
  23112. this.parameters = {
  23113. radius: radius,
  23114. detail: detail
  23115. };
  23116. }
  23117. /**
  23118. * Factory method for creating an instance of this class from the given
  23119. * JSON object.
  23120. *
  23121. * @param {Object} data - A JSON object representing the serialized geometry.
  23122. * @return {DodecahedronGeometry} A new instance.
  23123. */
  23124. static fromJSON( data ) {
  23125. return new DodecahedronGeometry( data.radius, data.detail );
  23126. }
  23127. }
  23128. const _v0$1 = /*@__PURE__*/ new Vector3();
  23129. const _v1$1 = /*@__PURE__*/ new Vector3();
  23130. const _normal = /*@__PURE__*/ new Vector3();
  23131. const _triangle = /*@__PURE__*/ new Triangle();
  23132. /**
  23133. * Can be used as a helper object to view the edges of a geometry.
  23134. *
  23135. * ```js
  23136. * const geometry = new THREE.BoxGeometry();
  23137. * const edges = new THREE.EdgesGeometry( geometry );
  23138. * const line = new THREE.LineSegments( edges );
  23139. * scene.add( line );
  23140. * ```
  23141. *
  23142. * Note: It is not yet possible to serialize/deserialize instances of this class.
  23143. *
  23144. * @augments BufferGeometry
  23145. */
  23146. class EdgesGeometry extends BufferGeometry {
  23147. /**
  23148. * Constructs a new edges geometry.
  23149. *
  23150. * @param {?BufferGeometry} [geometry=null] - The geometry.
  23151. * @param {number} [thresholdAngle=1] - An edge is only rendered if the angle (in degrees)
  23152. * between the face normals of the adjoining faces exceeds this value.
  23153. */
  23154. constructor( geometry = null, thresholdAngle = 1 ) {
  23155. super();
  23156. this.type = 'EdgesGeometry';
  23157. /**
  23158. * Holds the constructor parameters that have been
  23159. * used to generate the geometry. Any modification
  23160. * after instantiation does not change the geometry.
  23161. *
  23162. * @type {Object}
  23163. */
  23164. this.parameters = {
  23165. geometry: geometry,
  23166. thresholdAngle: thresholdAngle
  23167. };
  23168. if ( geometry !== null ) {
  23169. const precisionPoints = 4;
  23170. const precision = Math.pow( 10, precisionPoints );
  23171. const thresholdDot = Math.cos( DEG2RAD * thresholdAngle );
  23172. const indexAttr = geometry.getIndex();
  23173. const positionAttr = geometry.getAttribute( 'position' );
  23174. const indexCount = indexAttr ? indexAttr.count : positionAttr.count;
  23175. const indexArr = [ 0, 0, 0 ];
  23176. const vertKeys = [ 'a', 'b', 'c' ];
  23177. const hashes = new Array( 3 );
  23178. const edgeData = {};
  23179. const vertices = [];
  23180. for ( let i = 0; i < indexCount; i += 3 ) {
  23181. if ( indexAttr ) {
  23182. indexArr[ 0 ] = indexAttr.getX( i );
  23183. indexArr[ 1 ] = indexAttr.getX( i + 1 );
  23184. indexArr[ 2 ] = indexAttr.getX( i + 2 );
  23185. } else {
  23186. indexArr[ 0 ] = i;
  23187. indexArr[ 1 ] = i + 1;
  23188. indexArr[ 2 ] = i + 2;
  23189. }
  23190. const { a, b, c } = _triangle;
  23191. a.fromBufferAttribute( positionAttr, indexArr[ 0 ] );
  23192. b.fromBufferAttribute( positionAttr, indexArr[ 1 ] );
  23193. c.fromBufferAttribute( positionAttr, indexArr[ 2 ] );
  23194. _triangle.getNormal( _normal );
  23195. // create hashes for the edge from the vertices
  23196. hashes[ 0 ] = `${ Math.round( a.x * precision ) },${ Math.round( a.y * precision ) },${ Math.round( a.z * precision ) }`;
  23197. hashes[ 1 ] = `${ Math.round( b.x * precision ) },${ Math.round( b.y * precision ) },${ Math.round( b.z * precision ) }`;
  23198. hashes[ 2 ] = `${ Math.round( c.x * precision ) },${ Math.round( c.y * precision ) },${ Math.round( c.z * precision ) }`;
  23199. // skip degenerate triangles
  23200. if ( hashes[ 0 ] === hashes[ 1 ] || hashes[ 1 ] === hashes[ 2 ] || hashes[ 2 ] === hashes[ 0 ] ) {
  23201. continue;
  23202. }
  23203. // iterate over every edge
  23204. for ( let j = 0; j < 3; j ++ ) {
  23205. // get the first and next vertex making up the edge
  23206. const jNext = ( j + 1 ) % 3;
  23207. const vecHash0 = hashes[ j ];
  23208. const vecHash1 = hashes[ jNext ];
  23209. const v0 = _triangle[ vertKeys[ j ] ];
  23210. const v1 = _triangle[ vertKeys[ jNext ] ];
  23211. const hash = `${ vecHash0 }_${ vecHash1 }`;
  23212. const reverseHash = `${ vecHash1 }_${ vecHash0 }`;
  23213. if ( reverseHash in edgeData && edgeData[ reverseHash ] ) {
  23214. // if we found a sibling edge add it into the vertex array if
  23215. // it meets the angle threshold and delete the edge from the map.
  23216. if ( _normal.dot( edgeData[ reverseHash ].normal ) <= thresholdDot ) {
  23217. vertices.push( v0.x, v0.y, v0.z );
  23218. vertices.push( v1.x, v1.y, v1.z );
  23219. }
  23220. edgeData[ reverseHash ] = null;
  23221. } else if ( ! ( hash in edgeData ) ) {
  23222. // if we've already got an edge here then skip adding a new one
  23223. edgeData[ hash ] = {
  23224. index0: indexArr[ j ],
  23225. index1: indexArr[ jNext ],
  23226. normal: _normal.clone(),
  23227. };
  23228. }
  23229. }
  23230. }
  23231. // iterate over all remaining, unmatched edges and add them to the vertex array
  23232. for ( const key in edgeData ) {
  23233. if ( edgeData[ key ] ) {
  23234. const { index0, index1 } = edgeData[ key ];
  23235. _v0$1.fromBufferAttribute( positionAttr, index0 );
  23236. _v1$1.fromBufferAttribute( positionAttr, index1 );
  23237. vertices.push( _v0$1.x, _v0$1.y, _v0$1.z );
  23238. vertices.push( _v1$1.x, _v1$1.y, _v1$1.z );
  23239. }
  23240. }
  23241. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  23242. }
  23243. }
  23244. copy( source ) {
  23245. super.copy( source );
  23246. this.parameters = Object.assign( {}, source.parameters );
  23247. return this;
  23248. }
  23249. }
  23250. /**
  23251. * An abstract base class for creating an analytic curve object that contains methods
  23252. * for interpolation.
  23253. *
  23254. * @abstract
  23255. */
  23256. class Curve {
  23257. /**
  23258. * Constructs a new curve.
  23259. */
  23260. constructor() {
  23261. /**
  23262. * The type property is used for detecting the object type
  23263. * in context of serialization/deserialization.
  23264. *
  23265. * @type {string}
  23266. * @readonly
  23267. */
  23268. this.type = 'Curve';
  23269. /**
  23270. * This value determines the amount of divisions when calculating the
  23271. * cumulative segment lengths of a curve via {@link Curve#getLengths}. To ensure
  23272. * precision when using methods like {@link Curve#getSpacedPoints}, it is
  23273. * recommended to increase the value of this property if the curve is very large.
  23274. *
  23275. * @type {number}
  23276. * @default 200
  23277. */
  23278. this.arcLengthDivisions = 200;
  23279. /**
  23280. * Must be set to `true` if the curve parameters have changed.
  23281. *
  23282. * @type {boolean}
  23283. * @default false
  23284. */
  23285. this.needsUpdate = false;
  23286. /**
  23287. * An internal cache that holds precomputed curve length values.
  23288. *
  23289. * @private
  23290. * @type {?Array<number>}
  23291. * @default null
  23292. */
  23293. this.cacheArcLengths = null;
  23294. }
  23295. /**
  23296. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23297. * for the given interpolation factor.
  23298. *
  23299. * @abstract
  23300. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23301. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23302. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23303. */
  23304. getPoint( /* t, optionalTarget */ ) {
  23305. warn( 'Curve: .getPoint() not implemented.' );
  23306. }
  23307. /**
  23308. * This method returns a vector in 2D or 3D space (depending on the curve definition)
  23309. * for the given interpolation factor. Unlike {@link Curve#getPoint}, this method honors the length
  23310. * of the curve which equidistant samples.
  23311. *
  23312. * @param {number} u - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23313. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23314. * @return {(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  23315. */
  23316. getPointAt( u, optionalTarget ) {
  23317. const t = this.getUtoTmapping( u );
  23318. return this.getPoint( t, optionalTarget );
  23319. }
  23320. /**
  23321. * This method samples the curve via {@link Curve#getPoint} and returns an array of points representing
  23322. * the curve shape.
  23323. *
  23324. * @param {number} [divisions=5] - The number of divisions.
  23325. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23326. */
  23327. getPoints( divisions = 5 ) {
  23328. const points = [];
  23329. for ( let d = 0; d <= divisions; d ++ ) {
  23330. points.push( this.getPoint( d / divisions ) );
  23331. }
  23332. return points;
  23333. }
  23334. // Get sequence of points using getPointAt( u )
  23335. /**
  23336. * This method samples the curve via {@link Curve#getPointAt} and returns an array of points representing
  23337. * the curve shape. Unlike {@link Curve#getPoints}, this method returns equi-spaced points across the entire
  23338. * curve.
  23339. *
  23340. * @param {number} [divisions=5] - The number of divisions.
  23341. * @return {Array<(Vector2|Vector3)>} An array holding the sampled curve values. The number of points is `divisions + 1`.
  23342. */
  23343. getSpacedPoints( divisions = 5 ) {
  23344. const points = [];
  23345. for ( let d = 0; d <= divisions; d ++ ) {
  23346. points.push( this.getPointAt( d / divisions ) );
  23347. }
  23348. return points;
  23349. }
  23350. /**
  23351. * Returns the total arc length of the curve.
  23352. *
  23353. * @return {number} The length of the curve.
  23354. */
  23355. getLength() {
  23356. const lengths = this.getLengths();
  23357. return lengths[ lengths.length - 1 ];
  23358. }
  23359. /**
  23360. * Returns an array of cumulative segment lengths of the curve.
  23361. *
  23362. * @param {number} [divisions=this.arcLengthDivisions] - The number of divisions.
  23363. * @return {Array<number>} An array holding the cumulative segment lengths.
  23364. */
  23365. getLengths( divisions = this.arcLengthDivisions ) {
  23366. if ( this.cacheArcLengths &&
  23367. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23368. ! this.needsUpdate ) {
  23369. return this.cacheArcLengths;
  23370. }
  23371. this.needsUpdate = false;
  23372. const cache = [];
  23373. let current, last = this.getPoint( 0 );
  23374. let sum = 0;
  23375. cache.push( 0 );
  23376. for ( let p = 1; p <= divisions; p ++ ) {
  23377. current = this.getPoint( p / divisions );
  23378. sum += current.distanceTo( last );
  23379. cache.push( sum );
  23380. last = current;
  23381. }
  23382. this.cacheArcLengths = cache;
  23383. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23384. }
  23385. /**
  23386. * Update the cumulative segment distance cache. The method must be called
  23387. * every time curve parameters are changed. If an updated curve is part of a
  23388. * composed curve like {@link CurvePath}, this method must be called on the
  23389. * composed curve, too.
  23390. */
  23391. updateArcLengths() {
  23392. this.needsUpdate = true;
  23393. this.getLengths();
  23394. }
  23395. /**
  23396. * Given an interpolation factor in the range `[0,1]`, this method returns an updated
  23397. * interpolation factor in the same range that can be ued to sample equidistant points
  23398. * from a curve.
  23399. *
  23400. * @param {number} u - The interpolation factor.
  23401. * @param {?number} distance - An optional distance on the curve.
  23402. * @return {number} The updated interpolation factor.
  23403. */
  23404. getUtoTmapping( u, distance = null ) {
  23405. const arcLengths = this.getLengths();
  23406. let i = 0;
  23407. const il = arcLengths.length;
  23408. let targetArcLength; // The targeted u distance value to get
  23409. if ( distance ) {
  23410. targetArcLength = distance;
  23411. } else {
  23412. targetArcLength = u * arcLengths[ il - 1 ];
  23413. }
  23414. // binary search for the index with largest value smaller than target u distance
  23415. let low = 0, high = il - 1, comparison;
  23416. while ( low <= high ) {
  23417. 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
  23418. comparison = arcLengths[ i ] - targetArcLength;
  23419. if ( comparison < 0 ) {
  23420. low = i + 1;
  23421. } else if ( comparison > 0 ) {
  23422. high = i - 1;
  23423. } else {
  23424. high = i;
  23425. break;
  23426. // DONE
  23427. }
  23428. }
  23429. i = high;
  23430. if ( arcLengths[ i ] === targetArcLength ) {
  23431. return i / ( il - 1 );
  23432. }
  23433. // we could get finer grain at lengths, or use simple interpolation between two points
  23434. const lengthBefore = arcLengths[ i ];
  23435. const lengthAfter = arcLengths[ i + 1 ];
  23436. const segmentLength = lengthAfter - lengthBefore;
  23437. // determine where we are between the 'before' and 'after' points
  23438. const segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23439. // add that fractional amount to t
  23440. const t = ( i + segmentFraction ) / ( il - 1 );
  23441. return t;
  23442. }
  23443. /**
  23444. * Returns a unit vector tangent for the given interpolation factor.
  23445. * If the derived curve does not implement its tangent derivation,
  23446. * two points a small delta apart will be used to find its gradient
  23447. * which seems to give a reasonable approximation.
  23448. *
  23449. * @param {number} t - The interpolation factor.
  23450. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23451. * @return {(Vector2|Vector3)} The tangent vector.
  23452. */
  23453. getTangent( t, optionalTarget ) {
  23454. const delta = 0.0001;
  23455. let t1 = t - delta;
  23456. let t2 = t + delta;
  23457. // Capping in case of danger
  23458. if ( t1 < 0 ) t1 = 0;
  23459. if ( t2 > 1 ) t2 = 1;
  23460. const pt1 = this.getPoint( t1 );
  23461. const pt2 = this.getPoint( t2 );
  23462. const tangent = optionalTarget || ( ( pt1.isVector2 ) ? new Vector2() : new Vector3() );
  23463. tangent.copy( pt2 ).sub( pt1 ).normalize();
  23464. return tangent;
  23465. }
  23466. /**
  23467. * Same as {@link Curve#getTangent} but with equidistant samples.
  23468. *
  23469. * @param {number} u - The interpolation factor.
  23470. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  23471. * @return {(Vector2|Vector3)} The tangent vector.
  23472. * @see {@link Curve#getPointAt}
  23473. */
  23474. getTangentAt( u, optionalTarget ) {
  23475. const t = this.getUtoTmapping( u );
  23476. return this.getTangent( t, optionalTarget );
  23477. }
  23478. /**
  23479. * Generates the Frenet Frames. Requires a curve definition in 3D space. Used
  23480. * in geometries like {@link TubeGeometry} or {@link ExtrudeGeometry}.
  23481. *
  23482. * @param {number} segments - The number of segments.
  23483. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23484. * @return {{tangents: Array<Vector3>, normals: Array<Vector3>, binormals: Array<Vector3>}} The Frenet Frames.
  23485. */
  23486. computeFrenetFrames( segments, closed = false ) {
  23487. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23488. const normal = new Vector3();
  23489. const tangents = [];
  23490. const normals = [];
  23491. const binormals = [];
  23492. const vec = new Vector3();
  23493. const mat = new Matrix4();
  23494. // compute the tangent vectors for each segment on the curve
  23495. for ( let i = 0; i <= segments; i ++ ) {
  23496. const u = i / segments;
  23497. tangents[ i ] = this.getTangentAt( u, new Vector3() );
  23498. }
  23499. // select an initial normal vector perpendicular to the first tangent vector,
  23500. // and in the direction of the minimum tangent xyz component
  23501. normals[ 0 ] = new Vector3();
  23502. binormals[ 0 ] = new Vector3();
  23503. let min = Number.MAX_VALUE;
  23504. const tx = Math.abs( tangents[ 0 ].x );
  23505. const ty = Math.abs( tangents[ 0 ].y );
  23506. const tz = Math.abs( tangents[ 0 ].z );
  23507. if ( tx <= min ) {
  23508. min = tx;
  23509. normal.set( 1, 0, 0 );
  23510. }
  23511. if ( ty <= min ) {
  23512. min = ty;
  23513. normal.set( 0, 1, 0 );
  23514. }
  23515. if ( tz <= min ) {
  23516. normal.set( 0, 0, 1 );
  23517. }
  23518. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23519. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23520. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23521. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23522. for ( let i = 1; i <= segments; i ++ ) {
  23523. normals[ i ] = normals[ i - 1 ].clone();
  23524. binormals[ i ] = binormals[ i - 1 ].clone();
  23525. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23526. if ( vec.length() > Number.EPSILON ) {
  23527. vec.normalize();
  23528. const theta = Math.acos( clamp( tangents[ i - 1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  23529. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23530. }
  23531. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23532. }
  23533. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23534. if ( closed === true ) {
  23535. let theta = Math.acos( clamp( normals[ 0 ].dot( normals[ segments ] ), -1, 1 ) );
  23536. theta /= segments;
  23537. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23538. theta = - theta;
  23539. }
  23540. for ( let i = 1; i <= segments; i ++ ) {
  23541. // twist a little...
  23542. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23543. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23544. }
  23545. }
  23546. return {
  23547. tangents: tangents,
  23548. normals: normals,
  23549. binormals: binormals
  23550. };
  23551. }
  23552. /**
  23553. * Returns a new curve with copied values from this instance.
  23554. *
  23555. * @return {Curve} A clone of this instance.
  23556. */
  23557. clone() {
  23558. return new this.constructor().copy( this );
  23559. }
  23560. /**
  23561. * Copies the values of the given curve to this instance.
  23562. *
  23563. * @param {Curve} source - The curve to copy.
  23564. * @return {Curve} A reference to this curve.
  23565. */
  23566. copy( source ) {
  23567. this.arcLengthDivisions = source.arcLengthDivisions;
  23568. return this;
  23569. }
  23570. /**
  23571. * Serializes the curve into JSON.
  23572. *
  23573. * @return {Object} A JSON object representing the serialized curve.
  23574. * @see {@link ObjectLoader#parse}
  23575. */
  23576. toJSON() {
  23577. const data = {
  23578. metadata: {
  23579. version: 4.7,
  23580. type: 'Curve',
  23581. generator: 'Curve.toJSON'
  23582. }
  23583. };
  23584. data.arcLengthDivisions = this.arcLengthDivisions;
  23585. data.type = this.type;
  23586. return data;
  23587. }
  23588. /**
  23589. * Deserializes the curve from the given JSON.
  23590. *
  23591. * @param {Object} json - The JSON holding the serialized curve.
  23592. * @return {Curve} A reference to this curve.
  23593. */
  23594. fromJSON( json ) {
  23595. this.arcLengthDivisions = json.arcLengthDivisions;
  23596. return this;
  23597. }
  23598. }
  23599. /**
  23600. * A curve representing an ellipse.
  23601. *
  23602. * ```js
  23603. * const curve = new THREE.EllipseCurve(
  23604. * 0, 0,
  23605. * 10, 10,
  23606. * 0, 2 * Math.PI,
  23607. * false,
  23608. * 0
  23609. * );
  23610. *
  23611. * const points = curve.getPoints( 50 );
  23612. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23613. *
  23614. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23615. *
  23616. * // Create the final object to add to the scene
  23617. * const ellipse = new THREE.Line( geometry, material );
  23618. * ```
  23619. *
  23620. * @augments Curve
  23621. */
  23622. class EllipseCurve extends Curve {
  23623. /**
  23624. * Constructs a new ellipse curve.
  23625. *
  23626. * @param {number} [aX=0] - The X center of the ellipse.
  23627. * @param {number} [aY=0] - The Y center of the ellipse.
  23628. * @param {number} [xRadius=1] - The radius of the ellipse in the x direction.
  23629. * @param {number} [yRadius=1] - The radius of the ellipse in the y direction.
  23630. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23631. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23632. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23633. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23634. */
  23635. constructor( aX = 0, aY = 0, xRadius = 1, yRadius = 1, aStartAngle = 0, aEndAngle = Math.PI * 2, aClockwise = false, aRotation = 0 ) {
  23636. super();
  23637. /**
  23638. * This flag can be used for type testing.
  23639. *
  23640. * @type {boolean}
  23641. * @readonly
  23642. * @default true
  23643. */
  23644. this.isEllipseCurve = true;
  23645. this.type = 'EllipseCurve';
  23646. /**
  23647. * The X center of the ellipse.
  23648. *
  23649. * @type {number}
  23650. * @default 0
  23651. */
  23652. this.aX = aX;
  23653. /**
  23654. * The Y center of the ellipse.
  23655. *
  23656. * @type {number}
  23657. * @default 0
  23658. */
  23659. this.aY = aY;
  23660. /**
  23661. * The radius of the ellipse in the x direction.
  23662. * Setting the this value equal to the {@link EllipseCurve#yRadius} will result in a circle.
  23663. *
  23664. * @type {number}
  23665. * @default 1
  23666. */
  23667. this.xRadius = xRadius;
  23668. /**
  23669. * The radius of the ellipse in the y direction.
  23670. * Setting the this value equal to the {@link EllipseCurve#xRadius} will result in a circle.
  23671. *
  23672. * @type {number}
  23673. * @default 1
  23674. */
  23675. this.yRadius = yRadius;
  23676. /**
  23677. * The start angle of the curve in radians starting from the positive X axis.
  23678. *
  23679. * @type {number}
  23680. * @default 0
  23681. */
  23682. this.aStartAngle = aStartAngle;
  23683. /**
  23684. * The end angle of the curve in radians starting from the positive X axis.
  23685. *
  23686. * @type {number}
  23687. * @default Math.PI*2
  23688. */
  23689. this.aEndAngle = aEndAngle;
  23690. /**
  23691. * Whether the ellipse is drawn clockwise or not.
  23692. *
  23693. * @type {boolean}
  23694. * @default false
  23695. */
  23696. this.aClockwise = aClockwise;
  23697. /**
  23698. * The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  23699. *
  23700. * @type {number}
  23701. * @default 0
  23702. */
  23703. this.aRotation = aRotation;
  23704. }
  23705. /**
  23706. * Returns a point on the curve.
  23707. *
  23708. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23709. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  23710. * @return {Vector2} The position on the curve.
  23711. */
  23712. getPoint( t, optionalTarget = new Vector2() ) {
  23713. const point = optionalTarget;
  23714. const twoPi = Math.PI * 2;
  23715. let deltaAngle = this.aEndAngle - this.aStartAngle;
  23716. const samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23717. // ensures that deltaAngle is 0 .. 2 PI
  23718. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23719. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23720. if ( deltaAngle < Number.EPSILON ) {
  23721. if ( samePoints ) {
  23722. deltaAngle = 0;
  23723. } else {
  23724. deltaAngle = twoPi;
  23725. }
  23726. }
  23727. if ( this.aClockwise === true && ! samePoints ) {
  23728. if ( deltaAngle === twoPi ) {
  23729. deltaAngle = - twoPi;
  23730. } else {
  23731. deltaAngle = deltaAngle - twoPi;
  23732. }
  23733. }
  23734. const angle = this.aStartAngle + t * deltaAngle;
  23735. let x = this.aX + this.xRadius * Math.cos( angle );
  23736. let y = this.aY + this.yRadius * Math.sin( angle );
  23737. if ( this.aRotation !== 0 ) {
  23738. const cos = Math.cos( this.aRotation );
  23739. const sin = Math.sin( this.aRotation );
  23740. const tx = x - this.aX;
  23741. const ty = y - this.aY;
  23742. // Rotate the point about the center of the ellipse.
  23743. x = tx * cos - ty * sin + this.aX;
  23744. y = tx * sin + ty * cos + this.aY;
  23745. }
  23746. return point.set( x, y );
  23747. }
  23748. copy( source ) {
  23749. super.copy( source );
  23750. this.aX = source.aX;
  23751. this.aY = source.aY;
  23752. this.xRadius = source.xRadius;
  23753. this.yRadius = source.yRadius;
  23754. this.aStartAngle = source.aStartAngle;
  23755. this.aEndAngle = source.aEndAngle;
  23756. this.aClockwise = source.aClockwise;
  23757. this.aRotation = source.aRotation;
  23758. return this;
  23759. }
  23760. toJSON() {
  23761. const data = super.toJSON();
  23762. data.aX = this.aX;
  23763. data.aY = this.aY;
  23764. data.xRadius = this.xRadius;
  23765. data.yRadius = this.yRadius;
  23766. data.aStartAngle = this.aStartAngle;
  23767. data.aEndAngle = this.aEndAngle;
  23768. data.aClockwise = this.aClockwise;
  23769. data.aRotation = this.aRotation;
  23770. return data;
  23771. }
  23772. fromJSON( json ) {
  23773. super.fromJSON( json );
  23774. this.aX = json.aX;
  23775. this.aY = json.aY;
  23776. this.xRadius = json.xRadius;
  23777. this.yRadius = json.yRadius;
  23778. this.aStartAngle = json.aStartAngle;
  23779. this.aEndAngle = json.aEndAngle;
  23780. this.aClockwise = json.aClockwise;
  23781. this.aRotation = json.aRotation;
  23782. return this;
  23783. }
  23784. }
  23785. /**
  23786. * A curve representing an arc.
  23787. *
  23788. * @augments EllipseCurve
  23789. */
  23790. class ArcCurve extends EllipseCurve {
  23791. /**
  23792. * Constructs a new arc curve.
  23793. *
  23794. * @param {number} [aX=0] - The X center of the ellipse.
  23795. * @param {number} [aY=0] - The Y center of the ellipse.
  23796. * @param {number} [aRadius=1] - The radius of the ellipse in the x direction.
  23797. * @param {number} [aStartAngle=0] - The start angle of the curve in radians starting from the positive X axis.
  23798. * @param {number} [aEndAngle=Math.PI*2] - The end angle of the curve in radians starting from the positive X axis.
  23799. * @param {boolean} [aClockwise=false] - Whether the ellipse is drawn clockwise or not.
  23800. */
  23801. constructor( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23802. super( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23803. /**
  23804. * This flag can be used for type testing.
  23805. *
  23806. * @type {boolean}
  23807. * @readonly
  23808. * @default true
  23809. */
  23810. this.isArcCurve = true;
  23811. this.type = 'ArcCurve';
  23812. }
  23813. }
  23814. function CubicPoly() {
  23815. /**
  23816. * Centripetal CatmullRom Curve - which is useful for avoiding
  23817. * cusps and self-intersections in non-uniform catmull rom curves.
  23818. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23819. *
  23820. * curve.type accepts centripetal(default), chordal and catmullrom
  23821. * curve.tension is used for catmullrom which defaults to 0.5
  23822. */
  23823. /*
  23824. Based on an optimized c++ solution in
  23825. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23826. - http://ideone.com/NoEbVM
  23827. This CubicPoly class could be used for reusing some variables and calculations,
  23828. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23829. which can be placed in CurveUtils.
  23830. */
  23831. let c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23832. /*
  23833. * Compute coefficients for a cubic polynomial
  23834. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23835. * such that
  23836. * p(0) = x0, p(1) = x1
  23837. * and
  23838. * p'(0) = t0, p'(1) = t1.
  23839. */
  23840. function init( x0, x1, t0, t1 ) {
  23841. c0 = x0;
  23842. c1 = t0;
  23843. c2 = -3 * x0 + 3 * x1 - 2 * t0 - t1;
  23844. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23845. }
  23846. return {
  23847. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23848. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23849. },
  23850. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23851. // compute tangents when parameterized in [t1,t2]
  23852. let t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23853. let t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23854. // rescale tangents for parametrization in [0,1]
  23855. t1 *= dt1;
  23856. t2 *= dt1;
  23857. init( x1, x2, t1, t2 );
  23858. },
  23859. calc: function ( t ) {
  23860. const t2 = t * t;
  23861. const t3 = t2 * t;
  23862. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23863. }
  23864. };
  23865. }
  23866. //
  23867. const tmp = /*@__PURE__*/ new Vector3();
  23868. const px = /*@__PURE__*/ new CubicPoly();
  23869. const py = /*@__PURE__*/ new CubicPoly();
  23870. const pz = /*@__PURE__*/ new CubicPoly();
  23871. /**
  23872. * A curve representing a Catmull-Rom spline.
  23873. *
  23874. * ```js
  23875. * //Create a closed wavey loop
  23876. * const curve = new THREE.CatmullRomCurve3( [
  23877. * new THREE.Vector3( -10, 0, 10 ),
  23878. * new THREE.Vector3( -5, 5, 5 ),
  23879. * new THREE.Vector3( 0, 0, 0 ),
  23880. * new THREE.Vector3( 5, -5, 5 ),
  23881. * new THREE.Vector3( 10, 0, 10 )
  23882. * ] );
  23883. *
  23884. * const points = curve.getPoints( 50 );
  23885. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  23886. *
  23887. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  23888. *
  23889. * // Create the final object to add to the scene
  23890. * const curveObject = new THREE.Line( geometry, material );
  23891. * ```
  23892. *
  23893. * @augments Curve
  23894. */
  23895. class CatmullRomCurve3 extends Curve {
  23896. /**
  23897. * Constructs a new Catmull-Rom curve.
  23898. *
  23899. * @param {Array<Vector3>} [points] - An array of 3D points defining the curve.
  23900. * @param {boolean} [closed=false] - Whether the curve is closed or not.
  23901. * @param {('centripetal'|'chordal'|'catmullrom')} [curveType='centripetal'] - The curve type.
  23902. * @param {number} [tension=0.5] - Tension of the curve.
  23903. */
  23904. constructor( points = [], closed = false, curveType = 'centripetal', tension = 0.5 ) {
  23905. super();
  23906. /**
  23907. * This flag can be used for type testing.
  23908. *
  23909. * @type {boolean}
  23910. * @readonly
  23911. * @default true
  23912. */
  23913. this.isCatmullRomCurve3 = true;
  23914. this.type = 'CatmullRomCurve3';
  23915. /**
  23916. * An array of 3D points defining the curve.
  23917. *
  23918. * @type {Array<Vector3>}
  23919. */
  23920. this.points = points;
  23921. /**
  23922. * Whether the curve is closed or not.
  23923. *
  23924. * @type {boolean}
  23925. * @default false
  23926. */
  23927. this.closed = closed;
  23928. /**
  23929. * The curve type.
  23930. *
  23931. * @type {('centripetal'|'chordal'|'catmullrom')}
  23932. * @default 'centripetal'
  23933. */
  23934. this.curveType = curveType;
  23935. /**
  23936. * Tension of the curve.
  23937. *
  23938. * @type {number}
  23939. * @default 0.5
  23940. */
  23941. this.tension = tension;
  23942. }
  23943. /**
  23944. * Returns a point on the curve.
  23945. *
  23946. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  23947. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  23948. * @return {Vector3} The position on the curve.
  23949. */
  23950. getPoint( t, optionalTarget = new Vector3() ) {
  23951. const point = optionalTarget;
  23952. const points = this.points;
  23953. const l = points.length;
  23954. const p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23955. let intPoint = Math.floor( p );
  23956. let weight = p - intPoint;
  23957. if ( this.closed ) {
  23958. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / l ) + 1 ) * l;
  23959. } else if ( weight === 0 && intPoint === l - 1 ) {
  23960. intPoint = l - 2;
  23961. weight = 1;
  23962. }
  23963. let p0, p3; // 4 points (p1 & p2 defined below)
  23964. if ( this.closed || intPoint > 0 ) {
  23965. p0 = points[ ( intPoint - 1 ) % l ];
  23966. } else {
  23967. // extrapolate first point
  23968. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23969. p0 = tmp;
  23970. }
  23971. const p1 = points[ intPoint % l ];
  23972. const p2 = points[ ( intPoint + 1 ) % l ];
  23973. if ( this.closed || intPoint + 2 < l ) {
  23974. p3 = points[ ( intPoint + 2 ) % l ];
  23975. } else {
  23976. // extrapolate last point
  23977. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23978. p3 = tmp;
  23979. }
  23980. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23981. // init Centripetal / Chordal Catmull-Rom
  23982. const pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23983. let dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23984. let dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23985. let dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23986. // safety check for repeated points
  23987. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23988. if ( dt0 < 1e-4 ) dt0 = dt1;
  23989. if ( dt2 < 1e-4 ) dt2 = dt1;
  23990. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23991. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23992. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23993. } else if ( this.curveType === 'catmullrom' ) {
  23994. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23995. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23996. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23997. }
  23998. point.set(
  23999. px.calc( weight ),
  24000. py.calc( weight ),
  24001. pz.calc( weight )
  24002. );
  24003. return point;
  24004. }
  24005. copy( source ) {
  24006. super.copy( source );
  24007. this.points = [];
  24008. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24009. const point = source.points[ i ];
  24010. this.points.push( point.clone() );
  24011. }
  24012. this.closed = source.closed;
  24013. this.curveType = source.curveType;
  24014. this.tension = source.tension;
  24015. return this;
  24016. }
  24017. toJSON() {
  24018. const data = super.toJSON();
  24019. data.points = [];
  24020. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24021. const point = this.points[ i ];
  24022. data.points.push( point.toArray() );
  24023. }
  24024. data.closed = this.closed;
  24025. data.curveType = this.curveType;
  24026. data.tension = this.tension;
  24027. return data;
  24028. }
  24029. fromJSON( json ) {
  24030. super.fromJSON( json );
  24031. this.points = [];
  24032. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24033. const point = json.points[ i ];
  24034. this.points.push( new Vector3().fromArray( point ) );
  24035. }
  24036. this.closed = json.closed;
  24037. this.curveType = json.curveType;
  24038. this.tension = json.tension;
  24039. return this;
  24040. }
  24041. }
  24042. /**
  24043. * Interpolations contains spline and Bézier functions internally used by concrete curve classes.
  24044. *
  24045. * Bezier Curves formulas obtained from: https://en.wikipedia.org/wiki/B%C3%A9zier_curve
  24046. *
  24047. * @module Interpolations
  24048. */
  24049. /**
  24050. * Computes a point on a Catmull-Rom spline.
  24051. *
  24052. * @param {number} t - The interpolation factor.
  24053. * @param {number} p0 - The first control point.
  24054. * @param {number} p1 - The second control point.
  24055. * @param {number} p2 - The third control point.
  24056. * @param {number} p3 - The fourth control point.
  24057. * @return {number} The calculated point on a Catmull-Rom spline.
  24058. */
  24059. function CatmullRom( t, p0, p1, p2, p3 ) {
  24060. const v0 = ( p2 - p0 ) * 0.5;
  24061. const v1 = ( p3 - p1 ) * 0.5;
  24062. const t2 = t * t;
  24063. const t3 = t * t2;
  24064. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( -3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  24065. }
  24066. //
  24067. function QuadraticBezierP0( t, p ) {
  24068. const k = 1 - t;
  24069. return k * k * p;
  24070. }
  24071. function QuadraticBezierP1( t, p ) {
  24072. return 2 * ( 1 - t ) * t * p;
  24073. }
  24074. function QuadraticBezierP2( t, p ) {
  24075. return t * t * p;
  24076. }
  24077. /**
  24078. * Computes a point on a Quadratic Bezier curve.
  24079. *
  24080. * @param {number} t - The interpolation factor.
  24081. * @param {number} p0 - The first control point.
  24082. * @param {number} p1 - The second control point.
  24083. * @param {number} p2 - The third control point.
  24084. * @return {number} The calculated point on a Quadratic Bezier curve.
  24085. */
  24086. function QuadraticBezier( t, p0, p1, p2 ) {
  24087. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  24088. QuadraticBezierP2( t, p2 );
  24089. }
  24090. //
  24091. function CubicBezierP0( t, p ) {
  24092. const k = 1 - t;
  24093. return k * k * k * p;
  24094. }
  24095. function CubicBezierP1( t, p ) {
  24096. const k = 1 - t;
  24097. return 3 * k * k * t * p;
  24098. }
  24099. function CubicBezierP2( t, p ) {
  24100. return 3 * ( 1 - t ) * t * t * p;
  24101. }
  24102. function CubicBezierP3( t, p ) {
  24103. return t * t * t * p;
  24104. }
  24105. /**
  24106. * Computes a point on a Cubic Bezier curve.
  24107. *
  24108. * @param {number} t - The interpolation factor.
  24109. * @param {number} p0 - The first control point.
  24110. * @param {number} p1 - The second control point.
  24111. * @param {number} p2 - The third control point.
  24112. * @param {number} p3 - The fourth control point.
  24113. * @return {number} The calculated point on a Cubic Bezier curve.
  24114. */
  24115. function CubicBezier( t, p0, p1, p2, p3 ) {
  24116. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  24117. CubicBezierP3( t, p3 );
  24118. }
  24119. /**
  24120. * A curve representing a 2D Cubic Bezier curve.
  24121. *
  24122. * ```js
  24123. * const curve = new THREE.CubicBezierCurve(
  24124. * new THREE.Vector2( - 0, 0 ),
  24125. * new THREE.Vector2( - 5, 15 ),
  24126. * new THREE.Vector2( 20, 15 ),
  24127. * new THREE.Vector2( 10, 0 )
  24128. * );
  24129. *
  24130. * const points = curve.getPoints( 50 );
  24131. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24132. *
  24133. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24134. *
  24135. * // Create the final object to add to the scene
  24136. * const curveObject = new THREE.Line( geometry, material );
  24137. * ```
  24138. *
  24139. * @augments Curve
  24140. */
  24141. class CubicBezierCurve extends Curve {
  24142. /**
  24143. * Constructs a new Cubic Bezier curve.
  24144. *
  24145. * @param {Vector2} [v0] - The start point.
  24146. * @param {Vector2} [v1] - The first control point.
  24147. * @param {Vector2} [v2] - The second control point.
  24148. * @param {Vector2} [v3] - The end point.
  24149. */
  24150. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2(), v3 = new Vector2() ) {
  24151. super();
  24152. /**
  24153. * This flag can be used for type testing.
  24154. *
  24155. * @type {boolean}
  24156. * @readonly
  24157. * @default true
  24158. */
  24159. this.isCubicBezierCurve = true;
  24160. this.type = 'CubicBezierCurve';
  24161. /**
  24162. * The start point.
  24163. *
  24164. * @type {Vector2}
  24165. */
  24166. this.v0 = v0;
  24167. /**
  24168. * The first control point.
  24169. *
  24170. * @type {Vector2}
  24171. */
  24172. this.v1 = v1;
  24173. /**
  24174. * The second control point.
  24175. *
  24176. * @type {Vector2}
  24177. */
  24178. this.v2 = v2;
  24179. /**
  24180. * The end point.
  24181. *
  24182. * @type {Vector2}
  24183. */
  24184. this.v3 = v3;
  24185. }
  24186. /**
  24187. * Returns a point on the curve.
  24188. *
  24189. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24190. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24191. * @return {Vector2} The position on the curve.
  24192. */
  24193. getPoint( t, optionalTarget = new Vector2() ) {
  24194. const point = optionalTarget;
  24195. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24196. point.set(
  24197. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24198. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  24199. );
  24200. return point;
  24201. }
  24202. copy( source ) {
  24203. super.copy( source );
  24204. this.v0.copy( source.v0 );
  24205. this.v1.copy( source.v1 );
  24206. this.v2.copy( source.v2 );
  24207. this.v3.copy( source.v3 );
  24208. return this;
  24209. }
  24210. toJSON() {
  24211. const data = super.toJSON();
  24212. data.v0 = this.v0.toArray();
  24213. data.v1 = this.v1.toArray();
  24214. data.v2 = this.v2.toArray();
  24215. data.v3 = this.v3.toArray();
  24216. return data;
  24217. }
  24218. fromJSON( json ) {
  24219. super.fromJSON( json );
  24220. this.v0.fromArray( json.v0 );
  24221. this.v1.fromArray( json.v1 );
  24222. this.v2.fromArray( json.v2 );
  24223. this.v3.fromArray( json.v3 );
  24224. return this;
  24225. }
  24226. }
  24227. /**
  24228. * A curve representing a 3D Cubic Bezier curve.
  24229. *
  24230. * @augments Curve
  24231. */
  24232. class CubicBezierCurve3 extends Curve {
  24233. /**
  24234. * Constructs a new Cubic Bezier curve.
  24235. *
  24236. * @param {Vector3} [v0] - The start point.
  24237. * @param {Vector3} [v1] - The first control point.
  24238. * @param {Vector3} [v2] - The second control point.
  24239. * @param {Vector3} [v3] - The end point.
  24240. */
  24241. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3() ) {
  24242. super();
  24243. /**
  24244. * This flag can be used for type testing.
  24245. *
  24246. * @type {boolean}
  24247. * @readonly
  24248. * @default true
  24249. */
  24250. this.isCubicBezierCurve3 = true;
  24251. this.type = 'CubicBezierCurve3';
  24252. /**
  24253. * The start point.
  24254. *
  24255. * @type {Vector3}
  24256. */
  24257. this.v0 = v0;
  24258. /**
  24259. * The first control point.
  24260. *
  24261. * @type {Vector3}
  24262. */
  24263. this.v1 = v1;
  24264. /**
  24265. * The second control point.
  24266. *
  24267. * @type {Vector3}
  24268. */
  24269. this.v2 = v2;
  24270. /**
  24271. * The end point.
  24272. *
  24273. * @type {Vector3}
  24274. */
  24275. this.v3 = v3;
  24276. }
  24277. /**
  24278. * Returns a point on the curve.
  24279. *
  24280. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24281. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24282. * @return {Vector3} The position on the curve.
  24283. */
  24284. getPoint( t, optionalTarget = new Vector3() ) {
  24285. const point = optionalTarget;
  24286. const v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  24287. point.set(
  24288. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  24289. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  24290. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  24291. );
  24292. return point;
  24293. }
  24294. copy( source ) {
  24295. super.copy( source );
  24296. this.v0.copy( source.v0 );
  24297. this.v1.copy( source.v1 );
  24298. this.v2.copy( source.v2 );
  24299. this.v3.copy( source.v3 );
  24300. return this;
  24301. }
  24302. toJSON() {
  24303. const data = super.toJSON();
  24304. data.v0 = this.v0.toArray();
  24305. data.v1 = this.v1.toArray();
  24306. data.v2 = this.v2.toArray();
  24307. data.v3 = this.v3.toArray();
  24308. return data;
  24309. }
  24310. fromJSON( json ) {
  24311. super.fromJSON( json );
  24312. this.v0.fromArray( json.v0 );
  24313. this.v1.fromArray( json.v1 );
  24314. this.v2.fromArray( json.v2 );
  24315. this.v3.fromArray( json.v3 );
  24316. return this;
  24317. }
  24318. }
  24319. /**
  24320. * A curve representing a 2D line segment.
  24321. *
  24322. * @augments Curve
  24323. */
  24324. class LineCurve extends Curve {
  24325. /**
  24326. * Constructs a new line curve.
  24327. *
  24328. * @param {Vector2} [v1] - The start point.
  24329. * @param {Vector2} [v2] - The end point.
  24330. */
  24331. constructor( v1 = new Vector2(), v2 = new Vector2() ) {
  24332. super();
  24333. /**
  24334. * This flag can be used for type testing.
  24335. *
  24336. * @type {boolean}
  24337. * @readonly
  24338. * @default true
  24339. */
  24340. this.isLineCurve = true;
  24341. this.type = 'LineCurve';
  24342. /**
  24343. * The start point.
  24344. *
  24345. * @type {Vector2}
  24346. */
  24347. this.v1 = v1;
  24348. /**
  24349. * The end point.
  24350. *
  24351. * @type {Vector2}
  24352. */
  24353. this.v2 = v2;
  24354. }
  24355. /**
  24356. * Returns a point on the line.
  24357. *
  24358. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24359. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24360. * @return {Vector2} The position on the line.
  24361. */
  24362. getPoint( t, optionalTarget = new Vector2() ) {
  24363. const point = optionalTarget;
  24364. if ( t === 1 ) {
  24365. point.copy( this.v2 );
  24366. } else {
  24367. point.copy( this.v2 ).sub( this.v1 );
  24368. point.multiplyScalar( t ).add( this.v1 );
  24369. }
  24370. return point;
  24371. }
  24372. // Line curve is linear, so we can overwrite default getPointAt
  24373. getPointAt( u, optionalTarget ) {
  24374. return this.getPoint( u, optionalTarget );
  24375. }
  24376. getTangent( t, optionalTarget = new Vector2() ) {
  24377. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24378. }
  24379. getTangentAt( u, optionalTarget ) {
  24380. return this.getTangent( u, optionalTarget );
  24381. }
  24382. copy( source ) {
  24383. super.copy( source );
  24384. this.v1.copy( source.v1 );
  24385. this.v2.copy( source.v2 );
  24386. return this;
  24387. }
  24388. toJSON() {
  24389. const data = super.toJSON();
  24390. data.v1 = this.v1.toArray();
  24391. data.v2 = this.v2.toArray();
  24392. return data;
  24393. }
  24394. fromJSON( json ) {
  24395. super.fromJSON( json );
  24396. this.v1.fromArray( json.v1 );
  24397. this.v2.fromArray( json.v2 );
  24398. return this;
  24399. }
  24400. }
  24401. /**
  24402. * A curve representing a 3D line segment.
  24403. *
  24404. * @augments Curve
  24405. */
  24406. class LineCurve3 extends Curve {
  24407. /**
  24408. * Constructs a new line curve.
  24409. *
  24410. * @param {Vector3} [v1] - The start point.
  24411. * @param {Vector3} [v2] - The end point.
  24412. */
  24413. constructor( v1 = new Vector3(), v2 = new Vector3() ) {
  24414. super();
  24415. /**
  24416. * This flag can be used for type testing.
  24417. *
  24418. * @type {boolean}
  24419. * @readonly
  24420. * @default true
  24421. */
  24422. this.isLineCurve3 = true;
  24423. this.type = 'LineCurve3';
  24424. /**
  24425. * The start point.
  24426. *
  24427. * @type {Vector3}
  24428. */
  24429. this.v1 = v1;
  24430. /**
  24431. * The end point.
  24432. *
  24433. * @type {Vector2}
  24434. */
  24435. this.v2 = v2;
  24436. }
  24437. /**
  24438. * Returns a point on the line.
  24439. *
  24440. * @param {number} t - A interpolation factor representing a position on the line. Must be in the range `[0,1]`.
  24441. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24442. * @return {Vector3} The position on the line.
  24443. */
  24444. getPoint( t, optionalTarget = new Vector3() ) {
  24445. const point = optionalTarget;
  24446. if ( t === 1 ) {
  24447. point.copy( this.v2 );
  24448. } else {
  24449. point.copy( this.v2 ).sub( this.v1 );
  24450. point.multiplyScalar( t ).add( this.v1 );
  24451. }
  24452. return point;
  24453. }
  24454. // Line curve is linear, so we can overwrite default getPointAt
  24455. getPointAt( u, optionalTarget ) {
  24456. return this.getPoint( u, optionalTarget );
  24457. }
  24458. getTangent( t, optionalTarget = new Vector3() ) {
  24459. return optionalTarget.subVectors( this.v2, this.v1 ).normalize();
  24460. }
  24461. getTangentAt( u, optionalTarget ) {
  24462. return this.getTangent( u, optionalTarget );
  24463. }
  24464. copy( source ) {
  24465. super.copy( source );
  24466. this.v1.copy( source.v1 );
  24467. this.v2.copy( source.v2 );
  24468. return this;
  24469. }
  24470. toJSON() {
  24471. const data = super.toJSON();
  24472. data.v1 = this.v1.toArray();
  24473. data.v2 = this.v2.toArray();
  24474. return data;
  24475. }
  24476. fromJSON( json ) {
  24477. super.fromJSON( json );
  24478. this.v1.fromArray( json.v1 );
  24479. this.v2.fromArray( json.v2 );
  24480. return this;
  24481. }
  24482. }
  24483. /**
  24484. * A curve representing a 2D Quadratic Bezier curve.
  24485. *
  24486. * ```js
  24487. * const curve = new THREE.QuadraticBezierCurve(
  24488. * new THREE.Vector2( - 10, 0 ),
  24489. * new THREE.Vector2( 20, 15 ),
  24490. * new THREE.Vector2( 10, 0 )
  24491. * )
  24492. *
  24493. * const points = curve.getPoints( 50 );
  24494. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24495. *
  24496. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24497. *
  24498. * // Create the final object to add to the scene
  24499. * const curveObject = new THREE.Line( geometry, material );
  24500. * ```
  24501. *
  24502. * @augments Curve
  24503. */
  24504. class QuadraticBezierCurve extends Curve {
  24505. /**
  24506. * Constructs a new Quadratic Bezier curve.
  24507. *
  24508. * @param {Vector2} [v0] - The start point.
  24509. * @param {Vector2} [v1] - The control point.
  24510. * @param {Vector2} [v2] - The end point.
  24511. */
  24512. constructor( v0 = new Vector2(), v1 = new Vector2(), v2 = new Vector2() ) {
  24513. super();
  24514. /**
  24515. * This flag can be used for type testing.
  24516. *
  24517. * @type {boolean}
  24518. * @readonly
  24519. * @default true
  24520. */
  24521. this.isQuadraticBezierCurve = true;
  24522. this.type = 'QuadraticBezierCurve';
  24523. /**
  24524. * The start point.
  24525. *
  24526. * @type {Vector2}
  24527. */
  24528. this.v0 = v0;
  24529. /**
  24530. * The control point.
  24531. *
  24532. * @type {Vector2}
  24533. */
  24534. this.v1 = v1;
  24535. /**
  24536. * The end point.
  24537. *
  24538. * @type {Vector2}
  24539. */
  24540. this.v2 = v2;
  24541. }
  24542. /**
  24543. * Returns a point on the curve.
  24544. *
  24545. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24546. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24547. * @return {Vector2} The position on the curve.
  24548. */
  24549. getPoint( t, optionalTarget = new Vector2() ) {
  24550. const point = optionalTarget;
  24551. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24552. point.set(
  24553. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24554. QuadraticBezier( t, v0.y, v1.y, v2.y )
  24555. );
  24556. return point;
  24557. }
  24558. copy( source ) {
  24559. super.copy( source );
  24560. this.v0.copy( source.v0 );
  24561. this.v1.copy( source.v1 );
  24562. this.v2.copy( source.v2 );
  24563. return this;
  24564. }
  24565. toJSON() {
  24566. const data = super.toJSON();
  24567. data.v0 = this.v0.toArray();
  24568. data.v1 = this.v1.toArray();
  24569. data.v2 = this.v2.toArray();
  24570. return data;
  24571. }
  24572. fromJSON( json ) {
  24573. super.fromJSON( json );
  24574. this.v0.fromArray( json.v0 );
  24575. this.v1.fromArray( json.v1 );
  24576. this.v2.fromArray( json.v2 );
  24577. return this;
  24578. }
  24579. }
  24580. /**
  24581. * A curve representing a 3D Quadratic Bezier curve.
  24582. *
  24583. * @augments Curve
  24584. */
  24585. class QuadraticBezierCurve3 extends Curve {
  24586. /**
  24587. * Constructs a new Quadratic Bezier curve.
  24588. *
  24589. * @param {Vector3} [v0] - The start point.
  24590. * @param {Vector3} [v1] - The control point.
  24591. * @param {Vector3} [v2] - The end point.
  24592. */
  24593. constructor( v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3() ) {
  24594. super();
  24595. /**
  24596. * This flag can be used for type testing.
  24597. *
  24598. * @type {boolean}
  24599. * @readonly
  24600. * @default true
  24601. */
  24602. this.isQuadraticBezierCurve3 = true;
  24603. this.type = 'QuadraticBezierCurve3';
  24604. /**
  24605. * The start point.
  24606. *
  24607. * @type {Vector3}
  24608. */
  24609. this.v0 = v0;
  24610. /**
  24611. * The control point.
  24612. *
  24613. * @type {Vector3}
  24614. */
  24615. this.v1 = v1;
  24616. /**
  24617. * The end point.
  24618. *
  24619. * @type {Vector3}
  24620. */
  24621. this.v2 = v2;
  24622. }
  24623. /**
  24624. * Returns a point on the curve.
  24625. *
  24626. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24627. * @param {Vector3} [optionalTarget] - The optional target vector the result is written to.
  24628. * @return {Vector3} The position on the curve.
  24629. */
  24630. getPoint( t, optionalTarget = new Vector3() ) {
  24631. const point = optionalTarget;
  24632. const v0 = this.v0, v1 = this.v1, v2 = this.v2;
  24633. point.set(
  24634. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  24635. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  24636. QuadraticBezier( t, v0.z, v1.z, v2.z )
  24637. );
  24638. return point;
  24639. }
  24640. copy( source ) {
  24641. super.copy( source );
  24642. this.v0.copy( source.v0 );
  24643. this.v1.copy( source.v1 );
  24644. this.v2.copy( source.v2 );
  24645. return this;
  24646. }
  24647. toJSON() {
  24648. const data = super.toJSON();
  24649. data.v0 = this.v0.toArray();
  24650. data.v1 = this.v1.toArray();
  24651. data.v2 = this.v2.toArray();
  24652. return data;
  24653. }
  24654. fromJSON( json ) {
  24655. super.fromJSON( json );
  24656. this.v0.fromArray( json.v0 );
  24657. this.v1.fromArray( json.v1 );
  24658. this.v2.fromArray( json.v2 );
  24659. return this;
  24660. }
  24661. }
  24662. /**
  24663. * A curve representing a 2D spline curve.
  24664. *
  24665. * ```js
  24666. * // Create a sine-like wave
  24667. * const curve = new THREE.SplineCurve( [
  24668. * new THREE.Vector2( -10, 0 ),
  24669. * new THREE.Vector2( -5, 5 ),
  24670. * new THREE.Vector2( 0, 0 ),
  24671. * new THREE.Vector2( 5, -5 ),
  24672. * new THREE.Vector2( 10, 0 )
  24673. * ] );
  24674. *
  24675. * const points = curve.getPoints( 50 );
  24676. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24677. *
  24678. * const material = new THREE.LineBasicMaterial( { color: 0xff0000 } );
  24679. *
  24680. * // Create the final object to add to the scene
  24681. * const splineObject = new THREE.Line( geometry, material );
  24682. * ```
  24683. *
  24684. * @augments Curve
  24685. */
  24686. class SplineCurve extends Curve {
  24687. /**
  24688. * Constructs a new 2D spline curve.
  24689. *
  24690. * @param {Array<Vector2>} [points] - An array of 2D points defining the curve.
  24691. */
  24692. constructor( points = [] ) {
  24693. super();
  24694. /**
  24695. * This flag can be used for type testing.
  24696. *
  24697. * @type {boolean}
  24698. * @readonly
  24699. * @default true
  24700. */
  24701. this.isSplineCurve = true;
  24702. this.type = 'SplineCurve';
  24703. /**
  24704. * An array of 2D points defining the curve.
  24705. *
  24706. * @type {Array<Vector2>}
  24707. */
  24708. this.points = points;
  24709. }
  24710. /**
  24711. * Returns a point on the curve.
  24712. *
  24713. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24714. * @param {Vector2} [optionalTarget] - The optional target vector the result is written to.
  24715. * @return {Vector2} The position on the curve.
  24716. */
  24717. getPoint( t, optionalTarget = new Vector2() ) {
  24718. const point = optionalTarget;
  24719. const points = this.points;
  24720. const p = ( points.length - 1 ) * t;
  24721. const intPoint = Math.floor( p );
  24722. const weight = p - intPoint;
  24723. const p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  24724. const p1 = points[ intPoint ];
  24725. const p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  24726. const p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  24727. point.set(
  24728. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  24729. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  24730. );
  24731. return point;
  24732. }
  24733. copy( source ) {
  24734. super.copy( source );
  24735. this.points = [];
  24736. for ( let i = 0, l = source.points.length; i < l; i ++ ) {
  24737. const point = source.points[ i ];
  24738. this.points.push( point.clone() );
  24739. }
  24740. return this;
  24741. }
  24742. toJSON() {
  24743. const data = super.toJSON();
  24744. data.points = [];
  24745. for ( let i = 0, l = this.points.length; i < l; i ++ ) {
  24746. const point = this.points[ i ];
  24747. data.points.push( point.toArray() );
  24748. }
  24749. return data;
  24750. }
  24751. fromJSON( json ) {
  24752. super.fromJSON( json );
  24753. this.points = [];
  24754. for ( let i = 0, l = json.points.length; i < l; i ++ ) {
  24755. const point = json.points[ i ];
  24756. this.points.push( new Vector2().fromArray( point ) );
  24757. }
  24758. return this;
  24759. }
  24760. }
  24761. var Curves = /*#__PURE__*/Object.freeze({
  24762. __proto__: null,
  24763. ArcCurve: ArcCurve,
  24764. CatmullRomCurve3: CatmullRomCurve3,
  24765. CubicBezierCurve: CubicBezierCurve,
  24766. CubicBezierCurve3: CubicBezierCurve3,
  24767. EllipseCurve: EllipseCurve,
  24768. LineCurve: LineCurve,
  24769. LineCurve3: LineCurve3,
  24770. QuadraticBezierCurve: QuadraticBezierCurve,
  24771. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24772. SplineCurve: SplineCurve
  24773. });
  24774. /**
  24775. * A base class extending {@link Curve}. `CurvePath` is simply an
  24776. * array of connected curves, but retains the API of a curve.
  24777. *
  24778. * @augments Curve
  24779. */
  24780. class CurvePath extends Curve {
  24781. /**
  24782. * Constructs a new curve path.
  24783. */
  24784. constructor() {
  24785. super();
  24786. this.type = 'CurvePath';
  24787. /**
  24788. * An array of curves defining the
  24789. * path.
  24790. *
  24791. * @type {Array<Curve>}
  24792. */
  24793. this.curves = [];
  24794. /**
  24795. * Whether the path should automatically be closed
  24796. * by a line curve.
  24797. *
  24798. * @type {boolean}
  24799. * @default false
  24800. */
  24801. this.autoClose = false;
  24802. }
  24803. /**
  24804. * Adds a curve to this curve path.
  24805. *
  24806. * @param {Curve} curve - The curve to add.
  24807. */
  24808. add( curve ) {
  24809. this.curves.push( curve );
  24810. }
  24811. /**
  24812. * Adds a line curve to close the path.
  24813. *
  24814. * @return {CurvePath} A reference to this curve path.
  24815. */
  24816. closePath() {
  24817. // Add a line curve if start and end of lines are not connected
  24818. const startPoint = this.curves[ 0 ].getPoint( 0 );
  24819. const endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24820. if ( ! startPoint.equals( endPoint ) ) {
  24821. const lineType = ( startPoint.isVector2 === true ) ? 'LineCurve' : 'LineCurve3';
  24822. this.curves.push( new Curves[ lineType ]( endPoint, startPoint ) );
  24823. }
  24824. return this;
  24825. }
  24826. /**
  24827. * This method returns a vector in 2D or 3D space (depending on the curve definitions)
  24828. * for the given interpolation factor.
  24829. *
  24830. * @param {number} t - A interpolation factor representing a position on the curve. Must be in the range `[0,1]`.
  24831. * @param {(Vector2|Vector3)} [optionalTarget] - The optional target vector the result is written to.
  24832. * @return {?(Vector2|Vector3)} The position on the curve. It can be a 2D or 3D vector depending on the curve definition.
  24833. */
  24834. getPoint( t, optionalTarget ) {
  24835. // To get accurate point with reference to
  24836. // entire path distance at time t,
  24837. // following has to be done:
  24838. // 1. Length of each sub path have to be known
  24839. // 2. Locate and identify type of curve
  24840. // 3. Get t for the curve
  24841. // 4. Return curve.getPointAt(t')
  24842. const d = t * this.getLength();
  24843. const curveLengths = this.getCurveLengths();
  24844. let i = 0;
  24845. // To think about boundaries points.
  24846. while ( i < curveLengths.length ) {
  24847. if ( curveLengths[ i ] >= d ) {
  24848. const diff = curveLengths[ i ] - d;
  24849. const curve = this.curves[ i ];
  24850. const segmentLength = curve.getLength();
  24851. const u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24852. return curve.getPointAt( u, optionalTarget );
  24853. }
  24854. i ++;
  24855. }
  24856. return null;
  24857. // loop where sum != 0, sum > d , sum+1 <d
  24858. }
  24859. getLength() {
  24860. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24861. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24862. // getPoint() depends on getLength
  24863. const lens = this.getCurveLengths();
  24864. return lens[ lens.length - 1 ];
  24865. }
  24866. updateArcLengths() {
  24867. // cacheLengths must be recalculated.
  24868. this.needsUpdate = true;
  24869. this.cacheLengths = null;
  24870. this.getCurveLengths();
  24871. }
  24872. /**
  24873. * Returns list of cumulative curve lengths of the defined curves.
  24874. *
  24875. * @return {Array<number>} The curve lengths.
  24876. */
  24877. getCurveLengths() {
  24878. // Compute lengths and cache them
  24879. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24880. // We use cache values if curves and cache array are same length
  24881. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24882. return this.cacheLengths;
  24883. }
  24884. // Get length of sub-curve
  24885. // Push sums into cached array
  24886. const lengths = [];
  24887. let sums = 0;
  24888. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24889. sums += this.curves[ i ].getLength();
  24890. lengths.push( sums );
  24891. }
  24892. this.cacheLengths = lengths;
  24893. return lengths;
  24894. }
  24895. getSpacedPoints( divisions = 40 ) {
  24896. const points = [];
  24897. for ( let i = 0; i <= divisions; i ++ ) {
  24898. points.push( this.getPoint( i / divisions ) );
  24899. }
  24900. if ( this.autoClose ) {
  24901. points.push( points[ 0 ] );
  24902. }
  24903. return points;
  24904. }
  24905. getPoints( divisions = 12 ) {
  24906. const points = [];
  24907. let last;
  24908. for ( let i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24909. const curve = curves[ i ];
  24910. const resolution = curve.isEllipseCurve ? divisions * 2
  24911. : ( curve.isLineCurve || curve.isLineCurve3 ) ? 1
  24912. : curve.isSplineCurve ? divisions * curve.points.length
  24913. : divisions;
  24914. const pts = curve.getPoints( resolution );
  24915. for ( let j = 0; j < pts.length; j ++ ) {
  24916. const point = pts[ j ];
  24917. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24918. points.push( point );
  24919. last = point;
  24920. }
  24921. }
  24922. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24923. points.push( points[ 0 ] );
  24924. }
  24925. return points;
  24926. }
  24927. copy( source ) {
  24928. super.copy( source );
  24929. this.curves = [];
  24930. for ( let i = 0, l = source.curves.length; i < l; i ++ ) {
  24931. const curve = source.curves[ i ];
  24932. this.curves.push( curve.clone() );
  24933. }
  24934. this.autoClose = source.autoClose;
  24935. return this;
  24936. }
  24937. toJSON() {
  24938. const data = super.toJSON();
  24939. data.autoClose = this.autoClose;
  24940. data.curves = [];
  24941. for ( let i = 0, l = this.curves.length; i < l; i ++ ) {
  24942. const curve = this.curves[ i ];
  24943. data.curves.push( curve.toJSON() );
  24944. }
  24945. return data;
  24946. }
  24947. fromJSON( json ) {
  24948. super.fromJSON( json );
  24949. this.autoClose = json.autoClose;
  24950. this.curves = [];
  24951. for ( let i = 0, l = json.curves.length; i < l; i ++ ) {
  24952. const curve = json.curves[ i ];
  24953. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24954. }
  24955. return this;
  24956. }
  24957. }
  24958. /**
  24959. * A 2D path representation. The class provides methods for creating paths
  24960. * and contours of 2D shapes similar to the 2D Canvas API.
  24961. *
  24962. * ```js
  24963. * const path = new THREE.Path();
  24964. *
  24965. * path.lineTo( 0, 0.8 );
  24966. * path.quadraticCurveTo( 0, 1, 0.2, 1 );
  24967. * path.lineTo( 1, 1 );
  24968. *
  24969. * const points = path.getPoints();
  24970. *
  24971. * const geometry = new THREE.BufferGeometry().setFromPoints( points );
  24972. * const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
  24973. *
  24974. * const line = new THREE.Line( geometry, material );
  24975. * scene.add( line );
  24976. * ```
  24977. *
  24978. * @augments CurvePath
  24979. */
  24980. class Path extends CurvePath {
  24981. /**
  24982. * Constructs a new path.
  24983. *
  24984. * @param {Array<Vector2>} [points] - An array of 2D points defining the path.
  24985. */
  24986. constructor( points ) {
  24987. super();
  24988. this.type = 'Path';
  24989. /**
  24990. * The current offset of the path. Any new curve added will start here.
  24991. *
  24992. * @type {Vector2}
  24993. */
  24994. this.currentPoint = new Vector2();
  24995. if ( points ) {
  24996. this.setFromPoints( points );
  24997. }
  24998. }
  24999. /**
  25000. * Creates a path from the given list of points. The points are added
  25001. * to the path as instances of {@link LineCurve}.
  25002. *
  25003. * @param {Array<Vector2>} points - An array of 2D points.
  25004. * @return {Path} A reference to this path.
  25005. */
  25006. setFromPoints( points ) {
  25007. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  25008. for ( let i = 1, l = points.length; i < l; i ++ ) {
  25009. this.lineTo( points[ i ].x, points[ i ].y );
  25010. }
  25011. return this;
  25012. }
  25013. /**
  25014. * Moves {@link Path#currentPoint} to the given point.
  25015. *
  25016. * @param {number} x - The x coordinate.
  25017. * @param {number} y - The y coordinate.
  25018. * @return {Path} A reference to this path.
  25019. */
  25020. moveTo( x, y ) {
  25021. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25022. return this;
  25023. }
  25024. /**
  25025. * Adds an instance of {@link LineCurve} to the path by connecting
  25026. * the current point with the given one.
  25027. *
  25028. * @param {number} x - The x coordinate of the end point.
  25029. * @param {number} y - The y coordinate of the end point.
  25030. * @return {Path} A reference to this path.
  25031. */
  25032. lineTo( x, y ) {
  25033. const curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25034. this.curves.push( curve );
  25035. this.currentPoint.set( x, y );
  25036. return this;
  25037. }
  25038. /**
  25039. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  25040. * the current point with the given one.
  25041. *
  25042. * @param {number} aCPx - The x coordinate of the control point.
  25043. * @param {number} aCPy - The y coordinate of the control point.
  25044. * @param {number} aX - The x coordinate of the end point.
  25045. * @param {number} aY - The y coordinate of the end point.
  25046. * @return {Path} A reference to this path.
  25047. */
  25048. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  25049. const curve = new QuadraticBezierCurve(
  25050. this.currentPoint.clone(),
  25051. new Vector2( aCPx, aCPy ),
  25052. new Vector2( aX, aY )
  25053. );
  25054. this.curves.push( curve );
  25055. this.currentPoint.set( aX, aY );
  25056. return this;
  25057. }
  25058. /**
  25059. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  25060. * the current point with the given one.
  25061. *
  25062. * @param {number} aCP1x - The x coordinate of the first control point.
  25063. * @param {number} aCP1y - The y coordinate of the first control point.
  25064. * @param {number} aCP2x - The x coordinate of the second control point.
  25065. * @param {number} aCP2y - The y coordinate of the second control point.
  25066. * @param {number} aX - The x coordinate of the end point.
  25067. * @param {number} aY - The y coordinate of the end point.
  25068. * @return {Path} A reference to this path.
  25069. */
  25070. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25071. const curve = new CubicBezierCurve(
  25072. this.currentPoint.clone(),
  25073. new Vector2( aCP1x, aCP1y ),
  25074. new Vector2( aCP2x, aCP2y ),
  25075. new Vector2( aX, aY )
  25076. );
  25077. this.curves.push( curve );
  25078. this.currentPoint.set( aX, aY );
  25079. return this;
  25080. }
  25081. /**
  25082. * Adds an instance of {@link SplineCurve} to the path by connecting
  25083. * the current point with the given list of points.
  25084. *
  25085. * @param {Array<Vector2>} pts - An array of points in 2D space.
  25086. * @return {Path} A reference to this path.
  25087. */
  25088. splineThru( pts ) {
  25089. const npts = [ this.currentPoint.clone() ].concat( pts );
  25090. const curve = new SplineCurve( npts );
  25091. this.curves.push( curve );
  25092. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25093. return this;
  25094. }
  25095. /**
  25096. * Adds an arc as an instance of {@link EllipseCurve} to the path, positioned relative
  25097. * to the current point.
  25098. *
  25099. * @param {number} [aX=0] - The x coordinate of the center of the arc offsetted from the previous curve.
  25100. * @param {number} [aY=0] - The y coordinate of the center of the arc offsetted from the previous curve.
  25101. * @param {number} [aRadius=1] - The radius of the arc.
  25102. * @param {number} [aStartAngle=0] - The start angle in radians.
  25103. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25104. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25105. * @return {Path} A reference to this path.
  25106. */
  25107. arc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25108. const x0 = this.currentPoint.x;
  25109. const y0 = this.currentPoint.y;
  25110. this.absarc( aX + x0, aY + y0, aRadius,
  25111. aStartAngle, aEndAngle, aClockwise );
  25112. return this;
  25113. }
  25114. /**
  25115. * Adds an absolutely positioned arc as an instance of {@link EllipseCurve} to the path.
  25116. *
  25117. * @param {number} [aX=0] - The x coordinate of the center of the arc.
  25118. * @param {number} [aY=0] - The y coordinate of the center of the arc.
  25119. * @param {number} [aRadius=1] - The radius of the arc.
  25120. * @param {number} [aStartAngle=0] - The start angle in radians.
  25121. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25122. * @param {boolean} [aClockwise=false] - Whether to sweep the arc clockwise or not.
  25123. * @return {Path} A reference to this path.
  25124. */
  25125. absarc( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25126. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25127. return this;
  25128. }
  25129. /**
  25130. * Adds an ellipse as an instance of {@link EllipseCurve} to the path, positioned relative
  25131. * to the current point
  25132. *
  25133. * @param {number} [aX=0] - The x coordinate of the center of the ellipse offsetted from the previous curve.
  25134. * @param {number} [aY=0] - The y coordinate of the center of the ellipse offsetted from the previous curve.
  25135. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25136. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25137. * @param {number} [aStartAngle=0] - The start angle in radians.
  25138. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25139. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25140. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25141. * @return {Path} A reference to this path.
  25142. */
  25143. ellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25144. const x0 = this.currentPoint.x;
  25145. const y0 = this.currentPoint.y;
  25146. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25147. return this;
  25148. }
  25149. /**
  25150. * Adds an absolutely positioned ellipse as an instance of {@link EllipseCurve} to the path.
  25151. *
  25152. * @param {number} [aX=0] - The x coordinate of the absolute center of the ellipse.
  25153. * @param {number} [aY=0] - The y coordinate of the absolute center of the ellipse.
  25154. * @param {number} [xRadius=1] - The radius of the ellipse in the x axis.
  25155. * @param {number} [yRadius=1] - The radius of the ellipse in the y axis.
  25156. * @param {number} [aStartAngle=0] - The start angle in radians.
  25157. * @param {number} [aEndAngle=Math.PI*2] - The end angle in radians.
  25158. * @param {boolean} [aClockwise=false] - Whether to sweep the ellipse clockwise or not.
  25159. * @param {number} [aRotation=0] - The rotation angle of the ellipse in radians, counterclockwise from the positive X axis.
  25160. * @return {Path} A reference to this path.
  25161. */
  25162. absellipse( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25163. const curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25164. if ( this.curves.length > 0 ) {
  25165. // if a previous curve is present, attempt to join
  25166. const firstPoint = curve.getPoint( 0 );
  25167. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25168. this.lineTo( firstPoint.x, firstPoint.y );
  25169. }
  25170. }
  25171. this.curves.push( curve );
  25172. const lastPoint = curve.getPoint( 1 );
  25173. this.currentPoint.copy( lastPoint );
  25174. return this;
  25175. }
  25176. copy( source ) {
  25177. super.copy( source );
  25178. this.currentPoint.copy( source.currentPoint );
  25179. return this;
  25180. }
  25181. toJSON() {
  25182. const data = super.toJSON();
  25183. data.currentPoint = this.currentPoint.toArray();
  25184. return data;
  25185. }
  25186. fromJSON( json ) {
  25187. super.fromJSON( json );
  25188. this.currentPoint.fromArray( json.currentPoint );
  25189. return this;
  25190. }
  25191. }
  25192. /**
  25193. * Defines an arbitrary 2d shape plane using paths with optional holes. It
  25194. * can be used with {@link ExtrudeGeometry}, {@link ShapeGeometry}, to get
  25195. * points, or to get triangulated faces.
  25196. *
  25197. * ```js
  25198. * const heartShape = new THREE.Shape();
  25199. *
  25200. * heartShape.moveTo( 25, 25 );
  25201. * heartShape.bezierCurveTo( 25, 25, 20, 0, 0, 0 );
  25202. * heartShape.bezierCurveTo( - 30, 0, - 30, 35, - 30, 35 );
  25203. * heartShape.bezierCurveTo( - 30, 55, - 10, 77, 25, 95 );
  25204. * heartShape.bezierCurveTo( 60, 77, 80, 55, 80, 35 );
  25205. * heartShape.bezierCurveTo( 80, 35, 80, 0, 50, 0 );
  25206. * heartShape.bezierCurveTo( 35, 0, 25, 25, 25, 25 );
  25207. *
  25208. * const extrudeSettings = {
  25209. * depth: 8,
  25210. * bevelEnabled: true,
  25211. * bevelSegments: 2,
  25212. * steps: 2,
  25213. * bevelSize: 1,
  25214. * bevelThickness: 1
  25215. * };
  25216. *
  25217. * const geometry = new THREE.ExtrudeGeometry( heartShape, extrudeSettings );
  25218. * const mesh = new THREE.Mesh( geometry, new THREE.MeshBasicMaterial() );
  25219. * ```
  25220. *
  25221. * @augments Path
  25222. */
  25223. class Shape extends Path {
  25224. /**
  25225. * Constructs a new shape.
  25226. *
  25227. * @param {Array<Vector2>} [points] - An array of 2D points defining the shape.
  25228. */
  25229. constructor( points ) {
  25230. super( points );
  25231. /**
  25232. * The UUID of the shape.
  25233. *
  25234. * @type {string}
  25235. * @readonly
  25236. */
  25237. this.uuid = generateUUID();
  25238. this.type = 'Shape';
  25239. /**
  25240. * Defines the holes in the shape. Hole definitions must use the
  25241. * opposite winding order (CW/CCW) than the outer shape.
  25242. *
  25243. * @type {Array<Path>}
  25244. * @readonly
  25245. */
  25246. this.holes = [];
  25247. }
  25248. /**
  25249. * Returns an array representing each contour of the holes
  25250. * as a list of 2D points.
  25251. *
  25252. * @param {number} divisions - The fineness of the result.
  25253. * @return {Array<Array<Vector2>>} The holes as a series of 2D points.
  25254. */
  25255. getPointsHoles( divisions ) {
  25256. const holesPts = [];
  25257. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25258. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25259. }
  25260. return holesPts;
  25261. }
  25262. // get points of shape and holes (keypoints based on segments parameter)
  25263. /**
  25264. * Returns an object that holds contour data for the shape and its holes as
  25265. * arrays of 2D points.
  25266. *
  25267. * @param {number} divisions - The fineness of the result.
  25268. * @return {{shape:Array<Vector2>,holes:Array<Array<Vector2>>}} An object with contour data.
  25269. */
  25270. extractPoints( divisions ) {
  25271. return {
  25272. shape: this.getPoints( divisions ),
  25273. holes: this.getPointsHoles( divisions )
  25274. };
  25275. }
  25276. copy( source ) {
  25277. super.copy( source );
  25278. this.holes = [];
  25279. for ( let i = 0, l = source.holes.length; i < l; i ++ ) {
  25280. const hole = source.holes[ i ];
  25281. this.holes.push( hole.clone() );
  25282. }
  25283. return this;
  25284. }
  25285. toJSON() {
  25286. const data = super.toJSON();
  25287. data.uuid = this.uuid;
  25288. data.holes = [];
  25289. for ( let i = 0, l = this.holes.length; i < l; i ++ ) {
  25290. const hole = this.holes[ i ];
  25291. data.holes.push( hole.toJSON() );
  25292. }
  25293. return data;
  25294. }
  25295. fromJSON( json ) {
  25296. super.fromJSON( json );
  25297. this.uuid = json.uuid;
  25298. this.holes = [];
  25299. for ( let i = 0, l = json.holes.length; i < l; i ++ ) {
  25300. const hole = json.holes[ i ];
  25301. this.holes.push( new Path().fromJSON( hole ) );
  25302. }
  25303. return this;
  25304. }
  25305. }
  25306. /* eslint-disable */
  25307. // copy of mapbox/earcut version 3.0.2
  25308. // https://github.com/mapbox/earcut/tree/v3.0.2
  25309. function earcut(data, holeIndices, dim = 2) {
  25310. const hasHoles = holeIndices && holeIndices.length;
  25311. const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  25312. let outerNode = linkedList(data, 0, outerLen, dim, true);
  25313. const triangles = [];
  25314. if (!outerNode || outerNode.next === outerNode.prev) return triangles;
  25315. let minX, minY, invSize;
  25316. if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  25317. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  25318. if (data.length > 80 * dim) {
  25319. minX = data[0];
  25320. minY = data[1];
  25321. let maxX = minX;
  25322. let maxY = minY;
  25323. for (let i = dim; i < outerLen; i += dim) {
  25324. const x = data[i];
  25325. const y = data[i + 1];
  25326. if (x < minX) minX = x;
  25327. if (y < minY) minY = y;
  25328. if (x > maxX) maxX = x;
  25329. if (y > maxY) maxY = y;
  25330. }
  25331. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  25332. invSize = Math.max(maxX - minX, maxY - minY);
  25333. invSize = invSize !== 0 ? 32767 / invSize : 0;
  25334. }
  25335. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  25336. return triangles;
  25337. }
  25338. // create a circular doubly linked list from polygon points in the specified winding order
  25339. function linkedList(data, start, end, dim, clockwise) {
  25340. let last;
  25341. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  25342. for (let i = start; i < end; i += dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25343. } else {
  25344. for (let i = end - dim; i >= start; i -= dim) last = insertNode(i / dim | 0, data[i], data[i + 1], last);
  25345. }
  25346. if (last && equals(last, last.next)) {
  25347. removeNode(last);
  25348. last = last.next;
  25349. }
  25350. return last;
  25351. }
  25352. // eliminate colinear or duplicate points
  25353. function filterPoints(start, end) {
  25354. if (!start) return start;
  25355. if (!end) end = start;
  25356. let p = start,
  25357. again;
  25358. do {
  25359. again = false;
  25360. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  25361. removeNode(p);
  25362. p = end = p.prev;
  25363. if (p === p.next) break;
  25364. again = true;
  25365. } else {
  25366. p = p.next;
  25367. }
  25368. } while (again || p !== end);
  25369. return end;
  25370. }
  25371. // main ear slicing loop which triangulates a polygon (given as a linked list)
  25372. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  25373. if (!ear) return;
  25374. // interlink polygon nodes in z-order
  25375. if (!pass && invSize) indexCurve(ear, minX, minY, invSize);
  25376. let stop = ear;
  25377. // iterate through ears, slicing them one by one
  25378. while (ear.prev !== ear.next) {
  25379. const prev = ear.prev;
  25380. const next = ear.next;
  25381. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  25382. triangles.push(prev.i, ear.i, next.i); // cut off the triangle
  25383. removeNode(ear);
  25384. // skipping the next vertex leads to less sliver triangles
  25385. ear = next.next;
  25386. stop = next.next;
  25387. continue;
  25388. }
  25389. ear = next;
  25390. // if we looped through the whole remaining polygon and can't find any more ears
  25391. if (ear === stop) {
  25392. // try filtering points and slicing again
  25393. if (!pass) {
  25394. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  25395. // if this didn't work, try curing all small self-intersections locally
  25396. } else if (pass === 1) {
  25397. ear = cureLocalIntersections(filterPoints(ear), triangles);
  25398. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  25399. // as a last resort, try splitting the remaining polygon into two
  25400. } else if (pass === 2) {
  25401. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  25402. }
  25403. break;
  25404. }
  25405. }
  25406. }
  25407. // check whether a polygon node forms a valid ear with adjacent nodes
  25408. function isEar(ear) {
  25409. const a = ear.prev,
  25410. b = ear,
  25411. c = ear.next;
  25412. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25413. // now make sure we don't have other points inside the potential ear
  25414. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25415. // triangle bbox
  25416. const x0 = Math.min(ax, bx, cx),
  25417. y0 = Math.min(ay, by, cy),
  25418. x1 = Math.max(ax, bx, cx),
  25419. y1 = Math.max(ay, by, cy);
  25420. let p = c.next;
  25421. while (p !== a) {
  25422. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  25423. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  25424. area(p.prev, p, p.next) >= 0) return false;
  25425. p = p.next;
  25426. }
  25427. return true;
  25428. }
  25429. function isEarHashed(ear, minX, minY, invSize) {
  25430. const a = ear.prev,
  25431. b = ear,
  25432. c = ear.next;
  25433. if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
  25434. const ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  25435. // triangle bbox
  25436. const x0 = Math.min(ax, bx, cx),
  25437. y0 = Math.min(ay, by, cy),
  25438. x1 = Math.max(ax, bx, cx),
  25439. y1 = Math.max(ay, by, cy);
  25440. // z-order range for the current triangle bbox;
  25441. const minZ = zOrder(x0, y0, minX, minY, invSize),
  25442. maxZ = zOrder(x1, y1, minX, minY, invSize);
  25443. let p = ear.prevZ,
  25444. n = ear.nextZ;
  25445. // look for points inside the triangle in both directions
  25446. while (p && p.z >= minZ && n && n.z <= maxZ) {
  25447. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  25448. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;
  25449. p = p.prevZ;
  25450. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25451. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25452. n = n.nextZ;
  25453. }
  25454. // look for remaining points in decreasing z-order
  25455. while (p && p.z >= minZ) {
  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. }
  25460. // look for remaining points in increasing z-order
  25461. while (n && n.z <= maxZ) {
  25462. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  25463. pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;
  25464. n = n.nextZ;
  25465. }
  25466. return true;
  25467. }
  25468. // go through all polygon nodes and cure small local self-intersections
  25469. function cureLocalIntersections(start, triangles) {
  25470. let p = start;
  25471. do {
  25472. const a = p.prev,
  25473. b = p.next.next;
  25474. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  25475. triangles.push(a.i, p.i, b.i);
  25476. // remove two nodes involved
  25477. removeNode(p);
  25478. removeNode(p.next);
  25479. p = start = b;
  25480. }
  25481. p = p.next;
  25482. } while (p !== start);
  25483. return filterPoints(p);
  25484. }
  25485. // try splitting polygon into two and triangulate them independently
  25486. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  25487. // look for a valid diagonal that divides the polygon into two
  25488. let a = start;
  25489. do {
  25490. let b = a.next.next;
  25491. while (b !== a.prev) {
  25492. if (a.i !== b.i && isValidDiagonal(a, b)) {
  25493. // split the polygon in two by the diagonal
  25494. let c = splitPolygon(a, b);
  25495. // filter colinear points around the cuts
  25496. a = filterPoints(a, a.next);
  25497. c = filterPoints(c, c.next);
  25498. // run earcut on each half
  25499. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  25500. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  25501. return;
  25502. }
  25503. b = b.next;
  25504. }
  25505. a = a.next;
  25506. } while (a !== start);
  25507. }
  25508. // link every hole into the outer loop, producing a single-ring polygon without holes
  25509. function eliminateHoles(data, holeIndices, outerNode, dim) {
  25510. const queue = [];
  25511. for (let i = 0, len = holeIndices.length; i < len; i++) {
  25512. const start = holeIndices[i] * dim;
  25513. const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  25514. const list = linkedList(data, start, end, dim, false);
  25515. if (list === list.next) list.steiner = true;
  25516. queue.push(getLeftmost(list));
  25517. }
  25518. queue.sort(compareXYSlope);
  25519. // process holes from left to right
  25520. for (let i = 0; i < queue.length; i++) {
  25521. outerNode = eliminateHole(queue[i], outerNode);
  25522. }
  25523. return outerNode;
  25524. }
  25525. function compareXYSlope(a, b) {
  25526. let result = a.x - b.x;
  25527. // when the left-most point of 2 holes meet at a vertex, sort the holes counterclockwise so that when we find
  25528. // the bridge to the outer shell is always the point that they meet at.
  25529. if (result === 0) {
  25530. result = a.y - b.y;
  25531. if (result === 0) {
  25532. const aSlope = (a.next.y - a.y) / (a.next.x - a.x);
  25533. const bSlope = (b.next.y - b.y) / (b.next.x - b.x);
  25534. result = aSlope - bSlope;
  25535. }
  25536. }
  25537. return result;
  25538. }
  25539. // find a bridge between vertices that connects hole with an outer ring and link it
  25540. function eliminateHole(hole, outerNode) {
  25541. const bridge = findHoleBridge(hole, outerNode);
  25542. if (!bridge) {
  25543. return outerNode;
  25544. }
  25545. const bridgeReverse = splitPolygon(bridge, hole);
  25546. // filter collinear points around the cuts
  25547. filterPoints(bridgeReverse, bridgeReverse.next);
  25548. return filterPoints(bridge, bridge.next);
  25549. }
  25550. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  25551. function findHoleBridge(hole, outerNode) {
  25552. let p = outerNode;
  25553. const hx = hole.x;
  25554. const hy = hole.y;
  25555. let qx = -Infinity;
  25556. let m;
  25557. // find a segment intersected by a ray from the hole's leftmost point to the left;
  25558. // segment's endpoint with lesser x will be potential connection point
  25559. // unless they intersect at a vertex, then choose the vertex
  25560. if (equals(hole, p)) return p;
  25561. do {
  25562. if (equals(hole, p.next)) return p.next;
  25563. else if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  25564. const x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  25565. if (x <= hx && x > qx) {
  25566. qx = x;
  25567. m = p.x < p.next.x ? p : p.next;
  25568. if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint
  25569. }
  25570. }
  25571. p = p.next;
  25572. } while (p !== outerNode);
  25573. if (!m) return null;
  25574. // look for points inside the triangle of hole point, segment intersection and endpoint;
  25575. // if there are no points found, we have a valid connection;
  25576. // otherwise choose the point of the minimum angle with the ray as connection point
  25577. const stop = m;
  25578. const mx = m.x;
  25579. const my = m.y;
  25580. let tanMin = Infinity;
  25581. p = m;
  25582. do {
  25583. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  25584. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  25585. const tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  25586. if (locallyInside(p, hole) &&
  25587. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  25588. m = p;
  25589. tanMin = tan;
  25590. }
  25591. }
  25592. p = p.next;
  25593. } while (p !== stop);
  25594. return m;
  25595. }
  25596. // whether sector in vertex m contains sector in vertex p in the same coordinates
  25597. function sectorContainsSector(m, p) {
  25598. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  25599. }
  25600. // interlink polygon nodes in z-order
  25601. function indexCurve(start, minX, minY, invSize) {
  25602. let p = start;
  25603. do {
  25604. if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);
  25605. p.prevZ = p.prev;
  25606. p.nextZ = p.next;
  25607. p = p.next;
  25608. } while (p !== start);
  25609. p.prevZ.nextZ = null;
  25610. p.prevZ = null;
  25611. sortLinked(p);
  25612. }
  25613. // Simon Tatham's linked list merge sort algorithm
  25614. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  25615. function sortLinked(list) {
  25616. let numMerges;
  25617. let inSize = 1;
  25618. do {
  25619. let p = list;
  25620. let e;
  25621. list = null;
  25622. let tail = null;
  25623. numMerges = 0;
  25624. while (p) {
  25625. numMerges++;
  25626. let q = p;
  25627. let pSize = 0;
  25628. for (let i = 0; i < inSize; i++) {
  25629. pSize++;
  25630. q = q.nextZ;
  25631. if (!q) break;
  25632. }
  25633. let qSize = inSize;
  25634. while (pSize > 0 || (qSize > 0 && q)) {
  25635. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  25636. e = p;
  25637. p = p.nextZ;
  25638. pSize--;
  25639. } else {
  25640. e = q;
  25641. q = q.nextZ;
  25642. qSize--;
  25643. }
  25644. if (tail) tail.nextZ = e;
  25645. else list = e;
  25646. e.prevZ = tail;
  25647. tail = e;
  25648. }
  25649. p = q;
  25650. }
  25651. tail.nextZ = null;
  25652. inSize *= 2;
  25653. } while (numMerges > 1);
  25654. return list;
  25655. }
  25656. // z-order of a point given coords and inverse of the longer side of data bbox
  25657. function zOrder(x, y, minX, minY, invSize) {
  25658. // coords are transformed into non-negative 15-bit integer range
  25659. x = (x - minX) * invSize | 0;
  25660. y = (y - minY) * invSize | 0;
  25661. x = (x | (x << 8)) & 0x00FF00FF;
  25662. x = (x | (x << 4)) & 0x0F0F0F0F;
  25663. x = (x | (x << 2)) & 0x33333333;
  25664. x = (x | (x << 1)) & 0x55555555;
  25665. y = (y | (y << 8)) & 0x00FF00FF;
  25666. y = (y | (y << 4)) & 0x0F0F0F0F;
  25667. y = (y | (y << 2)) & 0x33333333;
  25668. y = (y | (y << 1)) & 0x55555555;
  25669. return x | (y << 1);
  25670. }
  25671. // find the leftmost node of a polygon ring
  25672. function getLeftmost(start) {
  25673. let p = start,
  25674. leftmost = start;
  25675. do {
  25676. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;
  25677. p = p.next;
  25678. } while (p !== start);
  25679. return leftmost;
  25680. }
  25681. // check if a point lies within a convex triangle
  25682. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  25683. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  25684. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  25685. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  25686. }
  25687. // check if a point lies within a convex triangle but false if its equal to the first point of the triangle
  25688. function pointInTriangleExceptFirst(ax, ay, bx, by, cx, cy, px, py) {
  25689. return !(ax === px && ay === py) && pointInTriangle(ax, ay, bx, by, cx, cy, px, py);
  25690. }
  25691. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  25692. function isValidDiagonal(a, b) {
  25693. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // doesn't intersect other edges
  25694. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  25695. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  25696. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  25697. }
  25698. // signed area of a triangle
  25699. function area(p, q, r) {
  25700. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  25701. }
  25702. // check if two points are equal
  25703. function equals(p1, p2) {
  25704. return p1.x === p2.x && p1.y === p2.y;
  25705. }
  25706. // check if two segments intersect
  25707. function intersects(p1, q1, p2, q2) {
  25708. const o1 = sign(area(p1, q1, p2));
  25709. const o2 = sign(area(p1, q1, q2));
  25710. const o3 = sign(area(p2, q2, p1));
  25711. const o4 = sign(area(p2, q2, q1));
  25712. if (o1 !== o2 && o3 !== o4) return true; // general case
  25713. if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1
  25714. if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1
  25715. if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2
  25716. if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2
  25717. return false;
  25718. }
  25719. // for collinear points p, q, r, check if point q lies on segment pr
  25720. function onSegment(p, q, r) {
  25721. 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);
  25722. }
  25723. function sign(num) {
  25724. return num > 0 ? 1 : num < 0 ? -1 : 0;
  25725. }
  25726. // check if a polygon diagonal intersects any polygon segments
  25727. function intersectsPolygon(a, b) {
  25728. let p = a;
  25729. do {
  25730. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  25731. intersects(p, p.next, a, b)) return true;
  25732. p = p.next;
  25733. } while (p !== a);
  25734. return false;
  25735. }
  25736. // check if a polygon diagonal is locally inside the polygon
  25737. function locallyInside(a, b) {
  25738. return area(a.prev, a, a.next) < 0 ?
  25739. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  25740. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  25741. }
  25742. // check if the middle point of a polygon diagonal is inside the polygon
  25743. function middleInside(a, b) {
  25744. let p = a;
  25745. let inside = false;
  25746. const px = (a.x + b.x) / 2;
  25747. const py = (a.y + b.y) / 2;
  25748. do {
  25749. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  25750. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  25751. inside = !inside;
  25752. p = p.next;
  25753. } while (p !== a);
  25754. return inside;
  25755. }
  25756. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  25757. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  25758. function splitPolygon(a, b) {
  25759. const a2 = createNode(a.i, a.x, a.y),
  25760. b2 = createNode(b.i, b.x, b.y),
  25761. an = a.next,
  25762. bp = b.prev;
  25763. a.next = b;
  25764. b.prev = a;
  25765. a2.next = an;
  25766. an.prev = a2;
  25767. b2.next = a2;
  25768. a2.prev = b2;
  25769. bp.next = b2;
  25770. b2.prev = bp;
  25771. return b2;
  25772. }
  25773. // create a node and optionally link it with previous one (in a circular doubly linked list)
  25774. function insertNode(i, x, y, last) {
  25775. const p = createNode(i, x, y);
  25776. if (!last) {
  25777. p.prev = p;
  25778. p.next = p;
  25779. } else {
  25780. p.next = last.next;
  25781. p.prev = last;
  25782. last.next.prev = p;
  25783. last.next = p;
  25784. }
  25785. return p;
  25786. }
  25787. function removeNode(p) {
  25788. p.next.prev = p.prev;
  25789. p.prev.next = p.next;
  25790. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  25791. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  25792. }
  25793. function createNode(i, x, y) {
  25794. return {
  25795. i, // vertex index in coordinates array
  25796. x, y, // vertex coordinates
  25797. prev: null, // previous and next vertex nodes in a polygon ring
  25798. next: null,
  25799. z: 0, // z-order curve value
  25800. prevZ: null, // previous and next nodes in z-order
  25801. nextZ: null,
  25802. steiner: false // indicates whether this is a steiner point
  25803. };
  25804. }
  25805. function signedArea(data, start, end, dim) {
  25806. let sum = 0;
  25807. for (let i = start, j = end - dim; i < end; i += dim) {
  25808. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  25809. j = i;
  25810. }
  25811. return sum;
  25812. }
  25813. /**
  25814. * An implementation of the earcut polygon triangulation algorithm.
  25815. * The code is a port of [mapbox/earcut](https://github.com/mapbox/earcut).
  25816. *
  25817. * @see https://github.com/mapbox/earcut
  25818. */
  25819. class Earcut {
  25820. /**
  25821. * Triangulates the given shape definition by returning an array of triangles.
  25822. *
  25823. * @param {Array<number>} data - An array with 2D points.
  25824. * @param {Array<number>} holeIndices - An array with indices defining holes.
  25825. * @param {number} [dim=2] - The number of coordinates per vertex in the input array.
  25826. * @return {Array<number>} An array representing the triangulated faces. Each face is defined by three consecutive numbers
  25827. * representing vertex indices.
  25828. */
  25829. static triangulate( data, holeIndices, dim = 2 ) {
  25830. return earcut( data, holeIndices, dim );
  25831. }
  25832. }
  25833. /**
  25834. * A class containing utility functions for shapes.
  25835. *
  25836. * @hideconstructor
  25837. */
  25838. class ShapeUtils {
  25839. /**
  25840. * Calculate area of a ( 2D ) contour polygon.
  25841. *
  25842. * @param {Array<Vector2>} contour - An array of 2D points.
  25843. * @return {number} The area.
  25844. */
  25845. static area( contour ) {
  25846. const n = contour.length;
  25847. let a = 0.0;
  25848. for ( let p = n - 1, q = 0; q < n; p = q ++ ) {
  25849. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  25850. }
  25851. return a * 0.5;
  25852. }
  25853. /**
  25854. * Returns `true` if the given contour uses a clockwise winding order.
  25855. *
  25856. * @param {Array<Vector2>} pts - An array of 2D points defining a polygon.
  25857. * @return {boolean} Whether the given contour uses a clockwise winding order or not.
  25858. */
  25859. static isClockWise( pts ) {
  25860. return ShapeUtils.area( pts ) < 0;
  25861. }
  25862. /**
  25863. * Triangulates the given shape definition.
  25864. *
  25865. * @param {Array<Vector2>} contour - An array of 2D points defining the contour.
  25866. * @param {Array<Array<Vector2>>} holes - An array that holds arrays of 2D points defining the holes.
  25867. * @return {Array<Array<number>>} An array that holds for each face definition an array with three indices.
  25868. */
  25869. static triangulateShape( contour, holes ) {
  25870. const vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  25871. const holeIndices = []; // array of hole indices
  25872. const faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  25873. removeDupEndPts( contour );
  25874. addContour( vertices, contour );
  25875. //
  25876. let holeIndex = contour.length;
  25877. holes.forEach( removeDupEndPts );
  25878. for ( let i = 0; i < holes.length; i ++ ) {
  25879. holeIndices.push( holeIndex );
  25880. holeIndex += holes[ i ].length;
  25881. addContour( vertices, holes[ i ] );
  25882. }
  25883. //
  25884. const triangles = Earcut.triangulate( vertices, holeIndices );
  25885. //
  25886. for ( let i = 0; i < triangles.length; i += 3 ) {
  25887. faces.push( triangles.slice( i, i + 3 ) );
  25888. }
  25889. return faces;
  25890. }
  25891. }
  25892. function removeDupEndPts( points ) {
  25893. const l = points.length;
  25894. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  25895. points.pop();
  25896. }
  25897. }
  25898. function addContour( vertices, contour ) {
  25899. for ( let i = 0; i < contour.length; i ++ ) {
  25900. vertices.push( contour[ i ].x );
  25901. vertices.push( contour[ i ].y );
  25902. }
  25903. }
  25904. /**
  25905. * Creates extruded geometry from a path shape.
  25906. *
  25907. * ```js
  25908. * const length = 12, width = 8;
  25909. *
  25910. * const shape = new THREE.Shape();
  25911. * shape.moveTo( 0,0 );
  25912. * shape.lineTo( 0, width );
  25913. * shape.lineTo( length, width );
  25914. * shape.lineTo( length, 0 );
  25915. * shape.lineTo( 0, 0 );
  25916. *
  25917. * const geometry = new THREE.ExtrudeGeometry( shape );
  25918. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  25919. * const mesh = new THREE.Mesh( geometry, material ) ;
  25920. * scene.add( mesh );
  25921. * ```
  25922. *
  25923. * @augments BufferGeometry
  25924. * @demo scenes/geometry-browser.html#ExtrudeGeometry
  25925. */
  25926. class ExtrudeGeometry extends BufferGeometry {
  25927. /**
  25928. * Constructs a new extrude geometry.
  25929. *
  25930. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  25931. * @param {ExtrudeGeometry~Options} [options] - The extrude settings.
  25932. */
  25933. 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 = {} ) {
  25934. super();
  25935. this.type = 'ExtrudeGeometry';
  25936. /**
  25937. * Holds the constructor parameters that have been
  25938. * used to generate the geometry. Any modification
  25939. * after instantiation does not change the geometry.
  25940. *
  25941. * @type {Object}
  25942. */
  25943. this.parameters = {
  25944. shapes: shapes,
  25945. options: options
  25946. };
  25947. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  25948. const scope = this;
  25949. const verticesArray = [];
  25950. const uvArray = [];
  25951. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  25952. const shape = shapes[ i ];
  25953. addShape( shape );
  25954. }
  25955. // build geometry
  25956. this.setAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  25957. this.setAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  25958. this.computeVertexNormals();
  25959. // functions
  25960. function addShape( shape ) {
  25961. const placeholder = [];
  25962. // options
  25963. const curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  25964. const steps = options.steps !== undefined ? options.steps : 1;
  25965. const depth = options.depth !== undefined ? options.depth : 1;
  25966. let bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true;
  25967. let bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 0.2;
  25968. let bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 0.1;
  25969. let bevelOffset = options.bevelOffset !== undefined ? options.bevelOffset : 0;
  25970. let bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  25971. const extrudePath = options.extrudePath;
  25972. const uvgen = options.UVGenerator !== undefined ? options.UVGenerator : WorldUVGenerator;
  25973. //
  25974. let extrudePts, extrudeByPath = false;
  25975. let splineTube, binormal, normal, position2;
  25976. if ( extrudePath ) {
  25977. extrudePts = extrudePath.getSpacedPoints( steps );
  25978. extrudeByPath = true;
  25979. bevelEnabled = false; // bevels not supported for path extrusion
  25980. // SETUP TNB variables
  25981. // TODO1 - have a .isClosed in spline?
  25982. splineTube = extrudePath.computeFrenetFrames( steps, false );
  25983. // log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  25984. binormal = new Vector3();
  25985. normal = new Vector3();
  25986. position2 = new Vector3();
  25987. }
  25988. // Safeguards if bevels are not enabled
  25989. if ( ! bevelEnabled ) {
  25990. bevelSegments = 0;
  25991. bevelThickness = 0;
  25992. bevelSize = 0;
  25993. bevelOffset = 0;
  25994. }
  25995. // Variables initialization
  25996. const shapePoints = shape.extractPoints( curveSegments );
  25997. let vertices = shapePoints.shape;
  25998. const holes = shapePoints.holes;
  25999. const reverse = ! ShapeUtils.isClockWise( vertices );
  26000. if ( reverse ) {
  26001. vertices = vertices.reverse();
  26002. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  26003. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26004. const ahole = holes[ h ];
  26005. if ( ShapeUtils.isClockWise( ahole ) ) {
  26006. holes[ h ] = ahole.reverse();
  26007. }
  26008. }
  26009. }
  26010. /**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.
  26011. * @param {Array<Vector2>} points
  26012. */
  26013. function mergeOverlappingPoints( points ) {
  26014. const THRESHOLD = 1e-10;
  26015. const THRESHOLD_SQ = THRESHOLD * THRESHOLD;
  26016. let prevPos = points[ 0 ];
  26017. for ( let i = 1; i <= points.length; i ++ ) {
  26018. const currentIndex = i % points.length;
  26019. const currentPos = points[ currentIndex ];
  26020. const dx = currentPos.x - prevPos.x;
  26021. const dy = currentPos.y - prevPos.y;
  26022. const distSq = dx * dx + dy * dy;
  26023. const scalingFactorSqrt = Math.max(
  26024. Math.abs( currentPos.x ),
  26025. Math.abs( currentPos.y ),
  26026. Math.abs( prevPos.x ),
  26027. Math.abs( prevPos.y )
  26028. );
  26029. const thresholdSqScaled = THRESHOLD_SQ * scalingFactorSqrt * scalingFactorSqrt;
  26030. if ( distSq <= thresholdSqScaled ) {
  26031. points.splice( currentIndex, 1 );
  26032. i --;
  26033. continue;
  26034. }
  26035. prevPos = currentPos;
  26036. }
  26037. }
  26038. mergeOverlappingPoints( vertices );
  26039. holes.forEach( mergeOverlappingPoints );
  26040. const numHoles = holes.length;
  26041. /* Vertices */
  26042. const contour = vertices; // vertices has all points but contour has only points of circumference
  26043. for ( let h = 0; h < numHoles; h ++ ) {
  26044. const ahole = holes[ h ];
  26045. vertices = vertices.concat( ahole );
  26046. }
  26047. function scalePt2( pt, vec, size ) {
  26048. if ( ! vec ) error( 'ExtrudeGeometry: vec does not exist' );
  26049. return pt.clone().addScaledVector( vec, size );
  26050. }
  26051. const vlen = vertices.length;
  26052. // Find directions for point movement
  26053. function getBevelVec( inPt, inPrev, inNext ) {
  26054. // computes for inPt the corresponding point inPt' on a new contour
  26055. // shifted by 1 unit (length of normalized vector) to the left
  26056. // if we walk along contour clockwise, this new contour is outside the old one
  26057. //
  26058. // inPt' is the intersection of the two lines parallel to the two
  26059. // adjacent edges of inPt at a distance of 1 unit on the left side.
  26060. let v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  26061. // good reading for geometry algorithms (here: line-line intersection)
  26062. // http://geomalgorithms.com/a05-_intersect-1.html
  26063. const v_prev_x = inPt.x - inPrev.x,
  26064. v_prev_y = inPt.y - inPrev.y;
  26065. const v_next_x = inNext.x - inPt.x,
  26066. v_next_y = inNext.y - inPt.y;
  26067. const v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  26068. // check for collinear edges
  26069. const collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26070. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  26071. // not collinear
  26072. // length of vectors for normalizing
  26073. const v_prev_len = Math.sqrt( v_prev_lensq );
  26074. const v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  26075. // shift adjacent points by unit vectors to the left
  26076. const ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  26077. const ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  26078. const ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  26079. const ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  26080. // scaling factor for v_prev to intersection point
  26081. const sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  26082. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  26083. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  26084. // vector from inPt to intersection point
  26085. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  26086. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  26087. // Don't normalize!, otherwise sharp corners become ugly
  26088. // but prevent crazy spikes
  26089. const v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  26090. if ( v_trans_lensq <= 2 ) {
  26091. return new Vector2( v_trans_x, v_trans_y );
  26092. } else {
  26093. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  26094. }
  26095. } else {
  26096. // handle special case of collinear edges
  26097. let direction_eq = false; // assumes: opposite
  26098. if ( v_prev_x > Number.EPSILON ) {
  26099. if ( v_next_x > Number.EPSILON ) {
  26100. direction_eq = true;
  26101. }
  26102. } else {
  26103. if ( v_prev_x < - Number.EPSILON ) {
  26104. if ( v_next_x < - Number.EPSILON ) {
  26105. direction_eq = true;
  26106. }
  26107. } else {
  26108. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  26109. direction_eq = true;
  26110. }
  26111. }
  26112. }
  26113. if ( direction_eq ) {
  26114. // log("Warning: lines are a straight sequence");
  26115. v_trans_x = - v_prev_y;
  26116. v_trans_y = v_prev_x;
  26117. shrink_by = Math.sqrt( v_prev_lensq );
  26118. } else {
  26119. // log("Warning: lines are a straight spike");
  26120. v_trans_x = v_prev_x;
  26121. v_trans_y = v_prev_y;
  26122. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  26123. }
  26124. }
  26125. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  26126. }
  26127. const contourMovements = [];
  26128. for ( let i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26129. if ( j === il ) j = 0;
  26130. if ( k === il ) k = 0;
  26131. // (j)---(i)---(k)
  26132. // log('i,j,k', i, j , k)
  26133. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  26134. }
  26135. const holesMovements = [];
  26136. let oneHoleMovements, verticesMovements = contourMovements.concat();
  26137. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26138. const ahole = holes[ h ];
  26139. oneHoleMovements = [];
  26140. for ( let i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  26141. if ( j === il ) j = 0;
  26142. if ( k === il ) k = 0;
  26143. // (j)---(i)---(k)
  26144. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  26145. }
  26146. holesMovements.push( oneHoleMovements );
  26147. verticesMovements = verticesMovements.concat( oneHoleMovements );
  26148. }
  26149. let faces;
  26150. if ( bevelSegments === 0 ) {
  26151. faces = ShapeUtils.triangulateShape( contour, holes );
  26152. } else {
  26153. const contractedContourVertices = [];
  26154. const expandedHoleVertices = [];
  26155. // Loop bevelSegments, 1 for the front, 1 for the back
  26156. for ( let b = 0; b < bevelSegments; b ++ ) {
  26157. //for ( b = bevelSegments; b > 0; b -- ) {
  26158. const t = b / bevelSegments;
  26159. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26160. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26161. // contract shape
  26162. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26163. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26164. v( vert.x, vert.y, - z );
  26165. if ( t === 0 ) contractedContourVertices.push( vert );
  26166. }
  26167. // expand holes
  26168. for ( let h = 0, hl = numHoles; h < hl; h ++ ) {
  26169. const ahole = holes[ h ];
  26170. oneHoleMovements = holesMovements[ h ];
  26171. const oneHoleVertices = [];
  26172. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26173. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26174. v( vert.x, vert.y, - z );
  26175. if ( t === 0 ) oneHoleVertices.push( vert );
  26176. }
  26177. if ( t === 0 ) expandedHoleVertices.push( oneHoleVertices );
  26178. }
  26179. }
  26180. faces = ShapeUtils.triangulateShape( contractedContourVertices, expandedHoleVertices );
  26181. }
  26182. const flen = faces.length;
  26183. const bs = bevelSize + bevelOffset;
  26184. // Back facing vertices
  26185. for ( let i = 0; i < vlen; i ++ ) {
  26186. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26187. if ( ! extrudeByPath ) {
  26188. v( vert.x, vert.y, 0 );
  26189. } else {
  26190. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  26191. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  26192. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  26193. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  26194. v( position2.x, position2.y, position2.z );
  26195. }
  26196. }
  26197. // Add stepped vertices...
  26198. // Including front facing vertices
  26199. for ( let s = 1; s <= steps; s ++ ) {
  26200. for ( let i = 0; i < vlen; i ++ ) {
  26201. const vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  26202. if ( ! extrudeByPath ) {
  26203. v( vert.x, vert.y, depth / steps * s );
  26204. } else {
  26205. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  26206. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  26207. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  26208. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  26209. v( position2.x, position2.y, position2.z );
  26210. }
  26211. }
  26212. }
  26213. // Add bevel segments planes
  26214. //for ( b = 1; b <= bevelSegments; b ++ ) {
  26215. for ( let b = bevelSegments - 1; b >= 0; b -- ) {
  26216. const t = b / bevelSegments;
  26217. const z = bevelThickness * Math.cos( t * Math.PI / 2 );
  26218. const bs = bevelSize * Math.sin( t * Math.PI / 2 ) + bevelOffset;
  26219. // contract shape
  26220. for ( let i = 0, il = contour.length; i < il; i ++ ) {
  26221. const vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  26222. v( vert.x, vert.y, depth + z );
  26223. }
  26224. // expand holes
  26225. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26226. const ahole = holes[ h ];
  26227. oneHoleMovements = holesMovements[ h ];
  26228. for ( let i = 0, il = ahole.length; i < il; i ++ ) {
  26229. const vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  26230. if ( ! extrudeByPath ) {
  26231. v( vert.x, vert.y, depth + z );
  26232. } else {
  26233. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  26234. }
  26235. }
  26236. }
  26237. }
  26238. /* Faces */
  26239. // Top and bottom faces
  26240. buildLidFaces();
  26241. // Sides faces
  26242. buildSideFaces();
  26243. ///// Internal functions
  26244. function buildLidFaces() {
  26245. const start = verticesArray.length / 3;
  26246. if ( bevelEnabled ) {
  26247. let layer = 0; // steps + 1
  26248. let offset = vlen * layer;
  26249. // Bottom faces
  26250. for ( let i = 0; i < flen; i ++ ) {
  26251. const face = faces[ i ];
  26252. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  26253. }
  26254. layer = steps + bevelSegments * 2;
  26255. offset = vlen * layer;
  26256. // Top faces
  26257. for ( let i = 0; i < flen; i ++ ) {
  26258. const face = faces[ i ];
  26259. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  26260. }
  26261. } else {
  26262. // Bottom faces
  26263. for ( let i = 0; i < flen; i ++ ) {
  26264. const face = faces[ i ];
  26265. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  26266. }
  26267. // Top faces
  26268. for ( let i = 0; i < flen; i ++ ) {
  26269. const face = faces[ i ];
  26270. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  26271. }
  26272. }
  26273. scope.addGroup( start, verticesArray.length / 3 - start, 0 );
  26274. }
  26275. // Create faces for the z-sides of the shape
  26276. function buildSideFaces() {
  26277. const start = verticesArray.length / 3;
  26278. let layeroffset = 0;
  26279. sidewalls( contour, layeroffset );
  26280. layeroffset += contour.length;
  26281. for ( let h = 0, hl = holes.length; h < hl; h ++ ) {
  26282. const ahole = holes[ h ];
  26283. sidewalls( ahole, layeroffset );
  26284. //, true
  26285. layeroffset += ahole.length;
  26286. }
  26287. scope.addGroup( start, verticesArray.length / 3 - start, 1 );
  26288. }
  26289. function sidewalls( contour, layeroffset ) {
  26290. let i = contour.length;
  26291. while ( -- i >= 0 ) {
  26292. const j = i;
  26293. let k = i - 1;
  26294. if ( k < 0 ) k = contour.length - 1;
  26295. //log('b', i,j, i-1, k,vertices.length);
  26296. for ( let s = 0, sl = ( steps + bevelSegments * 2 ); s < sl; s ++ ) {
  26297. const slen1 = vlen * s;
  26298. const slen2 = vlen * ( s + 1 );
  26299. const a = layeroffset + j + slen1,
  26300. b = layeroffset + k + slen1,
  26301. c = layeroffset + k + slen2,
  26302. d = layeroffset + j + slen2;
  26303. f4( a, b, c, d );
  26304. }
  26305. }
  26306. }
  26307. function v( x, y, z ) {
  26308. placeholder.push( x );
  26309. placeholder.push( y );
  26310. placeholder.push( z );
  26311. }
  26312. function f3( a, b, c ) {
  26313. addVertex( a );
  26314. addVertex( b );
  26315. addVertex( c );
  26316. const nextIndex = verticesArray.length / 3;
  26317. const uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26318. addUV( uvs[ 0 ] );
  26319. addUV( uvs[ 1 ] );
  26320. addUV( uvs[ 2 ] );
  26321. }
  26322. function f4( a, b, c, d ) {
  26323. addVertex( a );
  26324. addVertex( b );
  26325. addVertex( d );
  26326. addVertex( b );
  26327. addVertex( c );
  26328. addVertex( d );
  26329. const nextIndex = verticesArray.length / 3;
  26330. const uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  26331. addUV( uvs[ 0 ] );
  26332. addUV( uvs[ 1 ] );
  26333. addUV( uvs[ 3 ] );
  26334. addUV( uvs[ 1 ] );
  26335. addUV( uvs[ 2 ] );
  26336. addUV( uvs[ 3 ] );
  26337. }
  26338. function addVertex( index ) {
  26339. verticesArray.push( placeholder[ index * 3 + 0 ] );
  26340. verticesArray.push( placeholder[ index * 3 + 1 ] );
  26341. verticesArray.push( placeholder[ index * 3 + 2 ] );
  26342. }
  26343. function addUV( vector2 ) {
  26344. uvArray.push( vector2.x );
  26345. uvArray.push( vector2.y );
  26346. }
  26347. }
  26348. }
  26349. copy( source ) {
  26350. super.copy( source );
  26351. this.parameters = Object.assign( {}, source.parameters );
  26352. return this;
  26353. }
  26354. toJSON() {
  26355. const data = super.toJSON();
  26356. const shapes = this.parameters.shapes;
  26357. const options = this.parameters.options;
  26358. return toJSON$1( shapes, options, data );
  26359. }
  26360. /**
  26361. * Factory method for creating an instance of this class from the given
  26362. * JSON object.
  26363. *
  26364. * @param {Object} data - A JSON object representing the serialized geometry.
  26365. * @param {Array<Shape>} shapes - An array of shapes.
  26366. * @return {ExtrudeGeometry} A new instance.
  26367. */
  26368. static fromJSON( data, shapes ) {
  26369. const geometryShapes = [];
  26370. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  26371. const shape = shapes[ data.shapes[ j ] ];
  26372. geometryShapes.push( shape );
  26373. }
  26374. const extrudePath = data.options.extrudePath;
  26375. if ( extrudePath !== undefined ) {
  26376. data.options.extrudePath = new Curves[ extrudePath.type ]().fromJSON( extrudePath );
  26377. }
  26378. return new ExtrudeGeometry( geometryShapes, data.options );
  26379. }
  26380. }
  26381. const WorldUVGenerator = {
  26382. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  26383. const a_x = vertices[ indexA * 3 ];
  26384. const a_y = vertices[ indexA * 3 + 1 ];
  26385. const b_x = vertices[ indexB * 3 ];
  26386. const b_y = vertices[ indexB * 3 + 1 ];
  26387. const c_x = vertices[ indexC * 3 ];
  26388. const c_y = vertices[ indexC * 3 + 1 ];
  26389. return [
  26390. new Vector2( a_x, a_y ),
  26391. new Vector2( b_x, b_y ),
  26392. new Vector2( c_x, c_y )
  26393. ];
  26394. },
  26395. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  26396. const a_x = vertices[ indexA * 3 ];
  26397. const a_y = vertices[ indexA * 3 + 1 ];
  26398. const a_z = vertices[ indexA * 3 + 2 ];
  26399. const b_x = vertices[ indexB * 3 ];
  26400. const b_y = vertices[ indexB * 3 + 1 ];
  26401. const b_z = vertices[ indexB * 3 + 2 ];
  26402. const c_x = vertices[ indexC * 3 ];
  26403. const c_y = vertices[ indexC * 3 + 1 ];
  26404. const c_z = vertices[ indexC * 3 + 2 ];
  26405. const d_x = vertices[ indexD * 3 ];
  26406. const d_y = vertices[ indexD * 3 + 1 ];
  26407. const d_z = vertices[ indexD * 3 + 2 ];
  26408. if ( Math.abs( a_y - b_y ) < Math.abs( a_x - b_x ) ) {
  26409. return [
  26410. new Vector2( a_x, 1 - a_z ),
  26411. new Vector2( b_x, 1 - b_z ),
  26412. new Vector2( c_x, 1 - c_z ),
  26413. new Vector2( d_x, 1 - d_z )
  26414. ];
  26415. } else {
  26416. return [
  26417. new Vector2( a_y, 1 - a_z ),
  26418. new Vector2( b_y, 1 - b_z ),
  26419. new Vector2( c_y, 1 - c_z ),
  26420. new Vector2( d_y, 1 - d_z )
  26421. ];
  26422. }
  26423. }
  26424. };
  26425. function toJSON$1( shapes, options, data ) {
  26426. data.shapes = [];
  26427. if ( Array.isArray( shapes ) ) {
  26428. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  26429. const shape = shapes[ i ];
  26430. data.shapes.push( shape.uuid );
  26431. }
  26432. } else {
  26433. data.shapes.push( shapes.uuid );
  26434. }
  26435. data.options = Object.assign( {}, options );
  26436. if ( options.extrudePath !== undefined ) data.options.extrudePath = options.extrudePath.toJSON();
  26437. return data;
  26438. }
  26439. /**
  26440. * A geometry class for representing an icosahedron.
  26441. *
  26442. * ```js
  26443. * const geometry = new THREE.IcosahedronGeometry();
  26444. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26445. * const icosahedron = new THREE.Mesh( geometry, material );
  26446. * scene.add( icosahedron );
  26447. * ```
  26448. *
  26449. * @augments PolyhedronGeometry
  26450. * @demo scenes/geometry-browser.html#IcosahedronGeometry
  26451. */
  26452. class IcosahedronGeometry extends PolyhedronGeometry {
  26453. /**
  26454. * Constructs a new icosahedron geometry.
  26455. *
  26456. * @param {number} [radius=1] - Radius of the icosahedron.
  26457. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a icosahedron.
  26458. */
  26459. constructor( radius = 1, detail = 0 ) {
  26460. const t = ( 1 + Math.sqrt( 5 ) ) / 2;
  26461. const vertices = [
  26462. -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t, 0,
  26463. 0, -1, t, 0, 1, t, 0, -1, - t, 0, 1, - t,
  26464. t, 0, -1, t, 0, 1, - t, 0, -1, - t, 0, 1
  26465. ];
  26466. const indices = [
  26467. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  26468. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  26469. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  26470. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  26471. ];
  26472. super( vertices, indices, radius, detail );
  26473. this.type = 'IcosahedronGeometry';
  26474. /**
  26475. * Holds the constructor parameters that have been
  26476. * used to generate the geometry. Any modification
  26477. * after instantiation does not change the geometry.
  26478. *
  26479. * @type {Object}
  26480. */
  26481. this.parameters = {
  26482. radius: radius,
  26483. detail: detail
  26484. };
  26485. }
  26486. /**
  26487. * Factory method for creating an instance of this class from the given
  26488. * JSON object.
  26489. *
  26490. * @param {Object} data - A JSON object representing the serialized geometry.
  26491. * @return {IcosahedronGeometry} A new instance.
  26492. */
  26493. static fromJSON( data ) {
  26494. return new IcosahedronGeometry( data.radius, data.detail );
  26495. }
  26496. }
  26497. /**
  26498. * Creates meshes with axial symmetry like vases. The lathe rotates around the Y axis.
  26499. *
  26500. * ```js
  26501. * const points = [];
  26502. * for ( let i = 0; i < 10; i ++ ) {
  26503. * points.push( new THREE.Vector2( Math.sin( i * 0.2 ) * 10 + 5, ( i - 5 ) * 2 ) );
  26504. * }
  26505. * const geometry = new THREE.LatheGeometry( points );
  26506. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26507. * const lathe = new THREE.Mesh( geometry, material );
  26508. * scene.add( lathe );
  26509. * ```
  26510. *
  26511. * @augments BufferGeometry
  26512. * @demo scenes/geometry-browser.html#LatheGeometry
  26513. */
  26514. class LatheGeometry extends BufferGeometry {
  26515. /**
  26516. * Constructs a new lathe geometry.
  26517. *
  26518. * @param {Array<Vector2|Vector3>} [points] - An array of points in 2D space. The x-coordinate of each point
  26519. * must be greater than zero.
  26520. * @param {number} [segments=12] - The number of circumference segments to generate.
  26521. * @param {number} [phiStart=0] - The starting angle in radians.
  26522. * @param {number} [phiLength=Math.PI*2] - The radian (0 to 2PI) range of the lathed section 2PI is a
  26523. * closed lathe, less than 2PI is a portion.
  26524. */
  26525. 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 ) {
  26526. super();
  26527. this.type = 'LatheGeometry';
  26528. /**
  26529. * Holds the constructor parameters that have been
  26530. * used to generate the geometry. Any modification
  26531. * after instantiation does not change the geometry.
  26532. *
  26533. * @type {Object}
  26534. */
  26535. this.parameters = {
  26536. points: points,
  26537. segments: segments,
  26538. phiStart: phiStart,
  26539. phiLength: phiLength
  26540. };
  26541. segments = Math.floor( segments );
  26542. // clamp phiLength so it's in range of [ 0, 2PI ]
  26543. phiLength = clamp( phiLength, 0, Math.PI * 2 );
  26544. // buffers
  26545. const indices = [];
  26546. const vertices = [];
  26547. const uvs = [];
  26548. const initNormals = [];
  26549. const normals = [];
  26550. // helper variables
  26551. const inverseSegments = 1.0 / segments;
  26552. const vertex = new Vector3();
  26553. const uv = new Vector2();
  26554. const normal = new Vector3();
  26555. const curNormal = new Vector3();
  26556. const prevNormal = new Vector3();
  26557. let dx = 0;
  26558. let dy = 0;
  26559. // pre-compute normals for initial "meridian"
  26560. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26561. switch ( j ) {
  26562. case 0: // special handling for 1st vertex on path
  26563. dx = points[ j + 1 ].x - points[ j ].x;
  26564. dy = points[ j + 1 ].y - points[ j ].y;
  26565. normal.x = dy * 1.0;
  26566. normal.y = - dx;
  26567. normal.z = dy * 0.0;
  26568. prevNormal.copy( normal );
  26569. normal.normalize();
  26570. initNormals.push( normal.x, normal.y, normal.z );
  26571. break;
  26572. case ( points.length - 1 ): // special handling for last Vertex on path
  26573. initNormals.push( prevNormal.x, prevNormal.y, prevNormal.z );
  26574. break;
  26575. default: // default handling for all vertices in between
  26576. dx = points[ j + 1 ].x - points[ j ].x;
  26577. dy = points[ j + 1 ].y - points[ j ].y;
  26578. normal.x = dy * 1.0;
  26579. normal.y = - dx;
  26580. normal.z = dy * 0.0;
  26581. curNormal.copy( normal );
  26582. normal.x += prevNormal.x;
  26583. normal.y += prevNormal.y;
  26584. normal.z += prevNormal.z;
  26585. normal.normalize();
  26586. initNormals.push( normal.x, normal.y, normal.z );
  26587. prevNormal.copy( curNormal );
  26588. }
  26589. }
  26590. // generate vertices, uvs and normals
  26591. for ( let i = 0; i <= segments; i ++ ) {
  26592. const phi = phiStart + i * inverseSegments * phiLength;
  26593. const sin = Math.sin( phi );
  26594. const cos = Math.cos( phi );
  26595. for ( let j = 0; j <= ( points.length - 1 ); j ++ ) {
  26596. // vertex
  26597. vertex.x = points[ j ].x * sin;
  26598. vertex.y = points[ j ].y;
  26599. vertex.z = points[ j ].x * cos;
  26600. vertices.push( vertex.x, vertex.y, vertex.z );
  26601. // uv
  26602. uv.x = i / segments;
  26603. uv.y = j / ( points.length - 1 );
  26604. uvs.push( uv.x, uv.y );
  26605. // normal
  26606. const x = initNormals[ 3 * j + 0 ] * sin;
  26607. const y = initNormals[ 3 * j + 1 ];
  26608. const z = initNormals[ 3 * j + 0 ] * cos;
  26609. normals.push( x, y, z );
  26610. }
  26611. }
  26612. // indices
  26613. for ( let i = 0; i < segments; i ++ ) {
  26614. for ( let j = 0; j < ( points.length - 1 ); j ++ ) {
  26615. const base = j + i * points.length;
  26616. const a = base;
  26617. const b = base + points.length;
  26618. const c = base + points.length + 1;
  26619. const d = base + 1;
  26620. // faces
  26621. indices.push( a, b, d );
  26622. indices.push( c, d, b );
  26623. }
  26624. }
  26625. // build geometry
  26626. this.setIndex( indices );
  26627. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26628. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26629. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26630. }
  26631. copy( source ) {
  26632. super.copy( source );
  26633. this.parameters = Object.assign( {}, source.parameters );
  26634. return this;
  26635. }
  26636. /**
  26637. * Factory method for creating an instance of this class from the given
  26638. * JSON object.
  26639. *
  26640. * @param {Object} data - A JSON object representing the serialized geometry.
  26641. * @return {LatheGeometry} A new instance.
  26642. */
  26643. static fromJSON( data ) {
  26644. return new LatheGeometry( data.points, data.segments, data.phiStart, data.phiLength );
  26645. }
  26646. }
  26647. /**
  26648. * A geometry class for representing an octahedron.
  26649. *
  26650. * ```js
  26651. * const geometry = new THREE.OctahedronGeometry();
  26652. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  26653. * const octahedron = new THREE.Mesh( geometry, material );
  26654. * scene.add( octahedron );
  26655. * ```
  26656. *
  26657. * @augments PolyhedronGeometry
  26658. * @demo scenes/geometry-browser.html#OctahedronGeometry
  26659. */
  26660. class OctahedronGeometry extends PolyhedronGeometry {
  26661. /**
  26662. * Constructs a new octahedron geometry.
  26663. *
  26664. * @param {number} [radius=1] - Radius of the octahedron.
  26665. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a octahedron.
  26666. */
  26667. constructor( radius = 1, detail = 0 ) {
  26668. const vertices = [
  26669. 1, 0, 0, -1, 0, 0, 0, 1, 0,
  26670. 0, -1, 0, 0, 0, 1, 0, 0, -1
  26671. ];
  26672. const indices = [
  26673. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  26674. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  26675. 1, 3, 4, 1, 4, 2
  26676. ];
  26677. super( vertices, indices, radius, detail );
  26678. this.type = 'OctahedronGeometry';
  26679. /**
  26680. * Holds the constructor parameters that have been
  26681. * used to generate the geometry. Any modification
  26682. * after instantiation does not change the geometry.
  26683. *
  26684. * @type {Object}
  26685. */
  26686. this.parameters = {
  26687. radius: radius,
  26688. detail: detail
  26689. };
  26690. }
  26691. /**
  26692. * Factory method for creating an instance of this class from the given
  26693. * JSON object.
  26694. *
  26695. * @param {Object} data - A JSON object representing the serialized geometry.
  26696. * @return {OctahedronGeometry} A new instance.
  26697. */
  26698. static fromJSON( data ) {
  26699. return new OctahedronGeometry( data.radius, data.detail );
  26700. }
  26701. }
  26702. /**
  26703. * A geometry class for representing a plane.
  26704. *
  26705. * ```js
  26706. * const geometry = new THREE.PlaneGeometry( 1, 1 );
  26707. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26708. * const plane = new THREE.Mesh( geometry, material );
  26709. * scene.add( plane );
  26710. * ```
  26711. *
  26712. * @augments BufferGeometry
  26713. * @demo scenes/geometry-browser.html#PlaneGeometry
  26714. */
  26715. class PlaneGeometry extends BufferGeometry {
  26716. /**
  26717. * Constructs a new plane geometry.
  26718. *
  26719. * @param {number} [width=1] - The width along the X axis.
  26720. * @param {number} [height=1] - The height along the Y axis
  26721. * @param {number} [widthSegments=1] - The number of segments along the X axis.
  26722. * @param {number} [heightSegments=1] - The number of segments along the Y axis.
  26723. */
  26724. constructor( width = 1, height = 1, widthSegments = 1, heightSegments = 1 ) {
  26725. super();
  26726. this.type = 'PlaneGeometry';
  26727. /**
  26728. * Holds the constructor parameters that have been
  26729. * used to generate the geometry. Any modification
  26730. * after instantiation does not change the geometry.
  26731. *
  26732. * @type {Object}
  26733. */
  26734. this.parameters = {
  26735. width: width,
  26736. height: height,
  26737. widthSegments: widthSegments,
  26738. heightSegments: heightSegments
  26739. };
  26740. const width_half = width / 2;
  26741. const height_half = height / 2;
  26742. const gridX = Math.floor( widthSegments );
  26743. const gridY = Math.floor( heightSegments );
  26744. const gridX1 = gridX + 1;
  26745. const gridY1 = gridY + 1;
  26746. const segment_width = width / gridX;
  26747. const segment_height = height / gridY;
  26748. //
  26749. const indices = [];
  26750. const vertices = [];
  26751. const normals = [];
  26752. const uvs = [];
  26753. for ( let iy = 0; iy < gridY1; iy ++ ) {
  26754. const y = iy * segment_height - height_half;
  26755. for ( let ix = 0; ix < gridX1; ix ++ ) {
  26756. const x = ix * segment_width - width_half;
  26757. vertices.push( x, - y, 0 );
  26758. normals.push( 0, 0, 1 );
  26759. uvs.push( ix / gridX );
  26760. uvs.push( 1 - ( iy / gridY ) );
  26761. }
  26762. }
  26763. for ( let iy = 0; iy < gridY; iy ++ ) {
  26764. for ( let ix = 0; ix < gridX; ix ++ ) {
  26765. const a = ix + gridX1 * iy;
  26766. const b = ix + gridX1 * ( iy + 1 );
  26767. const c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  26768. const d = ( ix + 1 ) + gridX1 * iy;
  26769. indices.push( a, b, d );
  26770. indices.push( b, c, d );
  26771. }
  26772. }
  26773. this.setIndex( indices );
  26774. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26775. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26776. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26777. }
  26778. copy( source ) {
  26779. super.copy( source );
  26780. this.parameters = Object.assign( {}, source.parameters );
  26781. return this;
  26782. }
  26783. /**
  26784. * Factory method for creating an instance of this class from the given
  26785. * JSON object.
  26786. *
  26787. * @param {Object} data - A JSON object representing the serialized geometry.
  26788. * @return {PlaneGeometry} A new instance.
  26789. */
  26790. static fromJSON( data ) {
  26791. return new PlaneGeometry( data.width, data.height, data.widthSegments, data.heightSegments );
  26792. }
  26793. }
  26794. /**
  26795. * A class for generating a two-dimensional ring geometry.
  26796. *
  26797. * ```js
  26798. * const geometry = new THREE.RingGeometry( 1, 5, 32 );
  26799. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
  26800. * const mesh = new THREE.Mesh( geometry, material );
  26801. * scene.add( mesh );
  26802. * ```
  26803. *
  26804. * @augments BufferGeometry
  26805. * @demo scenes/geometry-browser.html#RingGeometry
  26806. */
  26807. class RingGeometry extends BufferGeometry {
  26808. /**
  26809. * Constructs a new ring geometry.
  26810. *
  26811. * @param {number} [innerRadius=0.5] - The inner radius of the ring.
  26812. * @param {number} [outerRadius=1] - The outer radius of the ring.
  26813. * @param {number} [thetaSegments=32] - Number of segments. A higher number means the ring will be more round. Minimum is `3`.
  26814. * @param {number} [phiSegments=1] - Number of segments per ring segment. Minimum is `1`.
  26815. * @param {number} [thetaStart=0] - Starting angle in radians.
  26816. * @param {number} [thetaLength=Math.PI*2] - Central angle in radians.
  26817. */
  26818. constructor( innerRadius = 0.5, outerRadius = 1, thetaSegments = 32, phiSegments = 1, thetaStart = 0, thetaLength = Math.PI * 2 ) {
  26819. super();
  26820. this.type = 'RingGeometry';
  26821. /**
  26822. * Holds the constructor parameters that have been
  26823. * used to generate the geometry. Any modification
  26824. * after instantiation does not change the geometry.
  26825. *
  26826. * @type {Object}
  26827. */
  26828. this.parameters = {
  26829. innerRadius: innerRadius,
  26830. outerRadius: outerRadius,
  26831. thetaSegments: thetaSegments,
  26832. phiSegments: phiSegments,
  26833. thetaStart: thetaStart,
  26834. thetaLength: thetaLength
  26835. };
  26836. thetaSegments = Math.max( 3, thetaSegments );
  26837. phiSegments = Math.max( 1, phiSegments );
  26838. // buffers
  26839. const indices = [];
  26840. const vertices = [];
  26841. const normals = [];
  26842. const uvs = [];
  26843. // some helper variables
  26844. let radius = innerRadius;
  26845. const radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  26846. const vertex = new Vector3();
  26847. const uv = new Vector2();
  26848. // generate vertices, normals and uvs
  26849. for ( let j = 0; j <= phiSegments; j ++ ) {
  26850. for ( let i = 0; i <= thetaSegments; i ++ ) {
  26851. // values are generate from the inside of the ring to the outside
  26852. const segment = thetaStart + i / thetaSegments * thetaLength;
  26853. // vertex
  26854. vertex.x = radius * Math.cos( segment );
  26855. vertex.y = radius * Math.sin( segment );
  26856. vertices.push( vertex.x, vertex.y, vertex.z );
  26857. // normal
  26858. normals.push( 0, 0, 1 );
  26859. // uv
  26860. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  26861. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  26862. uvs.push( uv.x, uv.y );
  26863. }
  26864. // increase the radius for next row of vertices
  26865. radius += radiusStep;
  26866. }
  26867. // indices
  26868. for ( let j = 0; j < phiSegments; j ++ ) {
  26869. const thetaSegmentLevel = j * ( thetaSegments + 1 );
  26870. for ( let i = 0; i < thetaSegments; i ++ ) {
  26871. const segment = i + thetaSegmentLevel;
  26872. const a = segment;
  26873. const b = segment + thetaSegments + 1;
  26874. const c = segment + thetaSegments + 2;
  26875. const d = segment + 1;
  26876. // faces
  26877. indices.push( a, b, d );
  26878. indices.push( b, c, d );
  26879. }
  26880. }
  26881. // build geometry
  26882. this.setIndex( indices );
  26883. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26884. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26885. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26886. }
  26887. copy( source ) {
  26888. super.copy( source );
  26889. this.parameters = Object.assign( {}, source.parameters );
  26890. return this;
  26891. }
  26892. /**
  26893. * Factory method for creating an instance of this class from the given
  26894. * JSON object.
  26895. *
  26896. * @param {Object} data - A JSON object representing the serialized geometry.
  26897. * @return {RingGeometry} A new instance.
  26898. */
  26899. static fromJSON( data ) {
  26900. return new RingGeometry( data.innerRadius, data.outerRadius, data.thetaSegments, data.phiSegments, data.thetaStart, data.thetaLength );
  26901. }
  26902. }
  26903. /**
  26904. * Creates an one-sided polygonal geometry from one or more path shapes.
  26905. *
  26906. * ```js
  26907. * const arcShape = new THREE.Shape()
  26908. * .moveTo( 5, 1 )
  26909. * .absarc( 1, 1, 4, 0, Math.PI * 2, false );
  26910. *
  26911. * const geometry = new THREE.ShapeGeometry( arcShape );
  26912. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, side: THREE.DoubleSide } );
  26913. * const mesh = new THREE.Mesh( geometry, material ) ;
  26914. * scene.add( mesh );
  26915. * ```
  26916. *
  26917. * @augments BufferGeometry
  26918. * @demo scenes/geometry-browser.html#ShapeGeometry
  26919. */
  26920. class ShapeGeometry extends BufferGeometry {
  26921. /**
  26922. * Constructs a new shape geometry.
  26923. *
  26924. * @param {Shape|Array<Shape>} [shapes] - A shape or an array of shapes.
  26925. * @param {number} [curveSegments=12] - Number of segments per shape.
  26926. */
  26927. constructor( shapes = new Shape( [ new Vector2( 0, 0.5 ), new Vector2( -0.5, -0.5 ), new Vector2( 0.5, -0.5 ) ] ), curveSegments = 12 ) {
  26928. super();
  26929. this.type = 'ShapeGeometry';
  26930. /**
  26931. * Holds the constructor parameters that have been
  26932. * used to generate the geometry. Any modification
  26933. * after instantiation does not change the geometry.
  26934. *
  26935. * @type {Object}
  26936. */
  26937. this.parameters = {
  26938. shapes: shapes,
  26939. curveSegments: curveSegments
  26940. };
  26941. // buffers
  26942. const indices = [];
  26943. const vertices = [];
  26944. const normals = [];
  26945. const uvs = [];
  26946. // helper variables
  26947. let groupStart = 0;
  26948. let groupCount = 0;
  26949. // allow single and array values for "shapes" parameter
  26950. if ( Array.isArray( shapes ) === false ) {
  26951. addShape( shapes );
  26952. } else {
  26953. for ( let i = 0; i < shapes.length; i ++ ) {
  26954. addShape( shapes[ i ] );
  26955. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  26956. groupStart += groupCount;
  26957. groupCount = 0;
  26958. }
  26959. }
  26960. // build geometry
  26961. this.setIndex( indices );
  26962. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  26963. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  26964. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  26965. // helper functions
  26966. function addShape( shape ) {
  26967. const indexOffset = vertices.length / 3;
  26968. const points = shape.extractPoints( curveSegments );
  26969. let shapeVertices = points.shape;
  26970. const shapeHoles = points.holes;
  26971. // check direction of vertices
  26972. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  26973. shapeVertices = shapeVertices.reverse();
  26974. }
  26975. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26976. const shapeHole = shapeHoles[ i ];
  26977. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  26978. shapeHoles[ i ] = shapeHole.reverse();
  26979. }
  26980. }
  26981. const faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  26982. // join vertices of inner and outer paths to a single array
  26983. for ( let i = 0, l = shapeHoles.length; i < l; i ++ ) {
  26984. const shapeHole = shapeHoles[ i ];
  26985. shapeVertices = shapeVertices.concat( shapeHole );
  26986. }
  26987. // vertices, normals, uvs
  26988. for ( let i = 0, l = shapeVertices.length; i < l; i ++ ) {
  26989. const vertex = shapeVertices[ i ];
  26990. vertices.push( vertex.x, vertex.y, 0 );
  26991. normals.push( 0, 0, 1 );
  26992. uvs.push( vertex.x, vertex.y ); // world uvs
  26993. }
  26994. // indices
  26995. for ( let i = 0, l = faces.length; i < l; i ++ ) {
  26996. const face = faces[ i ];
  26997. const a = face[ 0 ] + indexOffset;
  26998. const b = face[ 1 ] + indexOffset;
  26999. const c = face[ 2 ] + indexOffset;
  27000. indices.push( a, b, c );
  27001. groupCount += 3;
  27002. }
  27003. }
  27004. }
  27005. copy( source ) {
  27006. super.copy( source );
  27007. this.parameters = Object.assign( {}, source.parameters );
  27008. return this;
  27009. }
  27010. toJSON() {
  27011. const data = super.toJSON();
  27012. const shapes = this.parameters.shapes;
  27013. return toJSON( shapes, data );
  27014. }
  27015. /**
  27016. * Factory method for creating an instance of this class from the given
  27017. * JSON object.
  27018. *
  27019. * @param {Object} data - A JSON object representing the serialized geometry.
  27020. * @param {Array<Shape>} shapes - An array of shapes.
  27021. * @return {ShapeGeometry} A new instance.
  27022. */
  27023. static fromJSON( data, shapes ) {
  27024. const geometryShapes = [];
  27025. for ( let j = 0, jl = data.shapes.length; j < jl; j ++ ) {
  27026. const shape = shapes[ data.shapes[ j ] ];
  27027. geometryShapes.push( shape );
  27028. }
  27029. return new ShapeGeometry( geometryShapes, data.curveSegments );
  27030. }
  27031. }
  27032. function toJSON( shapes, data ) {
  27033. data.shapes = [];
  27034. if ( Array.isArray( shapes ) ) {
  27035. for ( let i = 0, l = shapes.length; i < l; i ++ ) {
  27036. const shape = shapes[ i ];
  27037. data.shapes.push( shape.uuid );
  27038. }
  27039. } else {
  27040. data.shapes.push( shapes.uuid );
  27041. }
  27042. return data;
  27043. }
  27044. /**
  27045. * A class for generating a sphere geometry.
  27046. *
  27047. * ```js
  27048. * const geometry = new THREE.SphereGeometry( 15, 32, 16 );
  27049. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27050. * const sphere = new THREE.Mesh( geometry, material );
  27051. * scene.add( sphere );
  27052. * ```
  27053. *
  27054. * @augments BufferGeometry
  27055. * @demo scenes/geometry-browser.html#SphereGeometry
  27056. */
  27057. class SphereGeometry extends BufferGeometry {
  27058. /**
  27059. * Constructs a new sphere geometry.
  27060. *
  27061. * @param {number} [radius=1] - The sphere radius.
  27062. * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`.
  27063. * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`.
  27064. * @param {number} [phiStart=0] - The horizontal starting angle in radians.
  27065. * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size.
  27066. * @param {number} [thetaStart=0] - The vertical starting angle in radians.
  27067. * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size.
  27068. */
  27069. constructor( radius = 1, widthSegments = 32, heightSegments = 16, phiStart = 0, phiLength = Math.PI * 2, thetaStart = 0, thetaLength = Math.PI ) {
  27070. super();
  27071. this.type = 'SphereGeometry';
  27072. /**
  27073. * Holds the constructor parameters that have been
  27074. * used to generate the geometry. Any modification
  27075. * after instantiation does not change the geometry.
  27076. *
  27077. * @type {Object}
  27078. */
  27079. this.parameters = {
  27080. radius: radius,
  27081. widthSegments: widthSegments,
  27082. heightSegments: heightSegments,
  27083. phiStart: phiStart,
  27084. phiLength: phiLength,
  27085. thetaStart: thetaStart,
  27086. thetaLength: thetaLength
  27087. };
  27088. widthSegments = Math.max( 3, Math.floor( widthSegments ) );
  27089. heightSegments = Math.max( 2, Math.floor( heightSegments ) );
  27090. const thetaEnd = Math.min( thetaStart + thetaLength, Math.PI );
  27091. let index = 0;
  27092. const grid = [];
  27093. const vertex = new Vector3();
  27094. const normal = new Vector3();
  27095. // buffers
  27096. const indices = [];
  27097. const vertices = [];
  27098. const normals = [];
  27099. const uvs = [];
  27100. // generate vertices, normals and uvs
  27101. for ( let iy = 0; iy <= heightSegments; iy ++ ) {
  27102. const verticesRow = [];
  27103. const v = iy / heightSegments;
  27104. // special case for the poles
  27105. let uOffset = 0;
  27106. if ( iy === 0 && thetaStart === 0 ) {
  27107. uOffset = 0.5 / widthSegments;
  27108. } else if ( iy === heightSegments && thetaEnd === Math.PI ) {
  27109. uOffset = -0.5 / widthSegments;
  27110. }
  27111. for ( let ix = 0; ix <= widthSegments; ix ++ ) {
  27112. const u = ix / widthSegments;
  27113. // vertex
  27114. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27115. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  27116. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  27117. vertices.push( vertex.x, vertex.y, vertex.z );
  27118. // normal
  27119. normal.copy( vertex ).normalize();
  27120. normals.push( normal.x, normal.y, normal.z );
  27121. // uv
  27122. uvs.push( u + uOffset, 1 - v );
  27123. verticesRow.push( index ++ );
  27124. }
  27125. grid.push( verticesRow );
  27126. }
  27127. // indices
  27128. for ( let iy = 0; iy < heightSegments; iy ++ ) {
  27129. for ( let ix = 0; ix < widthSegments; ix ++ ) {
  27130. const a = grid[ iy ][ ix + 1 ];
  27131. const b = grid[ iy ][ ix ];
  27132. const c = grid[ iy + 1 ][ ix ];
  27133. const d = grid[ iy + 1 ][ ix + 1 ];
  27134. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  27135. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  27136. }
  27137. }
  27138. // build geometry
  27139. this.setIndex( indices );
  27140. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27141. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27142. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27143. }
  27144. copy( source ) {
  27145. super.copy( source );
  27146. this.parameters = Object.assign( {}, source.parameters );
  27147. return this;
  27148. }
  27149. /**
  27150. * Factory method for creating an instance of this class from the given
  27151. * JSON object.
  27152. *
  27153. * @param {Object} data - A JSON object representing the serialized geometry.
  27154. * @return {SphereGeometry} A new instance.
  27155. */
  27156. static fromJSON( data ) {
  27157. return new SphereGeometry( data.radius, data.widthSegments, data.heightSegments, data.phiStart, data.phiLength, data.thetaStart, data.thetaLength );
  27158. }
  27159. }
  27160. /**
  27161. * A geometry class for representing an tetrahedron.
  27162. *
  27163. * ```js
  27164. * const geometry = new THREE.TetrahedronGeometry();
  27165. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27166. * const tetrahedron = new THREE.Mesh( geometry, material );
  27167. * scene.add( tetrahedron );
  27168. * ```
  27169. *
  27170. * @augments PolyhedronGeometry
  27171. * @demo scenes/geometry-browser.html#TetrahedronGeometry
  27172. */
  27173. class TetrahedronGeometry extends PolyhedronGeometry {
  27174. /**
  27175. * Constructs a new tetrahedron geometry.
  27176. *
  27177. * @param {number} [radius=1] - Radius of the tetrahedron.
  27178. * @param {number} [detail=0] - Setting this to a value greater than `0` adds vertices making it no longer a tetrahedron.
  27179. */
  27180. constructor( radius = 1, detail = 0 ) {
  27181. const vertices = [
  27182. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  27183. ];
  27184. const indices = [
  27185. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  27186. ];
  27187. super( vertices, indices, radius, detail );
  27188. this.type = 'TetrahedronGeometry';
  27189. /**
  27190. * Holds the constructor parameters that have been
  27191. * used to generate the geometry. Any modification
  27192. * after instantiation does not change the geometry.
  27193. *
  27194. * @type {Object}
  27195. */
  27196. this.parameters = {
  27197. radius: radius,
  27198. detail: detail
  27199. };
  27200. }
  27201. /**
  27202. * Factory method for creating an instance of this class from the given
  27203. * JSON object.
  27204. *
  27205. * @param {Object} data - A JSON object representing the serialized geometry.
  27206. * @return {TetrahedronGeometry} A new instance.
  27207. */
  27208. static fromJSON( data ) {
  27209. return new TetrahedronGeometry( data.radius, data.detail );
  27210. }
  27211. }
  27212. /**
  27213. * A geometry class for representing an torus.
  27214. *
  27215. * ```js
  27216. * const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
  27217. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27218. * const torus = new THREE.Mesh( geometry, material );
  27219. * scene.add( torus );
  27220. * ```
  27221. *
  27222. * @augments BufferGeometry
  27223. * @demo scenes/geometry-browser.html#TorusGeometry
  27224. */
  27225. class TorusGeometry extends BufferGeometry {
  27226. /**
  27227. * Constructs a new torus geometry.
  27228. *
  27229. * @param {number} [radius=1] - Radius of the torus, from the center of the torus to the center of the tube.
  27230. * @param {number} [tube=0.4] - Radius of the tube. Must be smaller than `radius`.
  27231. * @param {number} [radialSegments=12] - The number of radial segments.
  27232. * @param {number} [tubularSegments=48] - The number of tubular segments.
  27233. * @param {number} [arc=Math.PI*2] - Central angle in radians.
  27234. */
  27235. constructor( radius = 1, tube = 0.4, radialSegments = 12, tubularSegments = 48, arc = Math.PI * 2 ) {
  27236. super();
  27237. this.type = 'TorusGeometry';
  27238. /**
  27239. * Holds the constructor parameters that have been
  27240. * used to generate the geometry. Any modification
  27241. * after instantiation does not change the geometry.
  27242. *
  27243. * @type {Object}
  27244. */
  27245. this.parameters = {
  27246. radius: radius,
  27247. tube: tube,
  27248. radialSegments: radialSegments,
  27249. tubularSegments: tubularSegments,
  27250. arc: arc
  27251. };
  27252. radialSegments = Math.floor( radialSegments );
  27253. tubularSegments = Math.floor( tubularSegments );
  27254. // buffers
  27255. const indices = [];
  27256. const vertices = [];
  27257. const normals = [];
  27258. const uvs = [];
  27259. // helper variables
  27260. const center = new Vector3();
  27261. const vertex = new Vector3();
  27262. const normal = new Vector3();
  27263. // generate vertices, normals and uvs
  27264. for ( let j = 0; j <= radialSegments; j ++ ) {
  27265. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27266. const u = i / tubularSegments * arc;
  27267. const v = j / radialSegments * Math.PI * 2;
  27268. // vertex
  27269. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  27270. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  27271. vertex.z = tube * Math.sin( v );
  27272. vertices.push( vertex.x, vertex.y, vertex.z );
  27273. // normal
  27274. center.x = radius * Math.cos( u );
  27275. center.y = radius * Math.sin( u );
  27276. normal.subVectors( vertex, center ).normalize();
  27277. normals.push( normal.x, normal.y, normal.z );
  27278. // uv
  27279. uvs.push( i / tubularSegments );
  27280. uvs.push( j / radialSegments );
  27281. }
  27282. }
  27283. // generate indices
  27284. for ( let j = 1; j <= radialSegments; j ++ ) {
  27285. for ( let i = 1; i <= tubularSegments; i ++ ) {
  27286. // indices
  27287. const a = ( tubularSegments + 1 ) * j + i - 1;
  27288. const b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  27289. const c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  27290. const d = ( tubularSegments + 1 ) * j + i;
  27291. // faces
  27292. indices.push( a, b, d );
  27293. indices.push( b, c, d );
  27294. }
  27295. }
  27296. // build geometry
  27297. this.setIndex( indices );
  27298. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27299. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27300. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27301. }
  27302. copy( source ) {
  27303. super.copy( source );
  27304. this.parameters = Object.assign( {}, source.parameters );
  27305. return this;
  27306. }
  27307. /**
  27308. * Factory method for creating an instance of this class from the given
  27309. * JSON object.
  27310. *
  27311. * @param {Object} data - A JSON object representing the serialized geometry.
  27312. * @return {TorusGeometry} A new instance.
  27313. */
  27314. static fromJSON( data ) {
  27315. return new TorusGeometry( data.radius, data.tube, data.radialSegments, data.tubularSegments, data.arc );
  27316. }
  27317. }
  27318. /**
  27319. * Creates a torus knot, the particular shape of which is defined by a pair
  27320. * of coprime integers, p and q. If p and q are not coprime, the result will
  27321. * be a torus link.
  27322. *
  27323. * ```js
  27324. * const geometry = new THREE.TorusKnotGeometry( 10, 3, 100, 16 );
  27325. * const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
  27326. * const torusKnot = new THREE.Mesh( geometry, material );
  27327. * scene.add( torusKnot );
  27328. * ```
  27329. *
  27330. * @augments BufferGeometry
  27331. * @demo scenes/geometry-browser.html#TorusKnotGeometry
  27332. */
  27333. class TorusKnotGeometry extends BufferGeometry {
  27334. /**
  27335. * Constructs a new torus knot geometry.
  27336. *
  27337. * @param {number} [radius=1] - Radius of the torus knot.
  27338. * @param {number} [tube=0.4] - Radius of the tube.
  27339. * @param {number} [tubularSegments=64] - The number of tubular segments.
  27340. * @param {number} [radialSegments=8] - The number of radial segments.
  27341. * @param {number} [p=2] - This value determines, how many times the geometry winds around its axis of rotational symmetry.
  27342. * @param {number} [q=3] - This value determines, how many times the geometry winds around a circle in the interior of the torus.
  27343. */
  27344. constructor( radius = 1, tube = 0.4, tubularSegments = 64, radialSegments = 8, p = 2, q = 3 ) {
  27345. super();
  27346. this.type = 'TorusKnotGeometry';
  27347. /**
  27348. * Holds the constructor parameters that have been
  27349. * used to generate the geometry. Any modification
  27350. * after instantiation does not change the geometry.
  27351. *
  27352. * @type {Object}
  27353. */
  27354. this.parameters = {
  27355. radius: radius,
  27356. tube: tube,
  27357. tubularSegments: tubularSegments,
  27358. radialSegments: radialSegments,
  27359. p: p,
  27360. q: q
  27361. };
  27362. tubularSegments = Math.floor( tubularSegments );
  27363. radialSegments = Math.floor( radialSegments );
  27364. // buffers
  27365. const indices = [];
  27366. const vertices = [];
  27367. const normals = [];
  27368. const uvs = [];
  27369. // helper variables
  27370. const vertex = new Vector3();
  27371. const normal = new Vector3();
  27372. const P1 = new Vector3();
  27373. const P2 = new Vector3();
  27374. const B = new Vector3();
  27375. const T = new Vector3();
  27376. const N = new Vector3();
  27377. // generate vertices, normals and uvs
  27378. for ( let i = 0; i <= tubularSegments; ++ i ) {
  27379. // the radian "u" is used to calculate the position on the torus curve of the current tubular segment
  27380. const u = i / tubularSegments * p * Math.PI * 2;
  27381. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  27382. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  27383. calculatePositionOnCurve( u, p, q, radius, P1 );
  27384. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  27385. // calculate orthonormal basis
  27386. T.subVectors( P2, P1 );
  27387. N.addVectors( P2, P1 );
  27388. B.crossVectors( T, N );
  27389. N.crossVectors( B, T );
  27390. // normalize B, N. T can be ignored, we don't use it
  27391. B.normalize();
  27392. N.normalize();
  27393. for ( let j = 0; j <= radialSegments; ++ j ) {
  27394. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  27395. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  27396. const v = j / radialSegments * Math.PI * 2;
  27397. const cx = - tube * Math.cos( v );
  27398. const cy = tube * Math.sin( v );
  27399. // now calculate the final vertex position.
  27400. // first we orient the extrusion with our basis vectors, then we add it to the current position on the curve
  27401. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  27402. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  27403. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  27404. vertices.push( vertex.x, vertex.y, vertex.z );
  27405. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  27406. normal.subVectors( vertex, P1 ).normalize();
  27407. normals.push( normal.x, normal.y, normal.z );
  27408. // uv
  27409. uvs.push( i / tubularSegments );
  27410. uvs.push( j / radialSegments );
  27411. }
  27412. }
  27413. // generate indices
  27414. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27415. for ( let i = 1; i <= radialSegments; i ++ ) {
  27416. // indices
  27417. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27418. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27419. const c = ( radialSegments + 1 ) * j + i;
  27420. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27421. // faces
  27422. indices.push( a, b, d );
  27423. indices.push( b, c, d );
  27424. }
  27425. }
  27426. // build geometry
  27427. this.setIndex( indices );
  27428. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27429. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27430. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27431. // this function calculates the current position on the torus curve
  27432. function calculatePositionOnCurve( u, p, q, radius, position ) {
  27433. const cu = Math.cos( u );
  27434. const su = Math.sin( u );
  27435. const quOverP = q / p * u;
  27436. const cs = Math.cos( quOverP );
  27437. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  27438. position.y = radius * ( 2 + cs ) * su * 0.5;
  27439. position.z = radius * Math.sin( quOverP ) * 0.5;
  27440. }
  27441. }
  27442. copy( source ) {
  27443. super.copy( source );
  27444. this.parameters = Object.assign( {}, source.parameters );
  27445. return this;
  27446. }
  27447. /**
  27448. * Factory method for creating an instance of this class from the given
  27449. * JSON object.
  27450. *
  27451. * @param {Object} data - A JSON object representing the serialized geometry.
  27452. * @return {TorusKnotGeometry} A new instance.
  27453. */
  27454. static fromJSON( data ) {
  27455. return new TorusKnotGeometry( data.radius, data.tube, data.tubularSegments, data.radialSegments, data.p, data.q );
  27456. }
  27457. }
  27458. /**
  27459. * Creates a tube that extrudes along a 3D curve.
  27460. *
  27461. * ```js
  27462. * class CustomSinCurve extends THREE.Curve {
  27463. *
  27464. * getPoint( t, optionalTarget = new THREE.Vector3() ) {
  27465. *
  27466. * const tx = t * 3 - 1.5;
  27467. * const ty = Math.sin( 2 * Math.PI * t );
  27468. * const tz = 0;
  27469. *
  27470. * return optionalTarget.set( tx, ty, tz );
  27471. * }
  27472. *
  27473. * }
  27474. *
  27475. * const path = new CustomSinCurve( 10 );
  27476. * const geometry = new THREE.TubeGeometry( path, 20, 2, 8, false );
  27477. * const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  27478. * const mesh = new THREE.Mesh( geometry, material );
  27479. * scene.add( mesh );
  27480. * ```
  27481. *
  27482. * @augments BufferGeometry
  27483. * @demo scenes/geometry-browser.html#TubeGeometry
  27484. */
  27485. class TubeGeometry extends BufferGeometry {
  27486. /**
  27487. * Constructs a new tube geometry.
  27488. *
  27489. * @param {Curve} [path=QuadraticBezierCurve3] - A 3D curve defining the path of the tube.
  27490. * @param {number} [tubularSegments=64] - The number of segments that make up the tube.
  27491. * @param {number} [radius=1] -The radius of the tube.
  27492. * @param {number} [radialSegments=8] - The number of segments that make up the cross-section.
  27493. * @param {boolean} [closed=false] - Whether the tube is closed or not.
  27494. */
  27495. 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 ) {
  27496. super();
  27497. this.type = 'TubeGeometry';
  27498. /**
  27499. * Holds the constructor parameters that have been
  27500. * used to generate the geometry. Any modification
  27501. * after instantiation does not change the geometry.
  27502. *
  27503. * @type {Object}
  27504. */
  27505. this.parameters = {
  27506. path: path,
  27507. tubularSegments: tubularSegments,
  27508. radius: radius,
  27509. radialSegments: radialSegments,
  27510. closed: closed
  27511. };
  27512. const frames = path.computeFrenetFrames( tubularSegments, closed );
  27513. // expose internals
  27514. this.tangents = frames.tangents;
  27515. this.normals = frames.normals;
  27516. this.binormals = frames.binormals;
  27517. // helper variables
  27518. const vertex = new Vector3();
  27519. const normal = new Vector3();
  27520. const uv = new Vector2();
  27521. let P = new Vector3();
  27522. // buffer
  27523. const vertices = [];
  27524. const normals = [];
  27525. const uvs = [];
  27526. const indices = [];
  27527. // create buffer data
  27528. generateBufferData();
  27529. // build geometry
  27530. this.setIndex( indices );
  27531. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27532. this.setAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  27533. this.setAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  27534. // functions
  27535. function generateBufferData() {
  27536. for ( let i = 0; i < tubularSegments; i ++ ) {
  27537. generateSegment( i );
  27538. }
  27539. // if the geometry is not closed, generate the last row of vertices and normals
  27540. // at the regular position on the given path
  27541. //
  27542. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  27543. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  27544. // uvs are generated in a separate function.
  27545. // this makes it easy compute correct values for closed geometries
  27546. generateUVs();
  27547. // finally create faces
  27548. generateIndices();
  27549. }
  27550. function generateSegment( i ) {
  27551. // we use getPointAt to sample evenly distributed points from the given path
  27552. P = path.getPointAt( i / tubularSegments, P );
  27553. // retrieve corresponding normal and binormal
  27554. const N = frames.normals[ i ];
  27555. const B = frames.binormals[ i ];
  27556. // generate normals and vertices for the current segment
  27557. for ( let j = 0; j <= radialSegments; j ++ ) {
  27558. const v = j / radialSegments * Math.PI * 2;
  27559. const sin = Math.sin( v );
  27560. const cos = - Math.cos( v );
  27561. // normal
  27562. normal.x = ( cos * N.x + sin * B.x );
  27563. normal.y = ( cos * N.y + sin * B.y );
  27564. normal.z = ( cos * N.z + sin * B.z );
  27565. normal.normalize();
  27566. normals.push( normal.x, normal.y, normal.z );
  27567. // vertex
  27568. vertex.x = P.x + radius * normal.x;
  27569. vertex.y = P.y + radius * normal.y;
  27570. vertex.z = P.z + radius * normal.z;
  27571. vertices.push( vertex.x, vertex.y, vertex.z );
  27572. }
  27573. }
  27574. function generateIndices() {
  27575. for ( let j = 1; j <= tubularSegments; j ++ ) {
  27576. for ( let i = 1; i <= radialSegments; i ++ ) {
  27577. const a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  27578. const b = ( radialSegments + 1 ) * j + ( i - 1 );
  27579. const c = ( radialSegments + 1 ) * j + i;
  27580. const d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  27581. // faces
  27582. indices.push( a, b, d );
  27583. indices.push( b, c, d );
  27584. }
  27585. }
  27586. }
  27587. function generateUVs() {
  27588. for ( let i = 0; i <= tubularSegments; i ++ ) {
  27589. for ( let j = 0; j <= radialSegments; j ++ ) {
  27590. uv.x = i / tubularSegments;
  27591. uv.y = j / radialSegments;
  27592. uvs.push( uv.x, uv.y );
  27593. }
  27594. }
  27595. }
  27596. }
  27597. copy( source ) {
  27598. super.copy( source );
  27599. this.parameters = Object.assign( {}, source.parameters );
  27600. return this;
  27601. }
  27602. toJSON() {
  27603. const data = super.toJSON();
  27604. data.path = this.parameters.path.toJSON();
  27605. return data;
  27606. }
  27607. /**
  27608. * Factory method for creating an instance of this class from the given
  27609. * JSON object.
  27610. *
  27611. * @param {Object} data - A JSON object representing the serialized geometry.
  27612. * @return {TubeGeometry} A new instance.
  27613. */
  27614. static fromJSON( data ) {
  27615. // This only works for built-in curves (e.g. CatmullRomCurve3).
  27616. // User defined curves or instances of CurvePath will not be deserialized.
  27617. return new TubeGeometry(
  27618. new Curves[ data.path.type ]().fromJSON( data.path ),
  27619. data.tubularSegments,
  27620. data.radius,
  27621. data.radialSegments,
  27622. data.closed
  27623. );
  27624. }
  27625. }
  27626. /**
  27627. * Can be used as a helper object to visualize a geometry as a wireframe.
  27628. *
  27629. * ```js
  27630. * const geometry = new THREE.SphereGeometry();
  27631. *
  27632. * const wireframe = new THREE.WireframeGeometry( geometry );
  27633. *
  27634. * const line = new THREE.LineSegments( wireframe );
  27635. * line.material.depthWrite = false;
  27636. * line.material.opacity = 0.25;
  27637. * line.material.transparent = true;
  27638. *
  27639. * scene.add( line );
  27640. * ```
  27641. *
  27642. * Note: It is not yet possible to serialize/deserialize instances of this class.
  27643. *
  27644. * @augments BufferGeometry
  27645. */
  27646. class WireframeGeometry extends BufferGeometry {
  27647. /**
  27648. * Constructs a new wireframe geometry.
  27649. *
  27650. * @param {?BufferGeometry} [geometry=null] - The geometry.
  27651. */
  27652. constructor( geometry = null ) {
  27653. super();
  27654. this.type = 'WireframeGeometry';
  27655. /**
  27656. * Holds the constructor parameters that have been
  27657. * used to generate the geometry. Any modification
  27658. * after instantiation does not change the geometry.
  27659. *
  27660. * @type {Object}
  27661. */
  27662. this.parameters = {
  27663. geometry: geometry
  27664. };
  27665. if ( geometry !== null ) {
  27666. // buffer
  27667. const vertices = [];
  27668. const edges = new Set();
  27669. // helper variables
  27670. const start = new Vector3();
  27671. const end = new Vector3();
  27672. if ( geometry.index !== null ) {
  27673. // indexed BufferGeometry
  27674. const position = geometry.attributes.position;
  27675. const indices = geometry.index;
  27676. let groups = geometry.groups;
  27677. if ( groups.length === 0 ) {
  27678. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  27679. }
  27680. // create a data structure that contains all edges without duplicates
  27681. for ( let o = 0, ol = groups.length; o < ol; ++ o ) {
  27682. const group = groups[ o ];
  27683. const groupStart = group.start;
  27684. const groupCount = group.count;
  27685. for ( let i = groupStart, l = ( groupStart + groupCount ); i < l; i += 3 ) {
  27686. for ( let j = 0; j < 3; j ++ ) {
  27687. const index1 = indices.getX( i + j );
  27688. const index2 = indices.getX( i + ( j + 1 ) % 3 );
  27689. start.fromBufferAttribute( position, index1 );
  27690. end.fromBufferAttribute( position, index2 );
  27691. if ( isUniqueEdge( start, end, edges ) === true ) {
  27692. vertices.push( start.x, start.y, start.z );
  27693. vertices.push( end.x, end.y, end.z );
  27694. }
  27695. }
  27696. }
  27697. }
  27698. } else {
  27699. // non-indexed BufferGeometry
  27700. const position = geometry.attributes.position;
  27701. for ( let i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  27702. for ( let j = 0; j < 3; j ++ ) {
  27703. // three edges per triangle, an edge is represented as (index1, index2)
  27704. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  27705. const index1 = 3 * i + j;
  27706. const index2 = 3 * i + ( ( j + 1 ) % 3 );
  27707. start.fromBufferAttribute( position, index1 );
  27708. end.fromBufferAttribute( position, index2 );
  27709. if ( isUniqueEdge( start, end, edges ) === true ) {
  27710. vertices.push( start.x, start.y, start.z );
  27711. vertices.push( end.x, end.y, end.z );
  27712. }
  27713. }
  27714. }
  27715. }
  27716. // build geometry
  27717. this.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  27718. }
  27719. }
  27720. copy( source ) {
  27721. super.copy( source );
  27722. this.parameters = Object.assign( {}, source.parameters );
  27723. return this;
  27724. }
  27725. }
  27726. function isUniqueEdge( start, end, edges ) {
  27727. const hash1 = `${start.x},${start.y},${start.z}-${end.x},${end.y},${end.z}`;
  27728. const hash2 = `${end.x},${end.y},${end.z}-${start.x},${start.y},${start.z}`; // coincident edge
  27729. if ( edges.has( hash1 ) === true || edges.has( hash2 ) === true ) {
  27730. return false;
  27731. } else {
  27732. edges.add( hash1 );
  27733. edges.add( hash2 );
  27734. return true;
  27735. }
  27736. }
  27737. var Geometries = /*#__PURE__*/Object.freeze({
  27738. __proto__: null,
  27739. BoxGeometry: BoxGeometry,
  27740. CapsuleGeometry: CapsuleGeometry,
  27741. CircleGeometry: CircleGeometry,
  27742. ConeGeometry: ConeGeometry,
  27743. CylinderGeometry: CylinderGeometry,
  27744. DodecahedronGeometry: DodecahedronGeometry,
  27745. EdgesGeometry: EdgesGeometry,
  27746. ExtrudeGeometry: ExtrudeGeometry,
  27747. IcosahedronGeometry: IcosahedronGeometry,
  27748. LatheGeometry: LatheGeometry,
  27749. OctahedronGeometry: OctahedronGeometry,
  27750. PlaneGeometry: PlaneGeometry,
  27751. PolyhedronGeometry: PolyhedronGeometry,
  27752. RingGeometry: RingGeometry,
  27753. ShapeGeometry: ShapeGeometry,
  27754. SphereGeometry: SphereGeometry,
  27755. TetrahedronGeometry: TetrahedronGeometry,
  27756. TorusGeometry: TorusGeometry,
  27757. TorusKnotGeometry: TorusKnotGeometry,
  27758. TubeGeometry: TubeGeometry,
  27759. WireframeGeometry: WireframeGeometry
  27760. });
  27761. /**
  27762. * This material can receive shadows, but otherwise is completely transparent.
  27763. *
  27764. * ```js
  27765. * const geometry = new THREE.PlaneGeometry( 2000, 2000 );
  27766. * geometry.rotateX( - Math.PI / 2 );
  27767. *
  27768. * const material = new THREE.ShadowMaterial();
  27769. * material.opacity = 0.2;
  27770. *
  27771. * const plane = new THREE.Mesh( geometry, material );
  27772. * plane.position.y = -200;
  27773. * plane.receiveShadow = true;
  27774. * scene.add( plane );
  27775. * ```
  27776. *
  27777. * @augments Material
  27778. */
  27779. class ShadowMaterial extends Material {
  27780. /**
  27781. * Constructs a new shadow material.
  27782. *
  27783. * @param {Object} [parameters] - An object with one or more properties
  27784. * defining the material's appearance. Any property of the material
  27785. * (including any property from inherited materials) can be passed
  27786. * in here. Color values can be passed any type of value accepted
  27787. * by {@link Color#set}.
  27788. */
  27789. constructor( parameters ) {
  27790. super();
  27791. /**
  27792. * This flag can be used for type testing.
  27793. *
  27794. * @type {boolean}
  27795. * @readonly
  27796. * @default true
  27797. */
  27798. this.isShadowMaterial = true;
  27799. this.type = 'ShadowMaterial';
  27800. /**
  27801. * Color of the material.
  27802. *
  27803. * @type {Color}
  27804. * @default (0,0,0)
  27805. */
  27806. this.color = new Color( 0x000000 );
  27807. /**
  27808. * Overwritten since shadow materials are transparent
  27809. * by default.
  27810. *
  27811. * @type {boolean}
  27812. * @default true
  27813. */
  27814. this.transparent = true;
  27815. /**
  27816. * Whether the material is affected by fog or not.
  27817. *
  27818. * @type {boolean}
  27819. * @default true
  27820. */
  27821. this.fog = true;
  27822. this.setValues( parameters );
  27823. }
  27824. copy( source ) {
  27825. super.copy( source );
  27826. this.color.copy( source.color );
  27827. this.fog = source.fog;
  27828. return this;
  27829. }
  27830. }
  27831. /**
  27832. * This class works just like {@link ShaderMaterial}, except that definitions
  27833. * of built-in uniforms and attributes are not automatically prepended to the
  27834. * GLSL shader code.
  27835. *
  27836. * `RawShaderMaterial` can only be used with {@link WebGLRenderer}.
  27837. *
  27838. * @augments ShaderMaterial
  27839. */
  27840. class RawShaderMaterial extends ShaderMaterial {
  27841. /**
  27842. * Constructs a new raw shader material.
  27843. *
  27844. * @param {Object} [parameters] - An object with one or more properties
  27845. * defining the material's appearance. Any property of the material
  27846. * (including any property from inherited materials) can be passed
  27847. * in here. Color values can be passed any type of value accepted
  27848. * by {@link Color#set}.
  27849. */
  27850. constructor( parameters ) {
  27851. super( parameters );
  27852. /**
  27853. * This flag can be used for type testing.
  27854. *
  27855. * @type {boolean}
  27856. * @readonly
  27857. * @default true
  27858. */
  27859. this.isRawShaderMaterial = true;
  27860. this.type = 'RawShaderMaterial';
  27861. }
  27862. }
  27863. /**
  27864. * A standard physically based material, using Metallic-Roughness workflow.
  27865. *
  27866. * Physically based rendering (PBR) has recently become the standard in many
  27867. * 3D applications, such as [Unity](https://blogs.unity3d.com/2014/10/29/physically-based-shading-in-unity-5-a-primer/),
  27868. * [Unreal](https://docs.unrealengine.com/latest/INT/Engine/Rendering/Materials/PhysicallyBased/) and
  27869. * [3D Studio Max](http://area.autodesk.com/blogs/the-3ds-max-blog/what039s-new-for-rendering-in-3ds-max-2017).
  27870. *
  27871. * This approach differs from older approaches in that instead of using
  27872. * approximations for the way in which light interacts with a surface, a
  27873. * physically correct model is used. The idea is that, instead of tweaking
  27874. * materials to look good under specific lighting, a material can be created
  27875. * that will react 'correctly' under all lighting scenarios.
  27876. *
  27877. * In practice this gives a more accurate and realistic looking result than
  27878. * the {@link MeshLambertMaterial} or {@link MeshPhongMaterial}, at the cost of
  27879. * being somewhat more computationally expensive. `MeshStandardMaterial` uses per-fragment
  27880. * shading.
  27881. *
  27882. * Note that for best results you should always specify an environment map when using this material.
  27883. *
  27884. * For a non-technical introduction to the concept of PBR and how to set up a
  27885. * PBR material, check out these articles by the people at [marmoset](https://www.marmoset.co):
  27886. *
  27887. * - [Basic Theory of Physically Based Rendering](https://www.marmoset.co/posts/basic-theory-of-physically-based-rendering/)
  27888. * - [Physically Based Rendering and You Can Too](https://www.marmoset.co/posts/physically-based-rendering-and-you-can-too/)
  27889. *
  27890. * Technical details of the approach used in three.js (and most other PBR systems) can be found is this
  27891. * [paper from Disney](https://media.disneyanimation.com/uploads/production/publication_asset/48/asset/s2012_pbs_disney_brdf_notes_v3.pdf)
  27892. * (pdf), by Brent Burley.
  27893. *
  27894. * @augments Material
  27895. * @demo scenes/material-browser.html#MeshStandardMaterial
  27896. */
  27897. class MeshStandardMaterial extends Material {
  27898. /**
  27899. * Constructs a new mesh standard material.
  27900. *
  27901. * @param {Object} [parameters] - An object with one or more properties
  27902. * defining the material's appearance. Any property of the material
  27903. * (including any property from inherited materials) can be passed
  27904. * in here. Color values can be passed any type of value accepted
  27905. * by {@link Color#set}.
  27906. */
  27907. constructor( parameters ) {
  27908. super();
  27909. /**
  27910. * This flag can be used for type testing.
  27911. *
  27912. * @type {boolean}
  27913. * @readonly
  27914. * @default true
  27915. */
  27916. this.isMeshStandardMaterial = true;
  27917. this.type = 'MeshStandardMaterial';
  27918. this.defines = { 'STANDARD': '' };
  27919. /**
  27920. * Color of the material.
  27921. *
  27922. * @type {Color}
  27923. * @default (1,1,1)
  27924. */
  27925. this.color = new Color( 0xffffff ); // diffuse
  27926. /**
  27927. * How rough the material appears. `0.0` means a smooth mirror reflection, `1.0`
  27928. * means fully diffuse. If `roughnessMap` is also provided,
  27929. * both values are multiplied.
  27930. *
  27931. * @type {number}
  27932. * @default 1
  27933. */
  27934. this.roughness = 1.0;
  27935. /**
  27936. * How much the material is like a metal. Non-metallic materials such as wood
  27937. * or stone use `0.0`, metallic use `1.0`, with nothing (usually) in between.
  27938. * A value between `0.0` and `1.0` could be used for a rusty metal look.
  27939. * If `metalnessMap` is also provided, both values are multiplied.
  27940. *
  27941. * @type {number}
  27942. * @default 0
  27943. */
  27944. this.metalness = 0.0;
  27945. /**
  27946. * The color map. May optionally include an alpha channel, typically combined
  27947. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  27948. * color is modulated by the diffuse `color`.
  27949. *
  27950. * @type {?Texture}
  27951. * @default null
  27952. */
  27953. this.map = null;
  27954. /**
  27955. * The light map. Requires a second set of UVs.
  27956. *
  27957. * @type {?Texture}
  27958. * @default null
  27959. */
  27960. this.lightMap = null;
  27961. /**
  27962. * Intensity of the baked light.
  27963. *
  27964. * @type {number}
  27965. * @default 1
  27966. */
  27967. this.lightMapIntensity = 1.0;
  27968. /**
  27969. * The red channel of this texture is used as the ambient occlusion map.
  27970. * Requires a second set of UVs.
  27971. *
  27972. * @type {?Texture}
  27973. * @default null
  27974. */
  27975. this.aoMap = null;
  27976. /**
  27977. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  27978. * disables ambient occlusion. Where intensity is `1` and the AO map's
  27979. * red channel is also `1`, ambient light is fully occluded on a surface.
  27980. *
  27981. * @type {number}
  27982. * @default 1
  27983. */
  27984. this.aoMapIntensity = 1.0;
  27985. /**
  27986. * Emissive (light) color of the material, essentially a solid color
  27987. * unaffected by other lighting.
  27988. *
  27989. * @type {Color}
  27990. * @default (0,0,0)
  27991. */
  27992. this.emissive = new Color( 0x000000 );
  27993. /**
  27994. * Intensity of the emissive light. Modulates the emissive color.
  27995. *
  27996. * @type {number}
  27997. * @default 1
  27998. */
  27999. this.emissiveIntensity = 1.0;
  28000. /**
  28001. * Set emissive (glow) map. The emissive map color is modulated by the
  28002. * emissive color and the emissive intensity. If you have an emissive map,
  28003. * be sure to set the emissive color to something other than black.
  28004. *
  28005. * @type {?Texture}
  28006. * @default null
  28007. */
  28008. this.emissiveMap = null;
  28009. /**
  28010. * The texture to create a bump map. The black and white values map to the
  28011. * perceived depth in relation to the lights. Bump doesn't actually affect
  28012. * the geometry of the object, only the lighting. If a normal map is defined
  28013. * this will be ignored.
  28014. *
  28015. * @type {?Texture}
  28016. * @default null
  28017. */
  28018. this.bumpMap = null;
  28019. /**
  28020. * How much the bump map affects the material. Typical range is `[0,1]`.
  28021. *
  28022. * @type {number}
  28023. * @default 1
  28024. */
  28025. this.bumpScale = 1;
  28026. /**
  28027. * The texture to create a normal map. The RGB values affect the surface
  28028. * normal for each pixel fragment and change the way the color is lit. Normal
  28029. * maps do not change the actual shape of the surface, only the lighting. In
  28030. * case the material has a normal map authored using the left handed
  28031. * convention, the `y` component of `normalScale` should be negated to compensate
  28032. * for the different handedness.
  28033. *
  28034. * @type {?Texture}
  28035. * @default null
  28036. */
  28037. this.normalMap = null;
  28038. /**
  28039. * The type of normal map.
  28040. *
  28041. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28042. * @default TangentSpaceNormalMap
  28043. */
  28044. this.normalMapType = TangentSpaceNormalMap;
  28045. /**
  28046. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28047. *
  28048. * @type {Vector2}
  28049. * @default (1,1)
  28050. */
  28051. this.normalScale = new Vector2( 1, 1 );
  28052. /**
  28053. * The displacement map affects the position of the mesh's vertices. Unlike
  28054. * other maps which only affect the light and shade of the material the
  28055. * displaced vertices can cast shadows, block other objects, and otherwise
  28056. * act as real geometry. The displacement texture is an image where the value
  28057. * of each pixel (white being the highest) is mapped against, and
  28058. * repositions, the vertices of the mesh.
  28059. *
  28060. * @type {?Texture}
  28061. * @default null
  28062. */
  28063. this.displacementMap = null;
  28064. /**
  28065. * How much the displacement map affects the mesh (where black is no
  28066. * displacement, and white is maximum displacement). Without a displacement
  28067. * map set, this value is not applied.
  28068. *
  28069. * @type {number}
  28070. * @default 0
  28071. */
  28072. this.displacementScale = 1;
  28073. /**
  28074. * The offset of the displacement map's values on the mesh's vertices.
  28075. * The bias is added to the scaled sample of the displacement map.
  28076. * Without a displacement map set, this value is not applied.
  28077. *
  28078. * @type {number}
  28079. * @default 0
  28080. */
  28081. this.displacementBias = 0;
  28082. /**
  28083. * The green channel of this texture is used to alter the roughness of the
  28084. * material.
  28085. *
  28086. * @type {?Texture}
  28087. * @default null
  28088. */
  28089. this.roughnessMap = null;
  28090. /**
  28091. * The blue channel of this texture is used to alter the metalness of the
  28092. * material.
  28093. *
  28094. * @type {?Texture}
  28095. * @default null
  28096. */
  28097. this.metalnessMap = null;
  28098. /**
  28099. * The alpha map is a grayscale texture that controls the opacity across the
  28100. * surface (black: fully transparent; white: fully opaque).
  28101. *
  28102. * Only the color of the texture is used, ignoring the alpha channel if one
  28103. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28104. * when sampling this texture due to the extra bit of precision provided for
  28105. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28106. * luminance/alpha textures will also still work as expected.
  28107. *
  28108. * @type {?Texture}
  28109. * @default null
  28110. */
  28111. this.alphaMap = null;
  28112. /**
  28113. * The environment map. To ensure a physically correct rendering, environment maps
  28114. * are internally pre-processed with {@link PMREMGenerator}.
  28115. *
  28116. * @type {?Texture}
  28117. * @default null
  28118. */
  28119. this.envMap = null;
  28120. /**
  28121. * The rotation of the environment map in radians.
  28122. *
  28123. * @type {Euler}
  28124. * @default (0,0,0)
  28125. */
  28126. this.envMapRotation = new Euler();
  28127. /**
  28128. * Scales the effect of the environment map by multiplying its color.
  28129. *
  28130. * @type {number}
  28131. * @default 1
  28132. */
  28133. this.envMapIntensity = 1.0;
  28134. /**
  28135. * Renders the geometry as a wireframe.
  28136. *
  28137. * @type {boolean}
  28138. * @default false
  28139. */
  28140. this.wireframe = false;
  28141. /**
  28142. * Controls the thickness of the wireframe.
  28143. *
  28144. * Can only be used with {@link SVGRenderer}.
  28145. *
  28146. * @type {number}
  28147. * @default 1
  28148. */
  28149. this.wireframeLinewidth = 1;
  28150. /**
  28151. * Defines appearance of wireframe ends.
  28152. *
  28153. * Can only be used with {@link SVGRenderer}.
  28154. *
  28155. * @type {('round'|'bevel'|'miter')}
  28156. * @default 'round'
  28157. */
  28158. this.wireframeLinecap = 'round';
  28159. /**
  28160. * Defines appearance of wireframe joints.
  28161. *
  28162. * Can only be used with {@link SVGRenderer}.
  28163. *
  28164. * @type {('round'|'bevel'|'miter')}
  28165. * @default 'round'
  28166. */
  28167. this.wireframeLinejoin = 'round';
  28168. /**
  28169. * Whether the material is rendered with flat shading or not.
  28170. *
  28171. * @type {boolean}
  28172. * @default false
  28173. */
  28174. this.flatShading = false;
  28175. /**
  28176. * Whether the material is affected by fog or not.
  28177. *
  28178. * @type {boolean}
  28179. * @default true
  28180. */
  28181. this.fog = true;
  28182. this.setValues( parameters );
  28183. }
  28184. copy( source ) {
  28185. super.copy( source );
  28186. this.defines = { 'STANDARD': '' };
  28187. this.color.copy( source.color );
  28188. this.roughness = source.roughness;
  28189. this.metalness = source.metalness;
  28190. this.map = source.map;
  28191. this.lightMap = source.lightMap;
  28192. this.lightMapIntensity = source.lightMapIntensity;
  28193. this.aoMap = source.aoMap;
  28194. this.aoMapIntensity = source.aoMapIntensity;
  28195. this.emissive.copy( source.emissive );
  28196. this.emissiveMap = source.emissiveMap;
  28197. this.emissiveIntensity = source.emissiveIntensity;
  28198. this.bumpMap = source.bumpMap;
  28199. this.bumpScale = source.bumpScale;
  28200. this.normalMap = source.normalMap;
  28201. this.normalMapType = source.normalMapType;
  28202. this.normalScale.copy( source.normalScale );
  28203. this.displacementMap = source.displacementMap;
  28204. this.displacementScale = source.displacementScale;
  28205. this.displacementBias = source.displacementBias;
  28206. this.roughnessMap = source.roughnessMap;
  28207. this.metalnessMap = source.metalnessMap;
  28208. this.alphaMap = source.alphaMap;
  28209. this.envMap = source.envMap;
  28210. this.envMapRotation.copy( source.envMapRotation );
  28211. this.envMapIntensity = source.envMapIntensity;
  28212. this.wireframe = source.wireframe;
  28213. this.wireframeLinewidth = source.wireframeLinewidth;
  28214. this.wireframeLinecap = source.wireframeLinecap;
  28215. this.wireframeLinejoin = source.wireframeLinejoin;
  28216. this.flatShading = source.flatShading;
  28217. this.fog = source.fog;
  28218. return this;
  28219. }
  28220. }
  28221. /**
  28222. * An extension of the {@link MeshStandardMaterial}, providing more advanced
  28223. * physically-based rendering properties:
  28224. *
  28225. * - Anisotropy: Ability to represent the anisotropic property of materials
  28226. * as observable with brushed metals.
  28227. * - Clearcoat: Some materials — like car paints, carbon fiber, and wet surfaces — require
  28228. * a clear, reflective layer on top of another layer that may be irregular or rough.
  28229. * Clearcoat approximates this effect, without the need for a separate transparent surface.
  28230. * - Iridescence: Allows to render the effect where hue varies depending on the viewing
  28231. * angle and illumination angle. This can be seen on soap bubbles, oil films, or on the
  28232. * wings of many insects.
  28233. * - Physically-based transparency: One limitation of {@link Material#opacity} is that highly
  28234. * transparent materials are less reflective. Physically-based transmission provides a more
  28235. * realistic option for thin, transparent surfaces like glass.
  28236. * - Advanced reflectivity: More flexible reflectivity for non-metallic materials.
  28237. * - Sheen: Can be used for representing cloth and fabric materials.
  28238. *
  28239. * As a result of these complex shading features, `MeshPhysicalMaterial` has a
  28240. * higher performance cost, per pixel, than other three.js materials. Most
  28241. * effects are disabled by default, and add cost as they are enabled. For
  28242. * best results, always specify an environment map when using this material.
  28243. *
  28244. * @augments MeshStandardMaterial
  28245. * @demo scenes/material-browser.html#MeshPhysicalMaterial
  28246. */
  28247. class MeshPhysicalMaterial extends MeshStandardMaterial {
  28248. /**
  28249. * Constructs a new mesh physical material.
  28250. *
  28251. * @param {Object} [parameters] - An object with one or more properties
  28252. * defining the material's appearance. Any property of the material
  28253. * (including any property from inherited materials) can be passed
  28254. * in here. Color values can be passed any type of value accepted
  28255. * by {@link Color#set}.
  28256. */
  28257. constructor( parameters ) {
  28258. super();
  28259. /**
  28260. * This flag can be used for type testing.
  28261. *
  28262. * @type {boolean}
  28263. * @readonly
  28264. * @default true
  28265. */
  28266. this.isMeshPhysicalMaterial = true;
  28267. this.defines = {
  28268. 'STANDARD': '',
  28269. 'PHYSICAL': ''
  28270. };
  28271. this.type = 'MeshPhysicalMaterial';
  28272. /**
  28273. * The rotation of the anisotropy in tangent, bitangent space, measured in radians
  28274. * counter-clockwise from the tangent. When `anisotropyMap` is present, this
  28275. * property provides additional rotation to the vectors in the texture.
  28276. *
  28277. * @type {number}
  28278. * @default 1
  28279. */
  28280. this.anisotropyRotation = 0;
  28281. /**
  28282. * Red and green channels represent the anisotropy direction in `[-1, 1]` tangent,
  28283. * bitangent space, to be rotated by `anisotropyRotation`. The blue channel
  28284. * contains strength as `[0, 1]` to be multiplied by `anisotropy`.
  28285. *
  28286. * @type {?Texture}
  28287. * @default null
  28288. */
  28289. this.anisotropyMap = null;
  28290. /**
  28291. * The red channel of this texture is multiplied against `clearcoat`,
  28292. * for per-pixel control over a coating's intensity.
  28293. *
  28294. * @type {?Texture}
  28295. * @default null
  28296. */
  28297. this.clearcoatMap = null;
  28298. /**
  28299. * Roughness of the clear coat layer, from `0.0` to `1.0`.
  28300. *
  28301. * @type {number}
  28302. * @default 0
  28303. */
  28304. this.clearcoatRoughness = 0.0;
  28305. /**
  28306. * The green channel of this texture is multiplied against
  28307. * `clearcoatRoughness`, for per-pixel control over a coating's roughness.
  28308. *
  28309. * @type {?Texture}
  28310. * @default null
  28311. */
  28312. this.clearcoatRoughnessMap = null;
  28313. /**
  28314. * How much `clearcoatNormalMap` affects the clear coat layer, from
  28315. * `(0,0)` to `(1,1)`.
  28316. *
  28317. * @type {Vector2}
  28318. * @default (1,1)
  28319. */
  28320. this.clearcoatNormalScale = new Vector2( 1, 1 );
  28321. /**
  28322. * Can be used to enable independent normals for the clear coat layer.
  28323. *
  28324. * @type {?Texture}
  28325. * @default null
  28326. */
  28327. this.clearcoatNormalMap = null;
  28328. /**
  28329. * Index-of-refraction for non-metallic materials, from `1.0` to `2.333`.
  28330. *
  28331. * @type {number}
  28332. * @default 1.5
  28333. */
  28334. this.ior = 1.5;
  28335. /**
  28336. * Degree of reflectivity, from `0.0` to `1.0`. Default is `0.5`, which
  28337. * corresponds to an index-of-refraction of `1.5`.
  28338. *
  28339. * This models the reflectivity of non-metallic materials. It has no effect
  28340. * when `metalness` is `1.0`
  28341. *
  28342. * @name MeshPhysicalMaterial#reflectivity
  28343. * @type {number}
  28344. * @default 0.5
  28345. */
  28346. Object.defineProperty( this, 'reflectivity', {
  28347. get: function () {
  28348. return ( clamp( 2.5 * ( this.ior - 1 ) / ( this.ior + 1 ), 0, 1 ) );
  28349. },
  28350. set: function ( reflectivity ) {
  28351. this.ior = ( 1 + 0.4 * reflectivity ) / ( 1 - 0.4 * reflectivity );
  28352. }
  28353. } );
  28354. /**
  28355. * The red channel of this texture is multiplied against `iridescence`, for per-pixel
  28356. * control over iridescence.
  28357. *
  28358. * @type {?Texture}
  28359. * @default null
  28360. */
  28361. this.iridescenceMap = null;
  28362. /**
  28363. * Strength of the iridescence RGB color shift effect, represented by an index-of-refraction.
  28364. * Between `1.0` to `2.333`.
  28365. *
  28366. * @type {number}
  28367. * @default 1.3
  28368. */
  28369. this.iridescenceIOR = 1.3;
  28370. /**
  28371. *Array of exactly 2 elements, specifying minimum and maximum thickness of the iridescence layer.
  28372. Thickness of iridescence layer has an equivalent effect of the one `thickness` has on `ior`.
  28373. *
  28374. * @type {Array<number,number>}
  28375. * @default [100,400]
  28376. */
  28377. this.iridescenceThicknessRange = [ 100, 400 ];
  28378. /**
  28379. * A texture that defines the thickness of the iridescence layer, stored in the green channel.
  28380. * Minimum and maximum values of thickness are defined by `iridescenceThicknessRange` array:
  28381. * - `0.0` in the green channel will result in thickness equal to first element of the array.
  28382. * - `1.0` in the green channel will result in thickness equal to second element of the array.
  28383. * - Values in-between will linearly interpolate between the elements of the array.
  28384. *
  28385. * @type {?Texture}
  28386. * @default null
  28387. */
  28388. this.iridescenceThicknessMap = null;
  28389. /**
  28390. * The sheen tint.
  28391. *
  28392. * @type {Color}
  28393. * @default (0,0,0)
  28394. */
  28395. this.sheenColor = new Color( 0x000000 );
  28396. /**
  28397. * The RGB channels of this texture are multiplied against `sheenColor`, for per-pixel control
  28398. * over sheen tint.
  28399. *
  28400. * @type {?Texture}
  28401. * @default null
  28402. */
  28403. this.sheenColorMap = null;
  28404. /**
  28405. * Roughness of the sheen layer, from `0.0` to `1.0`.
  28406. *
  28407. * @type {number}
  28408. * @default 1
  28409. */
  28410. this.sheenRoughness = 1.0;
  28411. /**
  28412. * The alpha channel of this texture is multiplied against `sheenRoughness`, for per-pixel control
  28413. * over sheen roughness.
  28414. *
  28415. * @type {?Texture}
  28416. * @default null
  28417. */
  28418. this.sheenRoughnessMap = null;
  28419. /**
  28420. * The red channel of this texture is multiplied against `transmission`, for per-pixel control over
  28421. * optical transparency.
  28422. *
  28423. * @type {?Texture}
  28424. * @default null
  28425. */
  28426. this.transmissionMap = null;
  28427. /**
  28428. * The thickness of the volume beneath the surface. The value is given in the
  28429. * coordinate space of the mesh. If the value is `0` the material is
  28430. * thin-walled. Otherwise the material is a volume boundary.
  28431. *
  28432. * @type {number}
  28433. * @default 0
  28434. */
  28435. this.thickness = 0;
  28436. /**
  28437. * A texture that defines the thickness, stored in the green channel. This will
  28438. * be multiplied by `thickness`.
  28439. *
  28440. * @type {?Texture}
  28441. * @default null
  28442. */
  28443. this.thicknessMap = null;
  28444. /**
  28445. * Density of the medium given as the average distance that light travels in
  28446. * the medium before interacting with a particle. The value is given in world
  28447. * space units, and must be greater than zero.
  28448. *
  28449. * @type {number}
  28450. * @default Infinity
  28451. */
  28452. this.attenuationDistance = Infinity;
  28453. /**
  28454. * The color that white light turns into due to absorption when reaching the
  28455. * attenuation distance.
  28456. *
  28457. * @type {Color}
  28458. * @default (1,1,1)
  28459. */
  28460. this.attenuationColor = new Color( 1, 1, 1 );
  28461. /**
  28462. * A float that scales the amount of specular reflection for non-metals only.
  28463. * When set to zero, the model is effectively Lambertian. From `0.0` to `1.0`.
  28464. *
  28465. * @type {number}
  28466. * @default 1
  28467. */
  28468. this.specularIntensity = 1.0;
  28469. /**
  28470. * The alpha channel of this texture is multiplied against `specularIntensity`,
  28471. * for per-pixel control over specular intensity.
  28472. *
  28473. * @type {?Texture}
  28474. * @default null
  28475. */
  28476. this.specularIntensityMap = null;
  28477. /**
  28478. * Tints the specular reflection at normal incidence for non-metals only.
  28479. *
  28480. * @type {Color}
  28481. * @default (1,1,1)
  28482. */
  28483. this.specularColor = new Color( 1, 1, 1 );
  28484. /**
  28485. * The RGB channels of this texture are multiplied against `specularColor`,
  28486. * for per-pixel control over specular color.
  28487. *
  28488. * @type {?Texture}
  28489. * @default null
  28490. */
  28491. this.specularColorMap = null;
  28492. this._anisotropy = 0;
  28493. this._clearcoat = 0;
  28494. this._dispersion = 0;
  28495. this._iridescence = 0;
  28496. this._sheen = 0.0;
  28497. this._transmission = 0;
  28498. this.setValues( parameters );
  28499. }
  28500. /**
  28501. * The anisotropy strength, from `0.0` to `1.0`.
  28502. *
  28503. * @type {number}
  28504. * @default 0
  28505. */
  28506. get anisotropy() {
  28507. return this._anisotropy;
  28508. }
  28509. set anisotropy( value ) {
  28510. if ( this._anisotropy > 0 !== value > 0 ) {
  28511. this.version ++;
  28512. }
  28513. this._anisotropy = value;
  28514. }
  28515. /**
  28516. * Represents the intensity of the clear coat layer, from `0.0` to `1.0`. Use
  28517. * clear coat related properties to enable multilayer materials that have a
  28518. * thin translucent layer over the base layer.
  28519. *
  28520. * @type {number}
  28521. * @default 0
  28522. */
  28523. get clearcoat() {
  28524. return this._clearcoat;
  28525. }
  28526. set clearcoat( value ) {
  28527. if ( this._clearcoat > 0 !== value > 0 ) {
  28528. this.version ++;
  28529. }
  28530. this._clearcoat = value;
  28531. }
  28532. /**
  28533. * The intensity of the iridescence layer, simulating RGB color shift based on the angle between
  28534. * the surface and the viewer, from `0.0` to `1.0`.
  28535. *
  28536. * @type {number}
  28537. * @default 0
  28538. */
  28539. get iridescence() {
  28540. return this._iridescence;
  28541. }
  28542. set iridescence( value ) {
  28543. if ( this._iridescence > 0 !== value > 0 ) {
  28544. this.version ++;
  28545. }
  28546. this._iridescence = value;
  28547. }
  28548. /**
  28549. * Defines the strength of the angular separation of colors (chromatic aberration) transmitting
  28550. * through a relatively clear volume. Any value zero or larger is valid, the typical range of
  28551. * realistic values is `[0, 1]`. This property can be only be used with transmissive objects.
  28552. *
  28553. * @type {number}
  28554. * @default 0
  28555. */
  28556. get dispersion() {
  28557. return this._dispersion;
  28558. }
  28559. set dispersion( value ) {
  28560. if ( this._dispersion > 0 !== value > 0 ) {
  28561. this.version ++;
  28562. }
  28563. this._dispersion = value;
  28564. }
  28565. /**
  28566. * The intensity of the sheen layer, from `0.0` to `1.0`.
  28567. *
  28568. * @type {number}
  28569. * @default 0
  28570. */
  28571. get sheen() {
  28572. return this._sheen;
  28573. }
  28574. set sheen( value ) {
  28575. if ( this._sheen > 0 !== value > 0 ) {
  28576. this.version ++;
  28577. }
  28578. this._sheen = value;
  28579. }
  28580. /**
  28581. * Degree of transmission (or optical transparency), from `0.0` to `1.0`.
  28582. *
  28583. * Thin, transparent or semitransparent, plastic or glass materials remain
  28584. * largely reflective even if they are fully transmissive. The transmission
  28585. * property can be used to model these materials.
  28586. *
  28587. * When transmission is non-zero, `opacity` should be set to `1`.
  28588. *
  28589. * @type {number}
  28590. * @default 0
  28591. */
  28592. get transmission() {
  28593. return this._transmission;
  28594. }
  28595. set transmission( value ) {
  28596. if ( this._transmission > 0 !== value > 0 ) {
  28597. this.version ++;
  28598. }
  28599. this._transmission = value;
  28600. }
  28601. copy( source ) {
  28602. super.copy( source );
  28603. this.defines = {
  28604. 'STANDARD': '',
  28605. 'PHYSICAL': ''
  28606. };
  28607. this.anisotropy = source.anisotropy;
  28608. this.anisotropyRotation = source.anisotropyRotation;
  28609. this.anisotropyMap = source.anisotropyMap;
  28610. this.clearcoat = source.clearcoat;
  28611. this.clearcoatMap = source.clearcoatMap;
  28612. this.clearcoatRoughness = source.clearcoatRoughness;
  28613. this.clearcoatRoughnessMap = source.clearcoatRoughnessMap;
  28614. this.clearcoatNormalMap = source.clearcoatNormalMap;
  28615. this.clearcoatNormalScale.copy( source.clearcoatNormalScale );
  28616. this.dispersion = source.dispersion;
  28617. this.ior = source.ior;
  28618. this.iridescence = source.iridescence;
  28619. this.iridescenceMap = source.iridescenceMap;
  28620. this.iridescenceIOR = source.iridescenceIOR;
  28621. this.iridescenceThicknessRange = [ ...source.iridescenceThicknessRange ];
  28622. this.iridescenceThicknessMap = source.iridescenceThicknessMap;
  28623. this.sheen = source.sheen;
  28624. this.sheenColor.copy( source.sheenColor );
  28625. this.sheenColorMap = source.sheenColorMap;
  28626. this.sheenRoughness = source.sheenRoughness;
  28627. this.sheenRoughnessMap = source.sheenRoughnessMap;
  28628. this.transmission = source.transmission;
  28629. this.transmissionMap = source.transmissionMap;
  28630. this.thickness = source.thickness;
  28631. this.thicknessMap = source.thicknessMap;
  28632. this.attenuationDistance = source.attenuationDistance;
  28633. this.attenuationColor.copy( source.attenuationColor );
  28634. this.specularIntensity = source.specularIntensity;
  28635. this.specularIntensityMap = source.specularIntensityMap;
  28636. this.specularColor.copy( source.specularColor );
  28637. this.specularColorMap = source.specularColorMap;
  28638. return this;
  28639. }
  28640. }
  28641. /**
  28642. * A material for shiny surfaces with specular highlights.
  28643. *
  28644. * The material uses a non-physically based [Blinn-Phong](https://en.wikipedia.org/wiki/Blinn-Phong_shading_model)
  28645. * model for calculating reflectance. Unlike the Lambertian model used in the
  28646. * {@link MeshLambertMaterial} this can simulate shiny surfaces with specular
  28647. * highlights (such as varnished wood). `MeshPhongMaterial` uses per-fragment shading.
  28648. *
  28649. * Performance will generally be greater when using this material over the
  28650. * {@link MeshStandardMaterial} or {@link MeshPhysicalMaterial}, at the cost of
  28651. * some graphical accuracy.
  28652. *
  28653. * @augments Material
  28654. * @demo scenes/material-browser.html#MeshPhongMaterial
  28655. */
  28656. class MeshPhongMaterial extends Material {
  28657. /**
  28658. * Constructs a new mesh phong material.
  28659. *
  28660. * @param {Object} [parameters] - An object with one or more properties
  28661. * defining the material's appearance. Any property of the material
  28662. * (including any property from inherited materials) can be passed
  28663. * in here. Color values can be passed any type of value accepted
  28664. * by {@link Color#set}.
  28665. */
  28666. constructor( parameters ) {
  28667. super();
  28668. /**
  28669. * This flag can be used for type testing.
  28670. *
  28671. * @type {boolean}
  28672. * @readonly
  28673. * @default true
  28674. */
  28675. this.isMeshPhongMaterial = true;
  28676. this.type = 'MeshPhongMaterial';
  28677. /**
  28678. * Color of the material.
  28679. *
  28680. * @type {Color}
  28681. * @default (1,1,1)
  28682. */
  28683. this.color = new Color( 0xffffff ); // diffuse
  28684. /**
  28685. * Specular color of the material. The default color is set to `0x111111` (very dark grey)
  28686. *
  28687. * This defines how shiny the material is and the color of its shine.
  28688. *
  28689. * @type {Color}
  28690. */
  28691. this.specular = new Color( 0x111111 );
  28692. /**
  28693. * How shiny the specular highlight is; a higher value gives a sharper highlight.
  28694. *
  28695. * @type {number}
  28696. * @default 30
  28697. */
  28698. this.shininess = 30;
  28699. /**
  28700. * The color map. May optionally include an alpha channel, typically combined
  28701. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  28702. * color is modulated by the diffuse `color`.
  28703. *
  28704. * @type {?Texture}
  28705. * @default null
  28706. */
  28707. this.map = null;
  28708. /**
  28709. * The light map. Requires a second set of UVs.
  28710. *
  28711. * @type {?Texture}
  28712. * @default null
  28713. */
  28714. this.lightMap = null;
  28715. /**
  28716. * Intensity of the baked light.
  28717. *
  28718. * @type {number}
  28719. * @default 1
  28720. */
  28721. this.lightMapIntensity = 1.0;
  28722. /**
  28723. * The red channel of this texture is used as the ambient occlusion map.
  28724. * Requires a second set of UVs.
  28725. *
  28726. * @type {?Texture}
  28727. * @default null
  28728. */
  28729. this.aoMap = null;
  28730. /**
  28731. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  28732. * disables ambient occlusion. Where intensity is `1` and the AO map's
  28733. * red channel is also `1`, ambient light is fully occluded on a surface.
  28734. *
  28735. * @type {number}
  28736. * @default 1
  28737. */
  28738. this.aoMapIntensity = 1.0;
  28739. /**
  28740. * Emissive (light) color of the material, essentially a solid color
  28741. * unaffected by other lighting.
  28742. *
  28743. * @type {Color}
  28744. * @default (0,0,0)
  28745. */
  28746. this.emissive = new Color( 0x000000 );
  28747. /**
  28748. * Intensity of the emissive light. Modulates the emissive color.
  28749. *
  28750. * @type {number}
  28751. * @default 1
  28752. */
  28753. this.emissiveIntensity = 1.0;
  28754. /**
  28755. * Set emissive (glow) map. The emissive map color is modulated by the
  28756. * emissive color and the emissive intensity. If you have an emissive map,
  28757. * be sure to set the emissive color to something other than black.
  28758. *
  28759. * @type {?Texture}
  28760. * @default null
  28761. */
  28762. this.emissiveMap = null;
  28763. /**
  28764. * The texture to create a bump map. The black and white values map to the
  28765. * perceived depth in relation to the lights. Bump doesn't actually affect
  28766. * the geometry of the object, only the lighting. If a normal map is defined
  28767. * this will be ignored.
  28768. *
  28769. * @type {?Texture}
  28770. * @default null
  28771. */
  28772. this.bumpMap = null;
  28773. /**
  28774. * How much the bump map affects the material. Typical range is `[0,1]`.
  28775. *
  28776. * @type {number}
  28777. * @default 1
  28778. */
  28779. this.bumpScale = 1;
  28780. /**
  28781. * The texture to create a normal map. The RGB values affect the surface
  28782. * normal for each pixel fragment and change the way the color is lit. Normal
  28783. * maps do not change the actual shape of the surface, only the lighting. In
  28784. * case the material has a normal map authored using the left handed
  28785. * convention, the `y` component of `normalScale` should be negated to compensate
  28786. * for the different handedness.
  28787. *
  28788. * @type {?Texture}
  28789. * @default null
  28790. */
  28791. this.normalMap = null;
  28792. /**
  28793. * The type of normal map.
  28794. *
  28795. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  28796. * @default TangentSpaceNormalMap
  28797. */
  28798. this.normalMapType = TangentSpaceNormalMap;
  28799. /**
  28800. * How much the normal map affects the material. Typical value range is `[0,1]`.
  28801. *
  28802. * @type {Vector2}
  28803. * @default (1,1)
  28804. */
  28805. this.normalScale = new Vector2( 1, 1 );
  28806. /**
  28807. * The displacement map affects the position of the mesh's vertices. Unlike
  28808. * other maps which only affect the light and shade of the material the
  28809. * displaced vertices can cast shadows, block other objects, and otherwise
  28810. * act as real geometry. The displacement texture is an image where the value
  28811. * of each pixel (white being the highest) is mapped against, and
  28812. * repositions, the vertices of the mesh.
  28813. *
  28814. * @type {?Texture}
  28815. * @default null
  28816. */
  28817. this.displacementMap = null;
  28818. /**
  28819. * How much the displacement map affects the mesh (where black is no
  28820. * displacement, and white is maximum displacement). Without a displacement
  28821. * map set, this value is not applied.
  28822. *
  28823. * @type {number}
  28824. * @default 0
  28825. */
  28826. this.displacementScale = 1;
  28827. /**
  28828. * The offset of the displacement map's values on the mesh's vertices.
  28829. * The bias is added to the scaled sample of the displacement map.
  28830. * Without a displacement map set, this value is not applied.
  28831. *
  28832. * @type {number}
  28833. * @default 0
  28834. */
  28835. this.displacementBias = 0;
  28836. /**
  28837. * The specular map value affects both how much the specular surface
  28838. * highlight contributes and how much of the environment map affects the
  28839. * surface.
  28840. *
  28841. * @type {?Texture}
  28842. * @default null
  28843. */
  28844. this.specularMap = null;
  28845. /**
  28846. * The alpha map is a grayscale texture that controls the opacity across the
  28847. * surface (black: fully transparent; white: fully opaque).
  28848. *
  28849. * Only the color of the texture is used, ignoring the alpha channel if one
  28850. * exists. For RGB and RGBA textures, the renderer will use the green channel
  28851. * when sampling this texture due to the extra bit of precision provided for
  28852. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  28853. * luminance/alpha textures will also still work as expected.
  28854. *
  28855. * @type {?Texture}
  28856. * @default null
  28857. */
  28858. this.alphaMap = null;
  28859. /**
  28860. * The environment map.
  28861. *
  28862. * @type {?Texture}
  28863. * @default null
  28864. */
  28865. this.envMap = null;
  28866. /**
  28867. * The rotation of the environment map in radians.
  28868. *
  28869. * @type {Euler}
  28870. * @default (0,0,0)
  28871. */
  28872. this.envMapRotation = new Euler();
  28873. /**
  28874. * How to combine the result of the surface's color with the environment map, if any.
  28875. *
  28876. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  28877. * blend between the two colors.
  28878. *
  28879. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  28880. * @default MultiplyOperation
  28881. */
  28882. this.combine = MultiplyOperation;
  28883. /**
  28884. * How much the environment map affects the surface.
  28885. * The valid range is between `0` (no reflections) and `1` (full reflections).
  28886. *
  28887. * @type {number}
  28888. * @default 1
  28889. */
  28890. this.reflectivity = 1;
  28891. /**
  28892. * The index of refraction (IOR) of air (approximately 1) divided by the
  28893. * index of refraction of the material. It is used with environment mapping
  28894. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  28895. * The refraction ratio should not exceed `1`.
  28896. *
  28897. * @type {number}
  28898. * @default 0.98
  28899. */
  28900. this.refractionRatio = 0.98;
  28901. /**
  28902. * Renders the geometry as a wireframe.
  28903. *
  28904. * @type {boolean}
  28905. * @default false
  28906. */
  28907. this.wireframe = false;
  28908. /**
  28909. * Controls the thickness of the wireframe.
  28910. *
  28911. * Can only be used with {@link SVGRenderer}.
  28912. *
  28913. * @type {number}
  28914. * @default 1
  28915. */
  28916. this.wireframeLinewidth = 1;
  28917. /**
  28918. * Defines appearance of wireframe ends.
  28919. *
  28920. * Can only be used with {@link SVGRenderer}.
  28921. *
  28922. * @type {('round'|'bevel'|'miter')}
  28923. * @default 'round'
  28924. */
  28925. this.wireframeLinecap = 'round';
  28926. /**
  28927. * Defines appearance of wireframe joints.
  28928. *
  28929. * Can only be used with {@link SVGRenderer}.
  28930. *
  28931. * @type {('round'|'bevel'|'miter')}
  28932. * @default 'round'
  28933. */
  28934. this.wireframeLinejoin = 'round';
  28935. /**
  28936. * Whether the material is rendered with flat shading or not.
  28937. *
  28938. * @type {boolean}
  28939. * @default false
  28940. */
  28941. this.flatShading = false;
  28942. /**
  28943. * Whether the material is affected by fog or not.
  28944. *
  28945. * @type {boolean}
  28946. * @default true
  28947. */
  28948. this.fog = true;
  28949. this.setValues( parameters );
  28950. }
  28951. copy( source ) {
  28952. super.copy( source );
  28953. this.color.copy( source.color );
  28954. this.specular.copy( source.specular );
  28955. this.shininess = source.shininess;
  28956. this.map = source.map;
  28957. this.lightMap = source.lightMap;
  28958. this.lightMapIntensity = source.lightMapIntensity;
  28959. this.aoMap = source.aoMap;
  28960. this.aoMapIntensity = source.aoMapIntensity;
  28961. this.emissive.copy( source.emissive );
  28962. this.emissiveMap = source.emissiveMap;
  28963. this.emissiveIntensity = source.emissiveIntensity;
  28964. this.bumpMap = source.bumpMap;
  28965. this.bumpScale = source.bumpScale;
  28966. this.normalMap = source.normalMap;
  28967. this.normalMapType = source.normalMapType;
  28968. this.normalScale.copy( source.normalScale );
  28969. this.displacementMap = source.displacementMap;
  28970. this.displacementScale = source.displacementScale;
  28971. this.displacementBias = source.displacementBias;
  28972. this.specularMap = source.specularMap;
  28973. this.alphaMap = source.alphaMap;
  28974. this.envMap = source.envMap;
  28975. this.envMapRotation.copy( source.envMapRotation );
  28976. this.combine = source.combine;
  28977. this.reflectivity = source.reflectivity;
  28978. this.refractionRatio = source.refractionRatio;
  28979. this.wireframe = source.wireframe;
  28980. this.wireframeLinewidth = source.wireframeLinewidth;
  28981. this.wireframeLinecap = source.wireframeLinecap;
  28982. this.wireframeLinejoin = source.wireframeLinejoin;
  28983. this.flatShading = source.flatShading;
  28984. this.fog = source.fog;
  28985. return this;
  28986. }
  28987. }
  28988. /**
  28989. * A material implementing toon shading.
  28990. *
  28991. * @augments Material
  28992. * @demo scenes/material-browser.html#MeshToonMaterial
  28993. */
  28994. class MeshToonMaterial extends Material {
  28995. /**
  28996. * Constructs a new mesh toon material.
  28997. *
  28998. * @param {Object} [parameters] - An object with one or more properties
  28999. * defining the material's appearance. Any property of the material
  29000. * (including any property from inherited materials) can be passed
  29001. * in here. Color values can be passed any type of value accepted
  29002. * by {@link Color#set}.
  29003. */
  29004. constructor( parameters ) {
  29005. super();
  29006. /**
  29007. * This flag can be used for type testing.
  29008. *
  29009. * @type {boolean}
  29010. * @readonly
  29011. * @default true
  29012. */
  29013. this.isMeshToonMaterial = true;
  29014. this.defines = { 'TOON': '' };
  29015. this.type = 'MeshToonMaterial';
  29016. /**
  29017. * Color of the material.
  29018. *
  29019. * @type {Color}
  29020. * @default (1,1,1)
  29021. */
  29022. this.color = new Color( 0xffffff );
  29023. /**
  29024. * The color map. May optionally include an alpha channel, typically combined
  29025. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29026. * color is modulated by the diffuse `color`.
  29027. *
  29028. * @type {?Texture}
  29029. * @default null
  29030. */
  29031. this.map = null;
  29032. /**
  29033. * Gradient map for toon shading. It's required to set
  29034. * {@link Texture#minFilter} and {@link Texture#magFilter} to {@linkNearestFilter}
  29035. * when using this type of texture.
  29036. *
  29037. * @type {?Texture}
  29038. * @default null
  29039. */
  29040. this.gradientMap = null;
  29041. /**
  29042. * The light map. Requires a second set of UVs.
  29043. *
  29044. * @type {?Texture}
  29045. * @default null
  29046. */
  29047. this.lightMap = null;
  29048. /**
  29049. * Intensity of the baked light.
  29050. *
  29051. * @type {number}
  29052. * @default 1
  29053. */
  29054. this.lightMapIntensity = 1.0;
  29055. /**
  29056. * The red channel of this texture is used as the ambient occlusion map.
  29057. * Requires a second set of UVs.
  29058. *
  29059. * @type {?Texture}
  29060. * @default null
  29061. */
  29062. this.aoMap = null;
  29063. /**
  29064. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29065. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29066. * red channel is also `1`, ambient light is fully occluded on a surface.
  29067. *
  29068. * @type {number}
  29069. * @default 1
  29070. */
  29071. this.aoMapIntensity = 1.0;
  29072. /**
  29073. * Emissive (light) color of the material, essentially a solid color
  29074. * unaffected by other lighting.
  29075. *
  29076. * @type {Color}
  29077. * @default (0,0,0)
  29078. */
  29079. this.emissive = new Color( 0x000000 );
  29080. /**
  29081. * Intensity of the emissive light. Modulates the emissive color.
  29082. *
  29083. * @type {number}
  29084. * @default 1
  29085. */
  29086. this.emissiveIntensity = 1.0;
  29087. /**
  29088. * Set emissive (glow) map. The emissive map color is modulated by the
  29089. * emissive color and the emissive intensity. If you have an emissive map,
  29090. * be sure to set the emissive color to something other than black.
  29091. *
  29092. * @type {?Texture}
  29093. * @default null
  29094. */
  29095. this.emissiveMap = null;
  29096. /**
  29097. * The texture to create a bump map. The black and white values map to the
  29098. * perceived depth in relation to the lights. Bump doesn't actually affect
  29099. * the geometry of the object, only the lighting. If a normal map is defined
  29100. * this will be ignored.
  29101. *
  29102. * @type {?Texture}
  29103. * @default null
  29104. */
  29105. this.bumpMap = null;
  29106. /**
  29107. * How much the bump map affects the material. Typical range is `[0,1]`.
  29108. *
  29109. * @type {number}
  29110. * @default 1
  29111. */
  29112. this.bumpScale = 1;
  29113. /**
  29114. * The texture to create a normal map. The RGB values affect the surface
  29115. * normal for each pixel fragment and change the way the color is lit. Normal
  29116. * maps do not change the actual shape of the surface, only the lighting. In
  29117. * case the material has a normal map authored using the left handed
  29118. * convention, the `y` component of `normalScale` should be negated to compensate
  29119. * for the different handedness.
  29120. *
  29121. * @type {?Texture}
  29122. * @default null
  29123. */
  29124. this.normalMap = null;
  29125. /**
  29126. * The type of normal map.
  29127. *
  29128. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29129. * @default TangentSpaceNormalMap
  29130. */
  29131. this.normalMapType = TangentSpaceNormalMap;
  29132. /**
  29133. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29134. *
  29135. * @type {Vector2}
  29136. * @default (1,1)
  29137. */
  29138. this.normalScale = new Vector2( 1, 1 );
  29139. /**
  29140. * The displacement map affects the position of the mesh's vertices. Unlike
  29141. * other maps which only affect the light and shade of the material the
  29142. * displaced vertices can cast shadows, block other objects, and otherwise
  29143. * act as real geometry. The displacement texture is an image where the value
  29144. * of each pixel (white being the highest) is mapped against, and
  29145. * repositions, the vertices of the mesh.
  29146. *
  29147. * @type {?Texture}
  29148. * @default null
  29149. */
  29150. this.displacementMap = null;
  29151. /**
  29152. * How much the displacement map affects the mesh (where black is no
  29153. * displacement, and white is maximum displacement). Without a displacement
  29154. * map set, this value is not applied.
  29155. *
  29156. * @type {number}
  29157. * @default 0
  29158. */
  29159. this.displacementScale = 1;
  29160. /**
  29161. * The offset of the displacement map's values on the mesh's vertices.
  29162. * The bias is added to the scaled sample of the displacement map.
  29163. * Without a displacement map set, this value is not applied.
  29164. *
  29165. * @type {number}
  29166. * @default 0
  29167. */
  29168. this.displacementBias = 0;
  29169. /**
  29170. * The alpha map is a grayscale texture that controls the opacity across the
  29171. * surface (black: fully transparent; white: fully opaque).
  29172. *
  29173. * Only the color of the texture is used, ignoring the alpha channel if one
  29174. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29175. * when sampling this texture due to the extra bit of precision provided for
  29176. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29177. * luminance/alpha textures will also still work as expected.
  29178. *
  29179. * @type {?Texture}
  29180. * @default null
  29181. */
  29182. this.alphaMap = null;
  29183. /**
  29184. * Renders the geometry as a wireframe.
  29185. *
  29186. * @type {boolean}
  29187. * @default false
  29188. */
  29189. this.wireframe = false;
  29190. /**
  29191. * Controls the thickness of the wireframe.
  29192. *
  29193. * Can only be used with {@link SVGRenderer}.
  29194. *
  29195. * @type {number}
  29196. * @default 1
  29197. */
  29198. this.wireframeLinewidth = 1;
  29199. /**
  29200. * Defines appearance of wireframe ends.
  29201. *
  29202. * Can only be used with {@link SVGRenderer}.
  29203. *
  29204. * @type {('round'|'bevel'|'miter')}
  29205. * @default 'round'
  29206. */
  29207. this.wireframeLinecap = 'round';
  29208. /**
  29209. * Defines appearance of wireframe joints.
  29210. *
  29211. * Can only be used with {@link SVGRenderer}.
  29212. *
  29213. * @type {('round'|'bevel'|'miter')}
  29214. * @default 'round'
  29215. */
  29216. this.wireframeLinejoin = 'round';
  29217. /**
  29218. * Whether the material is affected by fog or not.
  29219. *
  29220. * @type {boolean}
  29221. * @default true
  29222. */
  29223. this.fog = true;
  29224. this.setValues( parameters );
  29225. }
  29226. copy( source ) {
  29227. super.copy( source );
  29228. this.color.copy( source.color );
  29229. this.map = source.map;
  29230. this.gradientMap = source.gradientMap;
  29231. this.lightMap = source.lightMap;
  29232. this.lightMapIntensity = source.lightMapIntensity;
  29233. this.aoMap = source.aoMap;
  29234. this.aoMapIntensity = source.aoMapIntensity;
  29235. this.emissive.copy( source.emissive );
  29236. this.emissiveMap = source.emissiveMap;
  29237. this.emissiveIntensity = source.emissiveIntensity;
  29238. this.bumpMap = source.bumpMap;
  29239. this.bumpScale = source.bumpScale;
  29240. this.normalMap = source.normalMap;
  29241. this.normalMapType = source.normalMapType;
  29242. this.normalScale.copy( source.normalScale );
  29243. this.displacementMap = source.displacementMap;
  29244. this.displacementScale = source.displacementScale;
  29245. this.displacementBias = source.displacementBias;
  29246. this.alphaMap = source.alphaMap;
  29247. this.wireframe = source.wireframe;
  29248. this.wireframeLinewidth = source.wireframeLinewidth;
  29249. this.wireframeLinecap = source.wireframeLinecap;
  29250. this.wireframeLinejoin = source.wireframeLinejoin;
  29251. this.fog = source.fog;
  29252. return this;
  29253. }
  29254. }
  29255. /**
  29256. * A material that maps the normal vectors to RGB colors.
  29257. *
  29258. * @augments Material
  29259. * @demo scenes/material-browser.html#MeshNormalMaterial
  29260. */
  29261. class MeshNormalMaterial extends Material {
  29262. /**
  29263. * Constructs a new mesh normal material.
  29264. *
  29265. * @param {Object} [parameters] - An object with one or more properties
  29266. * defining the material's appearance. Any property of the material
  29267. * (including any property from inherited materials) can be passed
  29268. * in here. Color values can be passed any type of value accepted
  29269. * by {@link Color#set}.
  29270. */
  29271. constructor( parameters ) {
  29272. super();
  29273. /**
  29274. * This flag can be used for type testing.
  29275. *
  29276. * @type {boolean}
  29277. * @readonly
  29278. * @default true
  29279. */
  29280. this.isMeshNormalMaterial = true;
  29281. this.type = 'MeshNormalMaterial';
  29282. /**
  29283. * The texture to create a bump map. The black and white values map to the
  29284. * perceived depth in relation to the lights. Bump doesn't actually affect
  29285. * the geometry of the object, only the lighting. If a normal map is defined
  29286. * this will be ignored.
  29287. *
  29288. * @type {?Texture}
  29289. * @default null
  29290. */
  29291. this.bumpMap = null;
  29292. /**
  29293. * How much the bump map affects the material. Typical range is `[0,1]`.
  29294. *
  29295. * @type {number}
  29296. * @default 1
  29297. */
  29298. this.bumpScale = 1;
  29299. /**
  29300. * The texture to create a normal map. The RGB values affect the surface
  29301. * normal for each pixel fragment and change the way the color is lit. Normal
  29302. * maps do not change the actual shape of the surface, only the lighting. In
  29303. * case the material has a normal map authored using the left handed
  29304. * convention, the `y` component of `normalScale` should be negated to compensate
  29305. * for the different handedness.
  29306. *
  29307. * @type {?Texture}
  29308. * @default null
  29309. */
  29310. this.normalMap = null;
  29311. /**
  29312. * The type of normal map.
  29313. *
  29314. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29315. * @default TangentSpaceNormalMap
  29316. */
  29317. this.normalMapType = TangentSpaceNormalMap;
  29318. /**
  29319. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29320. *
  29321. * @type {Vector2}
  29322. * @default (1,1)
  29323. */
  29324. this.normalScale = new Vector2( 1, 1 );
  29325. /**
  29326. * The displacement map affects the position of the mesh's vertices. Unlike
  29327. * other maps which only affect the light and shade of the material the
  29328. * displaced vertices can cast shadows, block other objects, and otherwise
  29329. * act as real geometry. The displacement texture is an image where the value
  29330. * of each pixel (white being the highest) is mapped against, and
  29331. * repositions, the vertices of the mesh.
  29332. *
  29333. * @type {?Texture}
  29334. * @default null
  29335. */
  29336. this.displacementMap = null;
  29337. /**
  29338. * How much the displacement map affects the mesh (where black is no
  29339. * displacement, and white is maximum displacement). Without a displacement
  29340. * map set, this value is not applied.
  29341. *
  29342. * @type {number}
  29343. * @default 0
  29344. */
  29345. this.displacementScale = 1;
  29346. /**
  29347. * The offset of the displacement map's values on the mesh's vertices.
  29348. * The bias is added to the scaled sample of the displacement map.
  29349. * Without a displacement map set, this value is not applied.
  29350. *
  29351. * @type {number}
  29352. * @default 0
  29353. */
  29354. this.displacementBias = 0;
  29355. /**
  29356. * Renders the geometry as a wireframe.
  29357. *
  29358. * @type {boolean}
  29359. * @default false
  29360. */
  29361. this.wireframe = false;
  29362. /**
  29363. * Controls the thickness of the wireframe.
  29364. *
  29365. * WebGL and WebGPU ignore this property and always render
  29366. * 1 pixel wide lines.
  29367. *
  29368. * @type {number}
  29369. * @default 1
  29370. */
  29371. this.wireframeLinewidth = 1;
  29372. /**
  29373. * Whether the material is rendered with flat shading or not.
  29374. *
  29375. * @type {boolean}
  29376. * @default false
  29377. */
  29378. this.flatShading = false;
  29379. this.setValues( parameters );
  29380. }
  29381. copy( source ) {
  29382. super.copy( source );
  29383. this.bumpMap = source.bumpMap;
  29384. this.bumpScale = source.bumpScale;
  29385. this.normalMap = source.normalMap;
  29386. this.normalMapType = source.normalMapType;
  29387. this.normalScale.copy( source.normalScale );
  29388. this.displacementMap = source.displacementMap;
  29389. this.displacementScale = source.displacementScale;
  29390. this.displacementBias = source.displacementBias;
  29391. this.wireframe = source.wireframe;
  29392. this.wireframeLinewidth = source.wireframeLinewidth;
  29393. this.flatShading = source.flatShading;
  29394. return this;
  29395. }
  29396. }
  29397. /**
  29398. * A material for non-shiny surfaces, without specular highlights.
  29399. *
  29400. * The material uses a non-physically based [Lambertian](https://en.wikipedia.org/wiki/Lambertian_reflectance)
  29401. * model for calculating reflectance. This can simulate some surfaces (such
  29402. * as untreated wood or stone) well, but cannot simulate shiny surfaces with
  29403. * specular highlights (such as varnished wood). `MeshLambertMaterial` uses per-fragment
  29404. * shading.
  29405. *
  29406. * Due to the simplicity of the reflectance and illumination models,
  29407. * performance will be greater when using this material over the
  29408. * {@link MeshPhongMaterial}, {@link MeshStandardMaterial} or
  29409. * {@link MeshPhysicalMaterial}, at the cost of some graphical accuracy.
  29410. *
  29411. * @augments Material
  29412. * @demo scenes/material-browser.html#MeshLambertMaterial
  29413. */
  29414. class MeshLambertMaterial extends Material {
  29415. /**
  29416. * Constructs a new mesh lambert material.
  29417. *
  29418. * @param {Object} [parameters] - An object with one or more properties
  29419. * defining the material's appearance. Any property of the material
  29420. * (including any property from inherited materials) can be passed
  29421. * in here. Color values can be passed any type of value accepted
  29422. * by {@link Color#set}.
  29423. */
  29424. constructor( parameters ) {
  29425. super();
  29426. /**
  29427. * This flag can be used for type testing.
  29428. *
  29429. * @type {boolean}
  29430. * @readonly
  29431. * @default true
  29432. */
  29433. this.isMeshLambertMaterial = true;
  29434. this.type = 'MeshLambertMaterial';
  29435. /**
  29436. * Color of the material.
  29437. *
  29438. * @type {Color}
  29439. * @default (1,1,1)
  29440. */
  29441. this.color = new Color( 0xffffff ); // diffuse
  29442. /**
  29443. * The color map. May optionally include an alpha channel, typically combined
  29444. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29445. * color is modulated by the diffuse `color`.
  29446. *
  29447. * @type {?Texture}
  29448. * @default null
  29449. */
  29450. this.map = null;
  29451. /**
  29452. * The light map. Requires a second set of UVs.
  29453. *
  29454. * @type {?Texture}
  29455. * @default null
  29456. */
  29457. this.lightMap = null;
  29458. /**
  29459. * Intensity of the baked light.
  29460. *
  29461. * @type {number}
  29462. * @default 1
  29463. */
  29464. this.lightMapIntensity = 1.0;
  29465. /**
  29466. * The red channel of this texture is used as the ambient occlusion map.
  29467. * Requires a second set of UVs.
  29468. *
  29469. * @type {?Texture}
  29470. * @default null
  29471. */
  29472. this.aoMap = null;
  29473. /**
  29474. * Intensity of the ambient occlusion effect. Range is `[0,1]`, where `0`
  29475. * disables ambient occlusion. Where intensity is `1` and the AO map's
  29476. * red channel is also `1`, ambient light is fully occluded on a surface.
  29477. *
  29478. * @type {number}
  29479. * @default 1
  29480. */
  29481. this.aoMapIntensity = 1.0;
  29482. /**
  29483. * Emissive (light) color of the material, essentially a solid color
  29484. * unaffected by other lighting.
  29485. *
  29486. * @type {Color}
  29487. * @default (0,0,0)
  29488. */
  29489. this.emissive = new Color( 0x000000 );
  29490. /**
  29491. * Intensity of the emissive light. Modulates the emissive color.
  29492. *
  29493. * @type {number}
  29494. * @default 1
  29495. */
  29496. this.emissiveIntensity = 1.0;
  29497. /**
  29498. * Set emissive (glow) map. The emissive map color is modulated by the
  29499. * emissive color and the emissive intensity. If you have an emissive map,
  29500. * be sure to set the emissive color to something other than black.
  29501. *
  29502. * @type {?Texture}
  29503. * @default null
  29504. */
  29505. this.emissiveMap = null;
  29506. /**
  29507. * The texture to create a bump map. The black and white values map to the
  29508. * perceived depth in relation to the lights. Bump doesn't actually affect
  29509. * the geometry of the object, only the lighting. If a normal map is defined
  29510. * this will be ignored.
  29511. *
  29512. * @type {?Texture}
  29513. * @default null
  29514. */
  29515. this.bumpMap = null;
  29516. /**
  29517. * How much the bump map affects the material. Typical range is `[0,1]`.
  29518. *
  29519. * @type {number}
  29520. * @default 1
  29521. */
  29522. this.bumpScale = 1;
  29523. /**
  29524. * The texture to create a normal map. The RGB values affect the surface
  29525. * normal for each pixel fragment and change the way the color is lit. Normal
  29526. * maps do not change the actual shape of the surface, only the lighting. In
  29527. * case the material has a normal map authored using the left handed
  29528. * convention, the `y` component of `normalScale` should be negated to compensate
  29529. * for the different handedness.
  29530. *
  29531. * @type {?Texture}
  29532. * @default null
  29533. */
  29534. this.normalMap = null;
  29535. /**
  29536. * The type of normal map.
  29537. *
  29538. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  29539. * @default TangentSpaceNormalMap
  29540. */
  29541. this.normalMapType = TangentSpaceNormalMap;
  29542. /**
  29543. * How much the normal map affects the material. Typical value range is `[0,1]`.
  29544. *
  29545. * @type {Vector2}
  29546. * @default (1,1)
  29547. */
  29548. this.normalScale = new Vector2( 1, 1 );
  29549. /**
  29550. * The displacement map affects the position of the mesh's vertices. Unlike
  29551. * other maps which only affect the light and shade of the material the
  29552. * displaced vertices can cast shadows, block other objects, and otherwise
  29553. * act as real geometry. The displacement texture is an image where the value
  29554. * of each pixel (white being the highest) is mapped against, and
  29555. * repositions, the vertices of the mesh.
  29556. *
  29557. * @type {?Texture}
  29558. * @default null
  29559. */
  29560. this.displacementMap = null;
  29561. /**
  29562. * How much the displacement map affects the mesh (where black is no
  29563. * displacement, and white is maximum displacement). Without a displacement
  29564. * map set, this value is not applied.
  29565. *
  29566. * @type {number}
  29567. * @default 0
  29568. */
  29569. this.displacementScale = 1;
  29570. /**
  29571. * The offset of the displacement map's values on the mesh's vertices.
  29572. * The bias is added to the scaled sample of the displacement map.
  29573. * Without a displacement map set, this value is not applied.
  29574. *
  29575. * @type {number}
  29576. * @default 0
  29577. */
  29578. this.displacementBias = 0;
  29579. /**
  29580. * Specular map used by the material.
  29581. *
  29582. * @type {?Texture}
  29583. * @default null
  29584. */
  29585. this.specularMap = null;
  29586. /**
  29587. * The alpha map is a grayscale texture that controls the opacity across the
  29588. * surface (black: fully transparent; white: fully opaque).
  29589. *
  29590. * Only the color of the texture is used, ignoring the alpha channel if one
  29591. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29592. * when sampling this texture due to the extra bit of precision provided for
  29593. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29594. * luminance/alpha textures will also still work as expected.
  29595. *
  29596. * @type {?Texture}
  29597. * @default null
  29598. */
  29599. this.alphaMap = null;
  29600. /**
  29601. * The environment map.
  29602. *
  29603. * @type {?Texture}
  29604. * @default null
  29605. */
  29606. this.envMap = null;
  29607. /**
  29608. * The rotation of the environment map in radians.
  29609. *
  29610. * @type {Euler}
  29611. * @default (0,0,0)
  29612. */
  29613. this.envMapRotation = new Euler();
  29614. /**
  29615. * How to combine the result of the surface's color with the environment map, if any.
  29616. *
  29617. * When set to `MixOperation`, the {@link MeshBasicMaterial#reflectivity} is used to
  29618. * blend between the two colors.
  29619. *
  29620. * @type {(MultiplyOperation|MixOperation|AddOperation)}
  29621. * @default MultiplyOperation
  29622. */
  29623. this.combine = MultiplyOperation;
  29624. /**
  29625. * How much the environment map affects the surface.
  29626. * The valid range is between `0` (no reflections) and `1` (full reflections).
  29627. *
  29628. * @type {number}
  29629. * @default 1
  29630. */
  29631. this.reflectivity = 1;
  29632. /**
  29633. * The index of refraction (IOR) of air (approximately 1) divided by the
  29634. * index of refraction of the material. It is used with environment mapping
  29635. * modes {@link CubeRefractionMapping} and {@link EquirectangularRefractionMapping}.
  29636. * The refraction ratio should not exceed `1`.
  29637. *
  29638. * @type {number}
  29639. * @default 0.98
  29640. */
  29641. this.refractionRatio = 0.98;
  29642. /**
  29643. * Renders the geometry as a wireframe.
  29644. *
  29645. * @type {boolean}
  29646. * @default false
  29647. */
  29648. this.wireframe = false;
  29649. /**
  29650. * Controls the thickness of the wireframe.
  29651. *
  29652. * Can only be used with {@link SVGRenderer}.
  29653. *
  29654. * @type {number}
  29655. * @default 1
  29656. */
  29657. this.wireframeLinewidth = 1;
  29658. /**
  29659. * Defines appearance of wireframe ends.
  29660. *
  29661. * Can only be used with {@link SVGRenderer}.
  29662. *
  29663. * @type {('round'|'bevel'|'miter')}
  29664. * @default 'round'
  29665. */
  29666. this.wireframeLinecap = 'round';
  29667. /**
  29668. * Defines appearance of wireframe joints.
  29669. *
  29670. * Can only be used with {@link SVGRenderer}.
  29671. *
  29672. * @type {('round'|'bevel'|'miter')}
  29673. * @default 'round'
  29674. */
  29675. this.wireframeLinejoin = 'round';
  29676. /**
  29677. * Whether the material is rendered with flat shading or not.
  29678. *
  29679. * @type {boolean}
  29680. * @default false
  29681. */
  29682. this.flatShading = false;
  29683. /**
  29684. * Whether the material is affected by fog or not.
  29685. *
  29686. * @type {boolean}
  29687. * @default true
  29688. */
  29689. this.fog = true;
  29690. this.setValues( parameters );
  29691. }
  29692. copy( source ) {
  29693. super.copy( source );
  29694. this.color.copy( source.color );
  29695. this.map = source.map;
  29696. this.lightMap = source.lightMap;
  29697. this.lightMapIntensity = source.lightMapIntensity;
  29698. this.aoMap = source.aoMap;
  29699. this.aoMapIntensity = source.aoMapIntensity;
  29700. this.emissive.copy( source.emissive );
  29701. this.emissiveMap = source.emissiveMap;
  29702. this.emissiveIntensity = source.emissiveIntensity;
  29703. this.bumpMap = source.bumpMap;
  29704. this.bumpScale = source.bumpScale;
  29705. this.normalMap = source.normalMap;
  29706. this.normalMapType = source.normalMapType;
  29707. this.normalScale.copy( source.normalScale );
  29708. this.displacementMap = source.displacementMap;
  29709. this.displacementScale = source.displacementScale;
  29710. this.displacementBias = source.displacementBias;
  29711. this.specularMap = source.specularMap;
  29712. this.alphaMap = source.alphaMap;
  29713. this.envMap = source.envMap;
  29714. this.envMapRotation.copy( source.envMapRotation );
  29715. this.combine = source.combine;
  29716. this.reflectivity = source.reflectivity;
  29717. this.refractionRatio = source.refractionRatio;
  29718. this.wireframe = source.wireframe;
  29719. this.wireframeLinewidth = source.wireframeLinewidth;
  29720. this.wireframeLinecap = source.wireframeLinecap;
  29721. this.wireframeLinejoin = source.wireframeLinejoin;
  29722. this.flatShading = source.flatShading;
  29723. this.fog = source.fog;
  29724. return this;
  29725. }
  29726. }
  29727. /**
  29728. * A material for drawing geometry by depth. Depth is based off of the camera
  29729. * near and far plane. White is nearest, black is farthest.
  29730. *
  29731. * @augments Material
  29732. * @demo scenes/material-browser.html#MeshDepthMaterial
  29733. */
  29734. class MeshDepthMaterial extends Material {
  29735. /**
  29736. * Constructs a new mesh depth material.
  29737. *
  29738. * @param {Object} [parameters] - An object with one or more properties
  29739. * defining the material's appearance. Any property of the material
  29740. * (including any property from inherited materials) can be passed
  29741. * in here. Color values can be passed any type of value accepted
  29742. * by {@link Color#set}.
  29743. */
  29744. constructor( parameters ) {
  29745. super();
  29746. /**
  29747. * This flag can be used for type testing.
  29748. *
  29749. * @type {boolean}
  29750. * @readonly
  29751. * @default true
  29752. */
  29753. this.isMeshDepthMaterial = true;
  29754. this.type = 'MeshDepthMaterial';
  29755. /**
  29756. * Type for depth packing.
  29757. *
  29758. * @type {(BasicDepthPacking|RGBADepthPacking|RGBDepthPacking|RGDepthPacking)}
  29759. * @default BasicDepthPacking
  29760. */
  29761. this.depthPacking = BasicDepthPacking;
  29762. /**
  29763. * The color map. May optionally include an alpha channel, typically combined
  29764. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29765. *
  29766. * @type {?Texture}
  29767. * @default null
  29768. */
  29769. this.map = null;
  29770. /**
  29771. * The alpha map is a grayscale texture that controls the opacity across the
  29772. * surface (black: fully transparent; white: fully opaque).
  29773. *
  29774. * Only the color of the texture is used, ignoring the alpha channel if one
  29775. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29776. * when sampling this texture due to the extra bit of precision provided for
  29777. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29778. * luminance/alpha textures will also still work as expected.
  29779. *
  29780. * @type {?Texture}
  29781. * @default null
  29782. */
  29783. this.alphaMap = null;
  29784. /**
  29785. * The displacement map affects the position of the mesh's vertices. Unlike
  29786. * other maps which only affect the light and shade of the material the
  29787. * displaced vertices can cast shadows, block other objects, and otherwise
  29788. * act as real geometry. The displacement texture is an image where the value
  29789. * of each pixel (white being the highest) is mapped against, and
  29790. * repositions, the vertices of the mesh.
  29791. *
  29792. * @type {?Texture}
  29793. * @default null
  29794. */
  29795. this.displacementMap = null;
  29796. /**
  29797. * How much the displacement map affects the mesh (where black is no
  29798. * displacement, and white is maximum displacement). Without a displacement
  29799. * map set, this value is not applied.
  29800. *
  29801. * @type {number}
  29802. * @default 0
  29803. */
  29804. this.displacementScale = 1;
  29805. /**
  29806. * The offset of the displacement map's values on the mesh's vertices.
  29807. * The bias is added to the scaled sample of the displacement map.
  29808. * Without a displacement map set, this value is not applied.
  29809. *
  29810. * @type {number}
  29811. * @default 0
  29812. */
  29813. this.displacementBias = 0;
  29814. /**
  29815. * Renders the geometry as a wireframe.
  29816. *
  29817. * @type {boolean}
  29818. * @default false
  29819. */
  29820. this.wireframe = false;
  29821. /**
  29822. * Controls the thickness of the wireframe.
  29823. *
  29824. * WebGL and WebGPU ignore this property and always render
  29825. * 1 pixel wide lines.
  29826. *
  29827. * @type {number}
  29828. * @default 1
  29829. */
  29830. this.wireframeLinewidth = 1;
  29831. this.setValues( parameters );
  29832. }
  29833. copy( source ) {
  29834. super.copy( source );
  29835. this.depthPacking = source.depthPacking;
  29836. this.map = source.map;
  29837. this.alphaMap = source.alphaMap;
  29838. this.displacementMap = source.displacementMap;
  29839. this.displacementScale = source.displacementScale;
  29840. this.displacementBias = source.displacementBias;
  29841. this.wireframe = source.wireframe;
  29842. this.wireframeLinewidth = source.wireframeLinewidth;
  29843. return this;
  29844. }
  29845. }
  29846. /**
  29847. * A material used internally for implementing shadow mapping with
  29848. * point lights.
  29849. *
  29850. * Can also be used to customize the shadow casting of an object by assigning
  29851. * an instance of `MeshDistanceMaterial` to {@link Object3D#customDistanceMaterial}.
  29852. * The following examples demonstrates this approach in order to ensure
  29853. * transparent parts of objects do not cast shadows.
  29854. *
  29855. * @augments Material
  29856. */
  29857. class MeshDistanceMaterial extends Material {
  29858. /**
  29859. * Constructs a new mesh distance material.
  29860. *
  29861. * @param {Object} [parameters] - An object with one or more properties
  29862. * defining the material's appearance. Any property of the material
  29863. * (including any property from inherited materials) can be passed
  29864. * in here. Color values can be passed any type of value accepted
  29865. * by {@link Color#set}.
  29866. */
  29867. constructor( parameters ) {
  29868. super();
  29869. /**
  29870. * This flag can be used for type testing.
  29871. *
  29872. * @type {boolean}
  29873. * @readonly
  29874. * @default true
  29875. */
  29876. this.isMeshDistanceMaterial = true;
  29877. this.type = 'MeshDistanceMaterial';
  29878. /**
  29879. * The color map. May optionally include an alpha channel, typically combined
  29880. * with {@link Material#transparent} or {@link Material#alphaTest}.
  29881. *
  29882. * @type {?Texture}
  29883. * @default null
  29884. */
  29885. this.map = null;
  29886. /**
  29887. * The alpha map is a grayscale texture that controls the opacity across the
  29888. * surface (black: fully transparent; white: fully opaque).
  29889. *
  29890. * Only the color of the texture is used, ignoring the alpha channel if one
  29891. * exists. For RGB and RGBA textures, the renderer will use the green channel
  29892. * when sampling this texture due to the extra bit of precision provided for
  29893. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  29894. * luminance/alpha textures will also still work as expected.
  29895. *
  29896. * @type {?Texture}
  29897. * @default null
  29898. */
  29899. this.alphaMap = null;
  29900. /**
  29901. * The displacement map affects the position of the mesh's vertices. Unlike
  29902. * other maps which only affect the light and shade of the material the
  29903. * displaced vertices can cast shadows, block other objects, and otherwise
  29904. * act as real geometry. The displacement texture is an image where the value
  29905. * of each pixel (white being the highest) is mapped against, and
  29906. * repositions, the vertices of the mesh.
  29907. *
  29908. * @type {?Texture}
  29909. * @default null
  29910. */
  29911. this.displacementMap = null;
  29912. /**
  29913. * How much the displacement map affects the mesh (where black is no
  29914. * displacement, and white is maximum displacement). Without a displacement
  29915. * map set, this value is not applied.
  29916. *
  29917. * @type {number}
  29918. * @default 0
  29919. */
  29920. this.displacementScale = 1;
  29921. /**
  29922. * The offset of the displacement map's values on the mesh's vertices.
  29923. * The bias is added to the scaled sample of the displacement map.
  29924. * Without a displacement map set, this value is not applied.
  29925. *
  29926. * @type {number}
  29927. * @default 0
  29928. */
  29929. this.displacementBias = 0;
  29930. this.setValues( parameters );
  29931. }
  29932. copy( source ) {
  29933. super.copy( source );
  29934. this.map = source.map;
  29935. this.alphaMap = source.alphaMap;
  29936. this.displacementMap = source.displacementMap;
  29937. this.displacementScale = source.displacementScale;
  29938. this.displacementBias = source.displacementBias;
  29939. return this;
  29940. }
  29941. }
  29942. /**
  29943. * This material is defined by a MatCap (or Lit Sphere) texture, which encodes the
  29944. * material color and shading.
  29945. *
  29946. * `MeshMatcapMaterial` does not respond to lights since the matcap image file encodes
  29947. * baked lighting. It will cast a shadow onto an object that receives shadows
  29948. * (and shadow clipping works), but it will not self-shadow or receive
  29949. * shadows.
  29950. *
  29951. * @augments Material
  29952. * @demo scenes/material-browser.html#MeshMatcapMaterial
  29953. */
  29954. class MeshMatcapMaterial extends Material {
  29955. /**
  29956. * Constructs a new mesh matcap material.
  29957. *
  29958. * @param {Object} [parameters] - An object with one or more properties
  29959. * defining the material's appearance. Any property of the material
  29960. * (including any property from inherited materials) can be passed
  29961. * in here. Color values can be passed any type of value accepted
  29962. * by {@link Color#set}.
  29963. */
  29964. constructor( parameters ) {
  29965. super();
  29966. /**
  29967. * This flag can be used for type testing.
  29968. *
  29969. * @type {boolean}
  29970. * @readonly
  29971. * @default true
  29972. */
  29973. this.isMeshMatcapMaterial = true;
  29974. this.defines = { 'MATCAP': '' };
  29975. this.type = 'MeshMatcapMaterial';
  29976. /**
  29977. * Color of the material.
  29978. *
  29979. * @type {Color}
  29980. * @default (1,1,1)
  29981. */
  29982. this.color = new Color( 0xffffff ); // diffuse
  29983. /**
  29984. * The matcap map.
  29985. *
  29986. * @type {?Texture}
  29987. * @default null
  29988. */
  29989. this.matcap = null;
  29990. /**
  29991. * The color map. May optionally include an alpha channel, typically combined
  29992. * with {@link Material#transparent} or {@link Material#alphaTest}. The texture map
  29993. * color is modulated by the diffuse `color`.
  29994. *
  29995. * @type {?Texture}
  29996. * @default null
  29997. */
  29998. this.map = null;
  29999. /**
  30000. * The texture to create a bump map. The black and white values map to the
  30001. * perceived depth in relation to the lights. Bump doesn't actually affect
  30002. * the geometry of the object, only the lighting. If a normal map is defined
  30003. * this will be ignored.
  30004. *
  30005. * @type {?Texture}
  30006. * @default null
  30007. */
  30008. this.bumpMap = null;
  30009. /**
  30010. * How much the bump map affects the material. Typical range is `[0,1]`.
  30011. *
  30012. * @type {number}
  30013. * @default 1
  30014. */
  30015. this.bumpScale = 1;
  30016. /**
  30017. * The texture to create a normal map. The RGB values affect the surface
  30018. * normal for each pixel fragment and change the way the color is lit. Normal
  30019. * maps do not change the actual shape of the surface, only the lighting. In
  30020. * case the material has a normal map authored using the left handed
  30021. * convention, the `y` component of `normalScale` should be negated to compensate
  30022. * for the different handedness.
  30023. *
  30024. * @type {?Texture}
  30025. * @default null
  30026. */
  30027. this.normalMap = null;
  30028. /**
  30029. * The type of normal map.
  30030. *
  30031. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  30032. * @default TangentSpaceNormalMap
  30033. */
  30034. this.normalMapType = TangentSpaceNormalMap;
  30035. /**
  30036. * How much the normal map affects the material. Typical value range is `[0,1]`.
  30037. *
  30038. * @type {Vector2}
  30039. * @default (1,1)
  30040. */
  30041. this.normalScale = new Vector2( 1, 1 );
  30042. /**
  30043. * The displacement map affects the position of the mesh's vertices. Unlike
  30044. * other maps which only affect the light and shade of the material the
  30045. * displaced vertices can cast shadows, block other objects, and otherwise
  30046. * act as real geometry. The displacement texture is an image where the value
  30047. * of each pixel (white being the highest) is mapped against, and
  30048. * repositions, the vertices of the mesh.
  30049. *
  30050. * @type {?Texture}
  30051. * @default null
  30052. */
  30053. this.displacementMap = null;
  30054. /**
  30055. * How much the displacement map affects the mesh (where black is no
  30056. * displacement, and white is maximum displacement). Without a displacement
  30057. * map set, this value is not applied.
  30058. *
  30059. * @type {number}
  30060. * @default 0
  30061. */
  30062. this.displacementScale = 1;
  30063. /**
  30064. * The offset of the displacement map's values on the mesh's vertices.
  30065. * The bias is added to the scaled sample of the displacement map.
  30066. * Without a displacement map set, this value is not applied.
  30067. *
  30068. * @type {number}
  30069. * @default 0
  30070. */
  30071. this.displacementBias = 0;
  30072. /**
  30073. * The alpha map is a grayscale texture that controls the opacity across the
  30074. * surface (black: fully transparent; white: fully opaque).
  30075. *
  30076. * Only the color of the texture is used, ignoring the alpha channel if one
  30077. * exists. For RGB and RGBA textures, the renderer will use the green channel
  30078. * when sampling this texture due to the extra bit of precision provided for
  30079. * green in DXT-compressed and uncompressed RGB 565 formats. Luminance-only and
  30080. * luminance/alpha textures will also still work as expected.
  30081. *
  30082. * @type {?Texture}
  30083. * @default null
  30084. */
  30085. this.alphaMap = null;
  30086. /**
  30087. * Renders the geometry as a wireframe.
  30088. *
  30089. * @type {boolean}
  30090. * @default false
  30091. */
  30092. this.wireframe = false;
  30093. /**
  30094. * Controls the thickness of the wireframe.
  30095. *
  30096. * Can only be used with {@link SVGRenderer}.
  30097. *
  30098. * @type {number}
  30099. * @default 1
  30100. */
  30101. this.wireframeLinewidth = 1;
  30102. /**
  30103. * Whether the material is rendered with flat shading or not.
  30104. *
  30105. * @type {boolean}
  30106. * @default false
  30107. */
  30108. this.flatShading = false;
  30109. /**
  30110. * Whether the material is affected by fog or not.
  30111. *
  30112. * @type {boolean}
  30113. * @default true
  30114. */
  30115. this.fog = true;
  30116. this.setValues( parameters );
  30117. }
  30118. copy( source ) {
  30119. super.copy( source );
  30120. this.defines = { 'MATCAP': '' };
  30121. this.color.copy( source.color );
  30122. this.matcap = source.matcap;
  30123. this.map = source.map;
  30124. this.bumpMap = source.bumpMap;
  30125. this.bumpScale = source.bumpScale;
  30126. this.normalMap = source.normalMap;
  30127. this.normalMapType = source.normalMapType;
  30128. this.normalScale.copy( source.normalScale );
  30129. this.displacementMap = source.displacementMap;
  30130. this.displacementScale = source.displacementScale;
  30131. this.displacementBias = source.displacementBias;
  30132. this.alphaMap = source.alphaMap;
  30133. this.wireframe = source.wireframe;
  30134. this.wireframeLinewidth = source.wireframeLinewidth;
  30135. this.flatShading = source.flatShading;
  30136. this.fog = source.fog;
  30137. return this;
  30138. }
  30139. }
  30140. /**
  30141. * A material for rendering line primitives.
  30142. *
  30143. * Materials define the appearance of renderable 3D objects.
  30144. *
  30145. * ```js
  30146. * const material = new THREE.LineDashedMaterial( {
  30147. * color: 0xffffff,
  30148. * scale: 1,
  30149. * dashSize: 3,
  30150. * gapSize: 1,
  30151. * } );
  30152. * ```
  30153. *
  30154. * @augments LineBasicMaterial
  30155. */
  30156. class LineDashedMaterial extends LineBasicMaterial {
  30157. /**
  30158. * Constructs a new line dashed material.
  30159. *
  30160. * @param {Object} [parameters] - An object with one or more properties
  30161. * defining the material's appearance. Any property of the material
  30162. * (including any property from inherited materials) can be passed
  30163. * in here. Color values can be passed any type of value accepted
  30164. * by {@link Color#set}.
  30165. */
  30166. constructor( parameters ) {
  30167. super();
  30168. /**
  30169. * This flag can be used for type testing.
  30170. *
  30171. * @type {boolean}
  30172. * @readonly
  30173. * @default true
  30174. */
  30175. this.isLineDashedMaterial = true;
  30176. this.type = 'LineDashedMaterial';
  30177. /**
  30178. * The scale of the dashed part of a line.
  30179. *
  30180. * @type {number}
  30181. * @default 1
  30182. */
  30183. this.scale = 1;
  30184. /**
  30185. * The size of the dash. This is both the gap with the stroke.
  30186. *
  30187. * @type {number}
  30188. * @default 3
  30189. */
  30190. this.dashSize = 3;
  30191. /**
  30192. * The size of the gap.
  30193. *
  30194. * @type {number}
  30195. * @default 1
  30196. */
  30197. this.gapSize = 1;
  30198. this.setValues( parameters );
  30199. }
  30200. copy( source ) {
  30201. super.copy( source );
  30202. this.scale = source.scale;
  30203. this.dashSize = source.dashSize;
  30204. this.gapSize = source.gapSize;
  30205. return this;
  30206. }
  30207. }
  30208. /**
  30209. * Converts an array to a specific type.
  30210. *
  30211. * @param {TypedArray|Array} array - The array to convert.
  30212. * @param {TypedArray.constructor} type - The constructor of a typed array that defines the new type.
  30213. * @return {TypedArray} The converted array.
  30214. */
  30215. function convertArray( array, type ) {
  30216. if ( ! array || array.constructor === type ) return array;
  30217. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  30218. return new type( array ); // create typed array
  30219. }
  30220. return Array.prototype.slice.call( array ); // create Array
  30221. }
  30222. /**
  30223. * Returns an array by which times and values can be sorted.
  30224. *
  30225. * @param {Array<number>} times - The keyframe time values.
  30226. * @return {Array<number>} The array.
  30227. */
  30228. function getKeyframeOrder( times ) {
  30229. function compareTime( i, j ) {
  30230. return times[ i ] - times[ j ];
  30231. }
  30232. const n = times.length;
  30233. const result = new Array( n );
  30234. for ( let i = 0; i !== n; ++ i ) result[ i ] = i;
  30235. result.sort( compareTime );
  30236. return result;
  30237. }
  30238. /**
  30239. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30240. *
  30241. * @param {Array<number>} values - The values to sort.
  30242. * @param {number} stride - The stride.
  30243. * @param {Array<number>} order - The sort order.
  30244. * @return {Array<number>} The sorted values.
  30245. */
  30246. function sortedArray( values, stride, order ) {
  30247. const nValues = values.length;
  30248. const result = new values.constructor( nValues );
  30249. for ( let i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  30250. const srcOffset = order[ i ] * stride;
  30251. for ( let j = 0; j !== stride; ++ j ) {
  30252. result[ dstOffset ++ ] = values[ srcOffset + j ];
  30253. }
  30254. }
  30255. return result;
  30256. }
  30257. /**
  30258. * Used for parsing AOS keyframe formats.
  30259. *
  30260. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30261. * @param {Array<number>} times - This array will be filled with keyframe times by this function.
  30262. * @param {Array<number>} values - This array will be filled with keyframe values by this function.
  30263. * @param {string} valuePropertyName - The name of the property to use.
  30264. */
  30265. function flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30266. let i = 1, key = jsonKeys[ 0 ];
  30267. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  30268. key = jsonKeys[ i ++ ];
  30269. }
  30270. if ( key === undefined ) return; // no data
  30271. let value = key[ valuePropertyName ];
  30272. if ( value === undefined ) return; // no data
  30273. if ( Array.isArray( value ) ) {
  30274. do {
  30275. value = key[ valuePropertyName ];
  30276. if ( value !== undefined ) {
  30277. times.push( key.time );
  30278. values.push( ...value ); // push all elements
  30279. }
  30280. key = jsonKeys[ i ++ ];
  30281. } while ( key !== undefined );
  30282. } else if ( value.toArray !== undefined ) {
  30283. // ...assume THREE.Math-ish
  30284. do {
  30285. value = key[ valuePropertyName ];
  30286. if ( value !== undefined ) {
  30287. times.push( key.time );
  30288. value.toArray( values, values.length );
  30289. }
  30290. key = jsonKeys[ i ++ ];
  30291. } while ( key !== undefined );
  30292. } else {
  30293. // otherwise push as-is
  30294. do {
  30295. value = key[ valuePropertyName ];
  30296. if ( value !== undefined ) {
  30297. times.push( key.time );
  30298. values.push( value );
  30299. }
  30300. key = jsonKeys[ i ++ ];
  30301. } while ( key !== undefined );
  30302. }
  30303. }
  30304. /**
  30305. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30306. *
  30307. * @param {AnimationClip} sourceClip - The values to sort.
  30308. * @param {string} name - The name of the clip.
  30309. * @param {number} startFrame - The start frame.
  30310. * @param {number} endFrame - The end frame.
  30311. * @param {number} [fps=30] - The FPS.
  30312. * @return {AnimationClip} The new sub clip.
  30313. */
  30314. function subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30315. const clip = sourceClip.clone();
  30316. clip.name = name;
  30317. const tracks = [];
  30318. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30319. const track = clip.tracks[ i ];
  30320. const valueSize = track.getValueSize();
  30321. const times = [];
  30322. const values = [];
  30323. for ( let j = 0; j < track.times.length; ++ j ) {
  30324. const frame = track.times[ j ] * fps;
  30325. if ( frame < startFrame || frame >= endFrame ) continue;
  30326. times.push( track.times[ j ] );
  30327. for ( let k = 0; k < valueSize; ++ k ) {
  30328. values.push( track.values[ j * valueSize + k ] );
  30329. }
  30330. }
  30331. if ( times.length === 0 ) continue;
  30332. track.times = convertArray( times, track.times.constructor );
  30333. track.values = convertArray( values, track.values.constructor );
  30334. tracks.push( track );
  30335. }
  30336. clip.tracks = tracks;
  30337. // find minimum .times value across all tracks in the trimmed clip
  30338. let minStartTime = Infinity;
  30339. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30340. if ( minStartTime > clip.tracks[ i ].times[ 0 ] ) {
  30341. minStartTime = clip.tracks[ i ].times[ 0 ];
  30342. }
  30343. }
  30344. // shift all tracks such that clip begins at t=0
  30345. for ( let i = 0; i < clip.tracks.length; ++ i ) {
  30346. clip.tracks[ i ].shift( -1 * minStartTime );
  30347. }
  30348. clip.resetDuration();
  30349. return clip;
  30350. }
  30351. /**
  30352. * Converts the keyframes of the given animation clip to an additive format.
  30353. *
  30354. * @param {AnimationClip} targetClip - The clip to make additive.
  30355. * @param {number} [referenceFrame=0] - The reference frame.
  30356. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30357. * @param {number} [fps=30] - The FPS.
  30358. * @return {AnimationClip} The updated clip which is now additive.
  30359. */
  30360. function makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30361. if ( fps <= 0 ) fps = 30;
  30362. const numTracks = referenceClip.tracks.length;
  30363. const referenceTime = referenceFrame / fps;
  30364. // Make each track's values relative to the values at the reference frame
  30365. for ( let i = 0; i < numTracks; ++ i ) {
  30366. const referenceTrack = referenceClip.tracks[ i ];
  30367. const referenceTrackType = referenceTrack.ValueTypeName;
  30368. // Skip this track if it's non-numeric
  30369. if ( referenceTrackType === 'bool' || referenceTrackType === 'string' ) continue;
  30370. // Find the track in the target clip whose name and type matches the reference track
  30371. const targetTrack = targetClip.tracks.find( function ( track ) {
  30372. return track.name === referenceTrack.name
  30373. && track.ValueTypeName === referenceTrackType;
  30374. } );
  30375. if ( targetTrack === undefined ) continue;
  30376. let referenceOffset = 0;
  30377. const referenceValueSize = referenceTrack.getValueSize();
  30378. if ( referenceTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30379. referenceOffset = referenceValueSize / 3;
  30380. }
  30381. let targetOffset = 0;
  30382. const targetValueSize = targetTrack.getValueSize();
  30383. if ( targetTrack.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline ) {
  30384. targetOffset = targetValueSize / 3;
  30385. }
  30386. const lastIndex = referenceTrack.times.length - 1;
  30387. let referenceValue;
  30388. // Find the value to subtract out of the track
  30389. if ( referenceTime <= referenceTrack.times[ 0 ] ) {
  30390. // Reference frame is earlier than the first keyframe, so just use the first keyframe
  30391. const startIndex = referenceOffset;
  30392. const endIndex = referenceValueSize - referenceOffset;
  30393. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30394. } else if ( referenceTime >= referenceTrack.times[ lastIndex ] ) {
  30395. // Reference frame is after the last keyframe, so just use the last keyframe
  30396. const startIndex = lastIndex * referenceValueSize + referenceOffset;
  30397. const endIndex = startIndex + referenceValueSize - referenceOffset;
  30398. referenceValue = referenceTrack.values.slice( startIndex, endIndex );
  30399. } else {
  30400. // Interpolate to the reference value
  30401. const interpolant = referenceTrack.createInterpolant();
  30402. const startIndex = referenceOffset;
  30403. const endIndex = referenceValueSize - referenceOffset;
  30404. interpolant.evaluate( referenceTime );
  30405. referenceValue = interpolant.resultBuffer.slice( startIndex, endIndex );
  30406. }
  30407. // Conjugate the quaternion
  30408. if ( referenceTrackType === 'quaternion' ) {
  30409. const referenceQuat = new Quaternion().fromArray( referenceValue ).normalize().conjugate();
  30410. referenceQuat.toArray( referenceValue );
  30411. }
  30412. // Subtract the reference value from all of the track values
  30413. const numTimes = targetTrack.times.length;
  30414. for ( let j = 0; j < numTimes; ++ j ) {
  30415. const valueStart = j * targetValueSize + targetOffset;
  30416. if ( referenceTrackType === 'quaternion' ) {
  30417. // Multiply the conjugate for quaternion track types
  30418. Quaternion.multiplyQuaternionsFlat(
  30419. targetTrack.values,
  30420. valueStart,
  30421. referenceValue,
  30422. 0,
  30423. targetTrack.values,
  30424. valueStart
  30425. );
  30426. } else {
  30427. const valueEnd = targetValueSize - targetOffset * 2;
  30428. // Subtract each value for all other numeric track types
  30429. for ( let k = 0; k < valueEnd; ++ k ) {
  30430. targetTrack.values[ valueStart + k ] -= referenceValue[ k ];
  30431. }
  30432. }
  30433. }
  30434. }
  30435. targetClip.blendMode = AdditiveAnimationBlendMode;
  30436. return targetClip;
  30437. }
  30438. /**
  30439. * A class with various methods to assist with animations.
  30440. *
  30441. * @hideconstructor
  30442. */
  30443. class AnimationUtils {
  30444. /**
  30445. * Converts an array to a specific type
  30446. *
  30447. * @static
  30448. * @param {TypedArray|Array} array - The array to convert.
  30449. * @param {TypedArray.constructor} type - The constructor of a type array.
  30450. * @return {TypedArray} The converted array
  30451. */
  30452. static convertArray( array, type ) {
  30453. return convertArray( array, type );
  30454. }
  30455. /**
  30456. * Returns `true` if the given object is a typed array.
  30457. *
  30458. * @static
  30459. * @param {any} object - The object to check.
  30460. * @return {boolean} Whether the given object is a typed array.
  30461. */
  30462. static isTypedArray( object ) {
  30463. return isTypedArray( object );
  30464. }
  30465. /**
  30466. * Returns an array by which times and values can be sorted.
  30467. *
  30468. * @static
  30469. * @param {Array<number>} times - The keyframe time values.
  30470. * @return {Array<number>} The array.
  30471. */
  30472. static getKeyframeOrder( times ) {
  30473. return getKeyframeOrder( times );
  30474. }
  30475. /**
  30476. * Sorts the given array by the previously computed order via `getKeyframeOrder()`.
  30477. *
  30478. * @static
  30479. * @param {Array<number>} values - The values to sort.
  30480. * @param {number} stride - The stride.
  30481. * @param {Array<number>} order - The sort order.
  30482. * @return {Array<number>} The sorted values.
  30483. */
  30484. static sortedArray( values, stride, order ) {
  30485. return sortedArray( values, stride, order );
  30486. }
  30487. /**
  30488. * Used for parsing AOS keyframe formats.
  30489. *
  30490. * @static
  30491. * @param {Array<number>} jsonKeys - A list of JSON keyframes.
  30492. * @param {Array<number>} times - This array will be filled with keyframe times by this method.
  30493. * @param {Array<number>} values - This array will be filled with keyframe values by this method.
  30494. * @param {string} valuePropertyName - The name of the property to use.
  30495. */
  30496. static flattenJSON( jsonKeys, times, values, valuePropertyName ) {
  30497. flattenJSON( jsonKeys, times, values, valuePropertyName );
  30498. }
  30499. /**
  30500. * Creates a new clip, containing only the segment of the original clip between the given frames.
  30501. *
  30502. * @static
  30503. * @param {AnimationClip} sourceClip - The values to sort.
  30504. * @param {string} name - The name of the clip.
  30505. * @param {number} startFrame - The start frame.
  30506. * @param {number} endFrame - The end frame.
  30507. * @param {number} [fps=30] - The FPS.
  30508. * @return {AnimationClip} The new sub clip.
  30509. */
  30510. static subclip( sourceClip, name, startFrame, endFrame, fps = 30 ) {
  30511. return subclip( sourceClip, name, startFrame, endFrame, fps );
  30512. }
  30513. /**
  30514. * Converts the keyframes of the given animation clip to an additive format.
  30515. *
  30516. * @static
  30517. * @param {AnimationClip} targetClip - The clip to make additive.
  30518. * @param {number} [referenceFrame=0] - The reference frame.
  30519. * @param {AnimationClip} [referenceClip=targetClip] - The reference clip.
  30520. * @param {number} [fps=30] - The FPS.
  30521. * @return {AnimationClip} The updated clip which is now additive.
  30522. */
  30523. static makeClipAdditive( targetClip, referenceFrame = 0, referenceClip = targetClip, fps = 30 ) {
  30524. return makeClipAdditive( targetClip, referenceFrame, referenceClip, fps );
  30525. }
  30526. }
  30527. /**
  30528. * Abstract base class of interpolants over parametric samples.
  30529. *
  30530. * The parameter domain is one dimensional, typically the time or a path
  30531. * along a curve defined by the data.
  30532. *
  30533. * The sample values can have any dimensionality and derived classes may
  30534. * apply special interpretations to the data.
  30535. *
  30536. * This class provides the interval seek in a Template Method, deferring
  30537. * the actual interpolation to derived classes.
  30538. *
  30539. * Time complexity is O(1) for linear access crossing at most two points
  30540. * and O(log N) for random access, where N is the number of positions.
  30541. *
  30542. * References: {@link http://www.oodesign.com/template-method-pattern.html}
  30543. *
  30544. * @abstract
  30545. */
  30546. class Interpolant {
  30547. /**
  30548. * Constructs a new interpolant.
  30549. *
  30550. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30551. * @param {TypedArray} sampleValues - The sample values.
  30552. * @param {number} sampleSize - The sample size
  30553. * @param {TypedArray} [resultBuffer] - The result buffer.
  30554. */
  30555. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30556. /**
  30557. * The parameter positions.
  30558. *
  30559. * @type {TypedArray}
  30560. */
  30561. this.parameterPositions = parameterPositions;
  30562. /**
  30563. * A cache index.
  30564. *
  30565. * @private
  30566. * @type {number}
  30567. * @default 0
  30568. */
  30569. this._cachedIndex = 0;
  30570. /**
  30571. * The result buffer.
  30572. *
  30573. * @type {TypedArray}
  30574. */
  30575. this.resultBuffer = resultBuffer !== undefined ? resultBuffer : new sampleValues.constructor( sampleSize );
  30576. /**
  30577. * The sample values.
  30578. *
  30579. * @type {TypedArray}
  30580. */
  30581. this.sampleValues = sampleValues;
  30582. /**
  30583. * The value size.
  30584. *
  30585. * @type {TypedArray}
  30586. */
  30587. this.valueSize = sampleSize;
  30588. /**
  30589. * The interpolation settings.
  30590. *
  30591. * @type {?Object}
  30592. * @default null
  30593. */
  30594. this.settings = null;
  30595. /**
  30596. * The default settings object.
  30597. *
  30598. * @type {Object}
  30599. */
  30600. this.DefaultSettings_ = {};
  30601. }
  30602. /**
  30603. * Evaluate the interpolant at position `t`.
  30604. *
  30605. * @param {number} t - The interpolation factor.
  30606. * @return {TypedArray} The result buffer.
  30607. */
  30608. evaluate( t ) {
  30609. const pp = this.parameterPositions;
  30610. let i1 = this._cachedIndex,
  30611. t1 = pp[ i1 ],
  30612. t0 = pp[ i1 - 1 ];
  30613. validate_interval: {
  30614. seek: {
  30615. let right;
  30616. linear_scan: {
  30617. //- See http://jsperf.com/comparison-to-undefined/3
  30618. //- slower code:
  30619. //-
  30620. //- if ( t >= t1 || t1 === undefined ) {
  30621. forward_scan: if ( ! ( t < t1 ) ) {
  30622. for ( let giveUpAt = i1 + 2; ; ) {
  30623. if ( t1 === undefined ) {
  30624. if ( t < t0 ) break forward_scan;
  30625. // after end
  30626. i1 = pp.length;
  30627. this._cachedIndex = i1;
  30628. return this.copySampleValue_( i1 - 1 );
  30629. }
  30630. if ( i1 === giveUpAt ) break; // this loop
  30631. t0 = t1;
  30632. t1 = pp[ ++ i1 ];
  30633. if ( t < t1 ) {
  30634. // we have arrived at the sought interval
  30635. break seek;
  30636. }
  30637. }
  30638. // prepare binary search on the right side of the index
  30639. right = pp.length;
  30640. break linear_scan;
  30641. }
  30642. //- slower code:
  30643. //- if ( t < t0 || t0 === undefined ) {
  30644. if ( ! ( t >= t0 ) ) {
  30645. // looping?
  30646. const t1global = pp[ 1 ];
  30647. if ( t < t1global ) {
  30648. i1 = 2; // + 1, using the scan for the details
  30649. t0 = t1global;
  30650. }
  30651. // linear reverse scan
  30652. for ( let giveUpAt = i1 - 2; ; ) {
  30653. if ( t0 === undefined ) {
  30654. // before start
  30655. this._cachedIndex = 0;
  30656. return this.copySampleValue_( 0 );
  30657. }
  30658. if ( i1 === giveUpAt ) break; // this loop
  30659. t1 = t0;
  30660. t0 = pp[ -- i1 - 1 ];
  30661. if ( t >= t0 ) {
  30662. // we have arrived at the sought interval
  30663. break seek;
  30664. }
  30665. }
  30666. // prepare binary search on the left side of the index
  30667. right = i1;
  30668. i1 = 0;
  30669. break linear_scan;
  30670. }
  30671. // the interval is valid
  30672. break validate_interval;
  30673. } // linear scan
  30674. // binary search
  30675. while ( i1 < right ) {
  30676. const mid = ( i1 + right ) >>> 1;
  30677. if ( t < pp[ mid ] ) {
  30678. right = mid;
  30679. } else {
  30680. i1 = mid + 1;
  30681. }
  30682. }
  30683. t1 = pp[ i1 ];
  30684. t0 = pp[ i1 - 1 ];
  30685. // check boundary cases, again
  30686. if ( t0 === undefined ) {
  30687. this._cachedIndex = 0;
  30688. return this.copySampleValue_( 0 );
  30689. }
  30690. if ( t1 === undefined ) {
  30691. i1 = pp.length;
  30692. this._cachedIndex = i1;
  30693. return this.copySampleValue_( i1 - 1 );
  30694. }
  30695. } // seek
  30696. this._cachedIndex = i1;
  30697. this.intervalChanged_( i1, t0, t1 );
  30698. } // validate_interval
  30699. return this.interpolate_( i1, t0, t, t1 );
  30700. }
  30701. /**
  30702. * Returns the interpolation settings.
  30703. *
  30704. * @return {Object} The interpolation settings.
  30705. */
  30706. getSettings_() {
  30707. return this.settings || this.DefaultSettings_;
  30708. }
  30709. /**
  30710. * Copies a sample value to the result buffer.
  30711. *
  30712. * @param {number} index - An index into the sample value buffer.
  30713. * @return {TypedArray} The result buffer.
  30714. */
  30715. copySampleValue_( index ) {
  30716. // copies a sample value to the result buffer
  30717. const result = this.resultBuffer,
  30718. values = this.sampleValues,
  30719. stride = this.valueSize,
  30720. offset = index * stride;
  30721. for ( let i = 0; i !== stride; ++ i ) {
  30722. result[ i ] = values[ offset + i ];
  30723. }
  30724. return result;
  30725. }
  30726. /**
  30727. * Copies a sample value to the result buffer.
  30728. *
  30729. * @abstract
  30730. * @param {number} i1 - An index into the sample value buffer.
  30731. * @param {number} t0 - The previous interpolation factor.
  30732. * @param {number} t - The current interpolation factor.
  30733. * @param {number} t1 - The next interpolation factor.
  30734. * @return {TypedArray} The result buffer.
  30735. */
  30736. interpolate_( /* i1, t0, t, t1 */ ) {
  30737. throw new Error( 'call to abstract method' );
  30738. // implementations shall return this.resultBuffer
  30739. }
  30740. /**
  30741. * Optional method that is executed when the interval has changed.
  30742. *
  30743. * @param {number} i1 - An index into the sample value buffer.
  30744. * @param {number} t0 - The previous interpolation factor.
  30745. * @param {number} t - The current interpolation factor.
  30746. */
  30747. intervalChanged_( /* i1, t0, t1 */ ) {
  30748. // empty
  30749. }
  30750. }
  30751. /**
  30752. * Fast and simple cubic spline interpolant.
  30753. *
  30754. * It was derived from a Hermitian construction setting the first derivative
  30755. * at each sample position to the linear slope between neighboring positions
  30756. * over their parameter interval.
  30757. *
  30758. * @augments Interpolant
  30759. */
  30760. class CubicInterpolant extends Interpolant {
  30761. /**
  30762. * Constructs a new cubic interpolant.
  30763. *
  30764. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30765. * @param {TypedArray} sampleValues - The sample values.
  30766. * @param {number} sampleSize - The sample size
  30767. * @param {TypedArray} [resultBuffer] - The result buffer.
  30768. */
  30769. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30770. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30771. this._weightPrev = -0;
  30772. this._offsetPrev = -0;
  30773. this._weightNext = -0;
  30774. this._offsetNext = -0;
  30775. this.DefaultSettings_ = {
  30776. endingStart: ZeroCurvatureEnding,
  30777. endingEnd: ZeroCurvatureEnding
  30778. };
  30779. }
  30780. intervalChanged_( i1, t0, t1 ) {
  30781. const pp = this.parameterPositions;
  30782. let iPrev = i1 - 2,
  30783. iNext = i1 + 1,
  30784. tPrev = pp[ iPrev ],
  30785. tNext = pp[ iNext ];
  30786. if ( tPrev === undefined ) {
  30787. switch ( this.getSettings_().endingStart ) {
  30788. case ZeroSlopeEnding:
  30789. // f'(t0) = 0
  30790. iPrev = i1;
  30791. tPrev = 2 * t0 - t1;
  30792. break;
  30793. case WrapAroundEnding:
  30794. // use the other end of the curve
  30795. iPrev = pp.length - 2;
  30796. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  30797. break;
  30798. default: // ZeroCurvatureEnding
  30799. // f''(t0) = 0 a.k.a. Natural Spline
  30800. iPrev = i1;
  30801. tPrev = t1;
  30802. }
  30803. }
  30804. if ( tNext === undefined ) {
  30805. switch ( this.getSettings_().endingEnd ) {
  30806. case ZeroSlopeEnding:
  30807. // f'(tN) = 0
  30808. iNext = i1;
  30809. tNext = 2 * t1 - t0;
  30810. break;
  30811. case WrapAroundEnding:
  30812. // use the other end of the curve
  30813. iNext = 1;
  30814. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  30815. break;
  30816. default: // ZeroCurvatureEnding
  30817. // f''(tN) = 0, a.k.a. Natural Spline
  30818. iNext = i1 - 1;
  30819. tNext = t0;
  30820. }
  30821. }
  30822. const halfDt = ( t1 - t0 ) * 0.5,
  30823. stride = this.valueSize;
  30824. this._weightPrev = halfDt / ( t0 - tPrev );
  30825. this._weightNext = halfDt / ( tNext - t1 );
  30826. this._offsetPrev = iPrev * stride;
  30827. this._offsetNext = iNext * stride;
  30828. }
  30829. interpolate_( i1, t0, t, t1 ) {
  30830. const result = this.resultBuffer,
  30831. values = this.sampleValues,
  30832. stride = this.valueSize,
  30833. o1 = i1 * stride, o0 = o1 - stride,
  30834. oP = this._offsetPrev, oN = this._offsetNext,
  30835. wP = this._weightPrev, wN = this._weightNext,
  30836. p = ( t - t0 ) / ( t1 - t0 ),
  30837. pp = p * p,
  30838. ppp = pp * p;
  30839. // evaluate polynomials
  30840. const sP = - wP * ppp + 2 * wP * pp - wP * p;
  30841. const s0 = ( 1 + wP ) * ppp + ( -1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  30842. const s1 = ( -1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  30843. const sN = wN * ppp - wN * pp;
  30844. // combine data linearly
  30845. for ( let i = 0; i !== stride; ++ i ) {
  30846. result[ i ] =
  30847. sP * values[ oP + i ] +
  30848. s0 * values[ o0 + i ] +
  30849. s1 * values[ o1 + i ] +
  30850. sN * values[ oN + i ];
  30851. }
  30852. return result;
  30853. }
  30854. }
  30855. /**
  30856. * A basic linear interpolant.
  30857. *
  30858. * @augments Interpolant
  30859. */
  30860. class LinearInterpolant extends Interpolant {
  30861. /**
  30862. * Constructs a new linear interpolant.
  30863. *
  30864. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30865. * @param {TypedArray} sampleValues - The sample values.
  30866. * @param {number} sampleSize - The sample size
  30867. * @param {TypedArray} [resultBuffer] - The result buffer.
  30868. */
  30869. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30870. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30871. }
  30872. interpolate_( i1, t0, t, t1 ) {
  30873. const result = this.resultBuffer,
  30874. values = this.sampleValues,
  30875. stride = this.valueSize,
  30876. offset1 = i1 * stride,
  30877. offset0 = offset1 - stride,
  30878. weight1 = ( t - t0 ) / ( t1 - t0 ),
  30879. weight0 = 1 - weight1;
  30880. for ( let i = 0; i !== stride; ++ i ) {
  30881. result[ i ] =
  30882. values[ offset0 + i ] * weight0 +
  30883. values[ offset1 + i ] * weight1;
  30884. }
  30885. return result;
  30886. }
  30887. }
  30888. /**
  30889. * Interpolant that evaluates to the sample value at the position preceding
  30890. * the parameter.
  30891. *
  30892. * @augments Interpolant
  30893. */
  30894. class DiscreteInterpolant extends Interpolant {
  30895. /**
  30896. * Constructs a new discrete interpolant.
  30897. *
  30898. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  30899. * @param {TypedArray} sampleValues - The sample values.
  30900. * @param {number} sampleSize - The sample size
  30901. * @param {TypedArray} [resultBuffer] - The result buffer.
  30902. */
  30903. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  30904. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  30905. }
  30906. interpolate_( i1 /*, t0, t, t1 */ ) {
  30907. return this.copySampleValue_( i1 - 1 );
  30908. }
  30909. }
  30910. /**
  30911. * Represents s a timed sequence of keyframes, which are composed of lists of
  30912. * times and related values, and which are used to animate a specific property
  30913. * of an object.
  30914. */
  30915. class KeyframeTrack {
  30916. /**
  30917. * Constructs a new keyframe track.
  30918. *
  30919. * @param {string} name - The keyframe track's name.
  30920. * @param {Array<number>} times - A list of keyframe times.
  30921. * @param {Array<number|string|boolean>} values - A list of keyframe values.
  30922. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  30923. */
  30924. constructor( name, times, values, interpolation ) {
  30925. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  30926. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  30927. /**
  30928. * The track's name can refer to morph targets or bones or
  30929. * possibly other values within an animated object. See {@link PropertyBinding#parseTrackName}
  30930. * for the forms of strings that can be parsed for property binding.
  30931. *
  30932. * @type {string}
  30933. */
  30934. this.name = name;
  30935. /**
  30936. * The keyframe times.
  30937. *
  30938. * @type {Float32Array}
  30939. */
  30940. this.times = convertArray( times, this.TimeBufferType );
  30941. /**
  30942. * The keyframe values.
  30943. *
  30944. * @type {Float32Array}
  30945. */
  30946. this.values = convertArray( values, this.ValueBufferType );
  30947. this.setInterpolation( interpolation || this.DefaultInterpolation );
  30948. }
  30949. /**
  30950. * Converts the keyframe track to JSON.
  30951. *
  30952. * @static
  30953. * @param {KeyframeTrack} track - The keyframe track to serialize.
  30954. * @return {Object} The serialized keyframe track as JSON.
  30955. */
  30956. static toJSON( track ) {
  30957. const trackType = track.constructor;
  30958. let json;
  30959. // derived classes can define a static toJSON method
  30960. if ( trackType.toJSON !== this.toJSON ) {
  30961. json = trackType.toJSON( track );
  30962. } else {
  30963. // by default, we assume the data can be serialized as-is
  30964. json = {
  30965. 'name': track.name,
  30966. 'times': convertArray( track.times, Array ),
  30967. 'values': convertArray( track.values, Array )
  30968. };
  30969. const interpolation = track.getInterpolation();
  30970. if ( interpolation !== track.DefaultInterpolation ) {
  30971. json.interpolation = interpolation;
  30972. }
  30973. }
  30974. json.type = track.ValueTypeName; // mandatory
  30975. return json;
  30976. }
  30977. /**
  30978. * Factory method for creating a new discrete interpolant.
  30979. *
  30980. * @static
  30981. * @param {TypedArray} [result] - The result buffer.
  30982. * @return {DiscreteInterpolant} The new interpolant.
  30983. */
  30984. InterpolantFactoryMethodDiscrete( result ) {
  30985. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  30986. }
  30987. /**
  30988. * Factory method for creating a new linear interpolant.
  30989. *
  30990. * @static
  30991. * @param {TypedArray} [result] - The result buffer.
  30992. * @return {LinearInterpolant} The new interpolant.
  30993. */
  30994. InterpolantFactoryMethodLinear( result ) {
  30995. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  30996. }
  30997. /**
  30998. * Factory method for creating a new smooth interpolant.
  30999. *
  31000. * @static
  31001. * @param {TypedArray} [result] - The result buffer.
  31002. * @return {CubicInterpolant} The new interpolant.
  31003. */
  31004. InterpolantFactoryMethodSmooth( result ) {
  31005. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  31006. }
  31007. /**
  31008. * Defines the interpolation factor method for this keyframe track.
  31009. *
  31010. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} interpolation - The interpolation type.
  31011. * @return {KeyframeTrack} A reference to this keyframe track.
  31012. */
  31013. setInterpolation( interpolation ) {
  31014. let factoryMethod;
  31015. switch ( interpolation ) {
  31016. case InterpolateDiscrete:
  31017. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  31018. break;
  31019. case InterpolateLinear:
  31020. factoryMethod = this.InterpolantFactoryMethodLinear;
  31021. break;
  31022. case InterpolateSmooth:
  31023. factoryMethod = this.InterpolantFactoryMethodSmooth;
  31024. break;
  31025. }
  31026. if ( factoryMethod === undefined ) {
  31027. const message = 'unsupported interpolation for ' +
  31028. this.ValueTypeName + ' keyframe track named ' + this.name;
  31029. if ( this.createInterpolant === undefined ) {
  31030. // fall back to default, unless the default itself is messed up
  31031. if ( interpolation !== this.DefaultInterpolation ) {
  31032. this.setInterpolation( this.DefaultInterpolation );
  31033. } else {
  31034. throw new Error( message ); // fatal, in this case
  31035. }
  31036. }
  31037. warn( 'KeyframeTrack:', message );
  31038. return this;
  31039. }
  31040. this.createInterpolant = factoryMethod;
  31041. return this;
  31042. }
  31043. /**
  31044. * Returns the current interpolation type.
  31045. *
  31046. * @return {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} The interpolation type.
  31047. */
  31048. getInterpolation() {
  31049. switch ( this.createInterpolant ) {
  31050. case this.InterpolantFactoryMethodDiscrete:
  31051. return InterpolateDiscrete;
  31052. case this.InterpolantFactoryMethodLinear:
  31053. return InterpolateLinear;
  31054. case this.InterpolantFactoryMethodSmooth:
  31055. return InterpolateSmooth;
  31056. }
  31057. }
  31058. /**
  31059. * Returns the value size.
  31060. *
  31061. * @return {number} The value size.
  31062. */
  31063. getValueSize() {
  31064. return this.values.length / this.times.length;
  31065. }
  31066. /**
  31067. * Moves all keyframes either forward or backward in time.
  31068. *
  31069. * @param {number} timeOffset - The offset to move the time values.
  31070. * @return {KeyframeTrack} A reference to this keyframe track.
  31071. */
  31072. shift( timeOffset ) {
  31073. if ( timeOffset !== 0.0 ) {
  31074. const times = this.times;
  31075. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31076. times[ i ] += timeOffset;
  31077. }
  31078. }
  31079. return this;
  31080. }
  31081. /**
  31082. * Scale all keyframe times by a factor (useful for frame - seconds conversions).
  31083. *
  31084. * @param {number} timeScale - The time scale.
  31085. * @return {KeyframeTrack} A reference to this keyframe track.
  31086. */
  31087. scale( timeScale ) {
  31088. if ( timeScale !== 1.0 ) {
  31089. const times = this.times;
  31090. for ( let i = 0, n = times.length; i !== n; ++ i ) {
  31091. times[ i ] *= timeScale;
  31092. }
  31093. }
  31094. return this;
  31095. }
  31096. /**
  31097. * Removes keyframes before and after animation without changing any values within the defined time range.
  31098. *
  31099. * Note: The method does not shift around keys to the start of the track time, because for interpolated
  31100. * keys this will change their values
  31101. *
  31102. * @param {number} startTime - The start time.
  31103. * @param {number} endTime - The end time.
  31104. * @return {KeyframeTrack} A reference to this keyframe track.
  31105. */
  31106. trim( startTime, endTime ) {
  31107. const times = this.times,
  31108. nKeys = times.length;
  31109. let from = 0,
  31110. to = nKeys - 1;
  31111. while ( from !== nKeys && times[ from ] < startTime ) {
  31112. ++ from;
  31113. }
  31114. while ( to !== -1 && times[ to ] > endTime ) {
  31115. -- to;
  31116. }
  31117. ++ to; // inclusive -> exclusive bound
  31118. if ( from !== 0 || to !== nKeys ) {
  31119. // empty tracks are forbidden, so keep at least one keyframe
  31120. if ( from >= to ) {
  31121. to = Math.max( to, 1 );
  31122. from = to - 1;
  31123. }
  31124. const stride = this.getValueSize();
  31125. this.times = times.slice( from, to );
  31126. this.values = this.values.slice( from * stride, to * stride );
  31127. }
  31128. return this;
  31129. }
  31130. /**
  31131. * Performs minimal validation on the keyframe track. Returns `true` if the values
  31132. * are valid.
  31133. *
  31134. * @return {boolean} Whether the keyframes are valid or not.
  31135. */
  31136. validate() {
  31137. let valid = true;
  31138. const valueSize = this.getValueSize();
  31139. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  31140. error( 'KeyframeTrack: Invalid value size in track.', this );
  31141. valid = false;
  31142. }
  31143. const times = this.times,
  31144. values = this.values,
  31145. nKeys = times.length;
  31146. if ( nKeys === 0 ) {
  31147. error( 'KeyframeTrack: Track is empty.', this );
  31148. valid = false;
  31149. }
  31150. let prevTime = null;
  31151. for ( let i = 0; i !== nKeys; i ++ ) {
  31152. const currTime = times[ i ];
  31153. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  31154. error( 'KeyframeTrack: Time is not a valid number.', this, i, currTime );
  31155. valid = false;
  31156. break;
  31157. }
  31158. if ( prevTime !== null && prevTime > currTime ) {
  31159. error( 'KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  31160. valid = false;
  31161. break;
  31162. }
  31163. prevTime = currTime;
  31164. }
  31165. if ( values !== undefined ) {
  31166. if ( isTypedArray( values ) ) {
  31167. for ( let i = 0, n = values.length; i !== n; ++ i ) {
  31168. const value = values[ i ];
  31169. if ( isNaN( value ) ) {
  31170. error( 'KeyframeTrack: Value is not a valid number.', this, i, value );
  31171. valid = false;
  31172. break;
  31173. }
  31174. }
  31175. }
  31176. }
  31177. return valid;
  31178. }
  31179. /**
  31180. * Optimizes this keyframe track by removing equivalent sequential keys (which are
  31181. * common in morph target sequences).
  31182. *
  31183. * @return {AnimationClip} A reference to this animation clip.
  31184. */
  31185. optimize() {
  31186. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  31187. // times or values may be shared with other tracks, so overwriting is unsafe
  31188. const times = this.times.slice(),
  31189. values = this.values.slice(),
  31190. stride = this.getValueSize(),
  31191. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  31192. lastIndex = times.length - 1;
  31193. let writeIndex = 1;
  31194. for ( let i = 1; i < lastIndex; ++ i ) {
  31195. let keep = false;
  31196. const time = times[ i ];
  31197. const timeNext = times[ i + 1 ];
  31198. // remove adjacent keyframes scheduled at the same time
  31199. if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
  31200. if ( ! smoothInterpolation ) {
  31201. // remove unnecessary keyframes same as their neighbors
  31202. const offset = i * stride,
  31203. offsetP = offset - stride,
  31204. offsetN = offset + stride;
  31205. for ( let j = 0; j !== stride; ++ j ) {
  31206. const value = values[ offset + j ];
  31207. if ( value !== values[ offsetP + j ] ||
  31208. value !== values[ offsetN + j ] ) {
  31209. keep = true;
  31210. break;
  31211. }
  31212. }
  31213. } else {
  31214. keep = true;
  31215. }
  31216. }
  31217. // in-place compaction
  31218. if ( keep ) {
  31219. if ( i !== writeIndex ) {
  31220. times[ writeIndex ] = times[ i ];
  31221. const readOffset = i * stride,
  31222. writeOffset = writeIndex * stride;
  31223. for ( let j = 0; j !== stride; ++ j ) {
  31224. values[ writeOffset + j ] = values[ readOffset + j ];
  31225. }
  31226. }
  31227. ++ writeIndex;
  31228. }
  31229. }
  31230. // flush last keyframe (compaction looks ahead)
  31231. if ( lastIndex > 0 ) {
  31232. times[ writeIndex ] = times[ lastIndex ];
  31233. for ( let readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  31234. values[ writeOffset + j ] = values[ readOffset + j ];
  31235. }
  31236. ++ writeIndex;
  31237. }
  31238. if ( writeIndex !== times.length ) {
  31239. this.times = times.slice( 0, writeIndex );
  31240. this.values = values.slice( 0, writeIndex * stride );
  31241. } else {
  31242. this.times = times;
  31243. this.values = values;
  31244. }
  31245. return this;
  31246. }
  31247. /**
  31248. * Returns a new keyframe track with copied values from this instance.
  31249. *
  31250. * @return {KeyframeTrack} A clone of this instance.
  31251. */
  31252. clone() {
  31253. const times = this.times.slice();
  31254. const values = this.values.slice();
  31255. const TypedKeyframeTrack = this.constructor;
  31256. const track = new TypedKeyframeTrack( this.name, times, values );
  31257. // Interpolant argument to constructor is not saved, so copy the factory method directly.
  31258. track.createInterpolant = this.createInterpolant;
  31259. return track;
  31260. }
  31261. }
  31262. /**
  31263. * The value type name.
  31264. *
  31265. * @type {String}
  31266. * @default ''
  31267. */
  31268. KeyframeTrack.prototype.ValueTypeName = '';
  31269. /**
  31270. * The time buffer type of this keyframe track.
  31271. *
  31272. * @type {TypedArray|Array}
  31273. * @default Float32Array.constructor
  31274. */
  31275. KeyframeTrack.prototype.TimeBufferType = Float32Array;
  31276. /**
  31277. * The value buffer type of this keyframe track.
  31278. *
  31279. * @type {TypedArray|Array}
  31280. * @default Float32Array.constructor
  31281. */
  31282. KeyframeTrack.prototype.ValueBufferType = Float32Array;
  31283. /**
  31284. * The default interpolation type of this keyframe track.
  31285. *
  31286. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31287. * @default InterpolateLinear
  31288. */
  31289. KeyframeTrack.prototype.DefaultInterpolation = InterpolateLinear;
  31290. /**
  31291. * A track for boolean keyframe values.
  31292. *
  31293. * @augments KeyframeTrack
  31294. */
  31295. class BooleanKeyframeTrack extends KeyframeTrack {
  31296. /**
  31297. * Constructs a new boolean keyframe track.
  31298. *
  31299. * This keyframe track type has no `interpolation` parameter because the
  31300. * interpolation is always discrete.
  31301. *
  31302. * @param {string} name - The keyframe track's name.
  31303. * @param {Array<number>} times - A list of keyframe times.
  31304. * @param {Array<boolean>} values - A list of keyframe values.
  31305. */
  31306. constructor( name, times, values ) {
  31307. super( name, times, values );
  31308. }
  31309. }
  31310. /**
  31311. * The value type name.
  31312. *
  31313. * @type {String}
  31314. * @default 'bool'
  31315. */
  31316. BooleanKeyframeTrack.prototype.ValueTypeName = 'bool';
  31317. /**
  31318. * The value buffer type of this keyframe track.
  31319. *
  31320. * @type {TypedArray|Array}
  31321. * @default Array.constructor
  31322. */
  31323. BooleanKeyframeTrack.prototype.ValueBufferType = Array;
  31324. /**
  31325. * The default interpolation type of this keyframe track.
  31326. *
  31327. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31328. * @default InterpolateDiscrete
  31329. */
  31330. BooleanKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31331. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31332. BooleanKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31333. /**
  31334. * A track for color keyframe values.
  31335. *
  31336. * @augments KeyframeTrack
  31337. */
  31338. class ColorKeyframeTrack extends KeyframeTrack {
  31339. /**
  31340. * Constructs a new color keyframe track.
  31341. *
  31342. * @param {string} name - The keyframe track's name.
  31343. * @param {Array<number>} times - A list of keyframe times.
  31344. * @param {Array<number>} values - A list of keyframe values.
  31345. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31346. */
  31347. constructor( name, times, values, interpolation ) {
  31348. super( name, times, values, interpolation );
  31349. }
  31350. }
  31351. /**
  31352. * The value type name.
  31353. *
  31354. * @type {String}
  31355. * @default 'color'
  31356. */
  31357. ColorKeyframeTrack.prototype.ValueTypeName = 'color';
  31358. /**
  31359. * A track for numeric keyframe values.
  31360. *
  31361. * @augments KeyframeTrack
  31362. */
  31363. class NumberKeyframeTrack extends KeyframeTrack {
  31364. /**
  31365. * Constructs a new number keyframe track.
  31366. *
  31367. * @param {string} name - The keyframe track's name.
  31368. * @param {Array<number>} times - A list of keyframe times.
  31369. * @param {Array<number>} values - A list of keyframe values.
  31370. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31371. */
  31372. constructor( name, times, values, interpolation ) {
  31373. super( name, times, values, interpolation );
  31374. }
  31375. }
  31376. /**
  31377. * The value type name.
  31378. *
  31379. * @type {String}
  31380. * @default 'number'
  31381. */
  31382. NumberKeyframeTrack.prototype.ValueTypeName = 'number';
  31383. /**
  31384. * Spherical linear unit quaternion interpolant.
  31385. *
  31386. * @augments Interpolant
  31387. */
  31388. class QuaternionLinearInterpolant extends Interpolant {
  31389. /**
  31390. * Constructs a new SLERP interpolant.
  31391. *
  31392. * @param {TypedArray} parameterPositions - The parameter positions hold the interpolation factors.
  31393. * @param {TypedArray} sampleValues - The sample values.
  31394. * @param {number} sampleSize - The sample size
  31395. * @param {TypedArray} [resultBuffer] - The result buffer.
  31396. */
  31397. constructor( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  31398. super( parameterPositions, sampleValues, sampleSize, resultBuffer );
  31399. }
  31400. interpolate_( i1, t0, t, t1 ) {
  31401. const result = this.resultBuffer,
  31402. values = this.sampleValues,
  31403. stride = this.valueSize,
  31404. alpha = ( t - t0 ) / ( t1 - t0 );
  31405. let offset = i1 * stride;
  31406. for ( let end = offset + stride; offset !== end; offset += 4 ) {
  31407. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  31408. }
  31409. return result;
  31410. }
  31411. }
  31412. /**
  31413. * A track for Quaternion keyframe values.
  31414. *
  31415. * @augments KeyframeTrack
  31416. */
  31417. class QuaternionKeyframeTrack extends KeyframeTrack {
  31418. /**
  31419. * Constructs a new Quaternion keyframe track.
  31420. *
  31421. * @param {string} name - The keyframe track's name.
  31422. * @param {Array<number>} times - A list of keyframe times.
  31423. * @param {Array<number>} values - A list of keyframe values.
  31424. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31425. */
  31426. constructor( name, times, values, interpolation ) {
  31427. super( name, times, values, interpolation );
  31428. }
  31429. /**
  31430. * Overwritten so the method returns Quaternion based interpolant.
  31431. *
  31432. * @static
  31433. * @param {TypedArray} [result] - The result buffer.
  31434. * @return {QuaternionLinearInterpolant} The new interpolant.
  31435. */
  31436. InterpolantFactoryMethodLinear( result ) {
  31437. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  31438. }
  31439. }
  31440. /**
  31441. * The value type name.
  31442. *
  31443. * @type {String}
  31444. * @default 'quaternion'
  31445. */
  31446. QuaternionKeyframeTrack.prototype.ValueTypeName = 'quaternion';
  31447. // ValueBufferType is inherited
  31448. // DefaultInterpolation is inherited;
  31449. QuaternionKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31450. /**
  31451. * A track for string keyframe values.
  31452. *
  31453. * @augments KeyframeTrack
  31454. */
  31455. class StringKeyframeTrack extends KeyframeTrack {
  31456. /**
  31457. * Constructs a new string keyframe track.
  31458. *
  31459. * This keyframe track type has no `interpolation` parameter because the
  31460. * interpolation is always discrete.
  31461. *
  31462. * @param {string} name - The keyframe track's name.
  31463. * @param {Array<number>} times - A list of keyframe times.
  31464. * @param {Array<string>} values - A list of keyframe values.
  31465. */
  31466. constructor( name, times, values ) {
  31467. super( name, times, values );
  31468. }
  31469. }
  31470. /**
  31471. * The value type name.
  31472. *
  31473. * @type {String}
  31474. * @default 'string'
  31475. */
  31476. StringKeyframeTrack.prototype.ValueTypeName = 'string';
  31477. /**
  31478. * The value buffer type of this keyframe track.
  31479. *
  31480. * @type {TypedArray|Array}
  31481. * @default Array.constructor
  31482. */
  31483. StringKeyframeTrack.prototype.ValueBufferType = Array;
  31484. /**
  31485. * The default interpolation type of this keyframe track.
  31486. *
  31487. * @type {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)}
  31488. * @default InterpolateDiscrete
  31489. */
  31490. StringKeyframeTrack.prototype.DefaultInterpolation = InterpolateDiscrete;
  31491. StringKeyframeTrack.prototype.InterpolantFactoryMethodLinear = undefined;
  31492. StringKeyframeTrack.prototype.InterpolantFactoryMethodSmooth = undefined;
  31493. /**
  31494. * A track for vector keyframe values.
  31495. *
  31496. * @augments KeyframeTrack
  31497. */
  31498. class VectorKeyframeTrack extends KeyframeTrack {
  31499. /**
  31500. * Constructs a new vector keyframe track.
  31501. *
  31502. * @param {string} name - The keyframe track's name.
  31503. * @param {Array<number>} times - A list of keyframe times.
  31504. * @param {Array<number>} values - A list of keyframe values.
  31505. * @param {(InterpolateLinear|InterpolateDiscrete|InterpolateSmooth)} [interpolation] - The interpolation type.
  31506. */
  31507. constructor( name, times, values, interpolation ) {
  31508. super( name, times, values, interpolation );
  31509. }
  31510. }
  31511. /**
  31512. * The value type name.
  31513. *
  31514. * @type {String}
  31515. * @default 'vector'
  31516. */
  31517. VectorKeyframeTrack.prototype.ValueTypeName = 'vector';
  31518. /**
  31519. * A reusable set of keyframe tracks which represent an animation.
  31520. */
  31521. class AnimationClip {
  31522. /**
  31523. * Constructs a new animation clip.
  31524. *
  31525. * Note: Instead of instantiating an AnimationClip directly with the constructor, you can
  31526. * use the static interface of this class for creating clips. In most cases though, animation clips
  31527. * will automatically be created by loaders when importing animated 3D assets.
  31528. *
  31529. * @param {string} [name=''] - The clip's name.
  31530. * @param {number} [duration=-1] - The clip's duration in seconds. If a negative value is passed,
  31531. * the duration will be calculated from the passed keyframes.
  31532. * @param {Array<KeyframeTrack>} tracks - An array of keyframe tracks.
  31533. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode=NormalAnimationBlendMode] - Defines how the animation
  31534. * is blended/combined when two or more animations are simultaneously played.
  31535. */
  31536. constructor( name = '', duration = -1, tracks = [], blendMode = NormalAnimationBlendMode ) {
  31537. /**
  31538. * The clip's name.
  31539. *
  31540. * @type {string}
  31541. */
  31542. this.name = name;
  31543. /**
  31544. * An array of keyframe tracks.
  31545. *
  31546. * @type {Array<KeyframeTrack>}
  31547. */
  31548. this.tracks = tracks;
  31549. /**
  31550. * The clip's duration in seconds.
  31551. *
  31552. * @type {number}
  31553. */
  31554. this.duration = duration;
  31555. /**
  31556. * Defines how the animation is blended/combined when two or more animations
  31557. * are simultaneously played.
  31558. *
  31559. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  31560. */
  31561. this.blendMode = blendMode;
  31562. /**
  31563. * The UUID of the animation clip.
  31564. *
  31565. * @type {string}
  31566. * @readonly
  31567. */
  31568. this.uuid = generateUUID();
  31569. /**
  31570. * An object that can be used to store custom data about the animation clip.
  31571. * It should not hold references to functions as these will not be cloned.
  31572. *
  31573. * @type {Object}
  31574. */
  31575. this.userData = {};
  31576. // this means it should figure out its duration by scanning the tracks
  31577. if ( this.duration < 0 ) {
  31578. this.resetDuration();
  31579. }
  31580. }
  31581. /**
  31582. * Factory method for creating an animation clip from the given JSON.
  31583. *
  31584. * @static
  31585. * @param {Object} json - The serialized animation clip.
  31586. * @return {AnimationClip} The new animation clip.
  31587. */
  31588. static parse( json ) {
  31589. const tracks = [],
  31590. jsonTracks = json.tracks,
  31591. frameTime = 1.0 / ( json.fps || 1.0 );
  31592. for ( let i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  31593. tracks.push( parseKeyframeTrack( jsonTracks[ i ] ).scale( frameTime ) );
  31594. }
  31595. const clip = new this( json.name, json.duration, tracks, json.blendMode );
  31596. clip.uuid = json.uuid;
  31597. clip.userData = JSON.parse( json.userData || '{}' );
  31598. return clip;
  31599. }
  31600. /**
  31601. * Serializes the given animation clip into JSON.
  31602. *
  31603. * @static
  31604. * @param {AnimationClip} clip - The animation clip to serialize.
  31605. * @return {Object} The JSON object.
  31606. */
  31607. static toJSON( clip ) {
  31608. const tracks = [],
  31609. clipTracks = clip.tracks;
  31610. const json = {
  31611. 'name': clip.name,
  31612. 'duration': clip.duration,
  31613. 'tracks': tracks,
  31614. 'uuid': clip.uuid,
  31615. 'blendMode': clip.blendMode,
  31616. 'userData': JSON.stringify( clip.userData ),
  31617. };
  31618. for ( let i = 0, n = clipTracks.length; i !== n; ++ i ) {
  31619. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  31620. }
  31621. return json;
  31622. }
  31623. /**
  31624. * Returns a new animation clip from the passed morph targets array of a
  31625. * geometry, taking a name and the number of frames per second.
  31626. *
  31627. * Note: The fps parameter is required, but the animation speed can be
  31628. * overridden via {@link AnimationAction#setDuration}.
  31629. *
  31630. * @static
  31631. * @param {string} name - The name of the animation clip.
  31632. * @param {Array<Object>} morphTargetSequence - A sequence of morph targets.
  31633. * @param {number} fps - The Frames-Per-Second value.
  31634. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31635. * @return {AnimationClip} The new animation clip.
  31636. */
  31637. static CreateFromMorphTargetSequence( name, morphTargetSequence, fps, noLoop ) {
  31638. const numMorphTargets = morphTargetSequence.length;
  31639. const tracks = [];
  31640. for ( let i = 0; i < numMorphTargets; i ++ ) {
  31641. let times = [];
  31642. let values = [];
  31643. times.push(
  31644. ( i + numMorphTargets - 1 ) % numMorphTargets,
  31645. i,
  31646. ( i + 1 ) % numMorphTargets );
  31647. values.push( 0, 1, 0 );
  31648. const order = getKeyframeOrder( times );
  31649. times = sortedArray( times, 1, order );
  31650. values = sortedArray( values, 1, order );
  31651. // if there is a key at the first frame, duplicate it as the
  31652. // last frame as well for perfect loop.
  31653. if ( ! noLoop && times[ 0 ] === 0 ) {
  31654. times.push( numMorphTargets );
  31655. values.push( values[ 0 ] );
  31656. }
  31657. tracks.push(
  31658. new NumberKeyframeTrack(
  31659. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  31660. times, values
  31661. ).scale( 1.0 / fps ) );
  31662. }
  31663. return new this( name, -1, tracks );
  31664. }
  31665. /**
  31666. * Searches for an animation clip by name, taking as its first parameter
  31667. * either an array of clips, or a mesh or geometry that contains an
  31668. * array named "animations" property.
  31669. *
  31670. * @static
  31671. * @param {(Array<AnimationClip>|Object3D)} objectOrClipArray - The array or object to search through.
  31672. * @param {string} name - The name to search for.
  31673. * @return {?AnimationClip} The found animation clip. Returns `null` if no clip has been found.
  31674. */
  31675. static findByName( objectOrClipArray, name ) {
  31676. let clipArray = objectOrClipArray;
  31677. if ( ! Array.isArray( objectOrClipArray ) ) {
  31678. const o = objectOrClipArray;
  31679. clipArray = o.geometry && o.geometry.animations || o.animations;
  31680. }
  31681. for ( let i = 0; i < clipArray.length; i ++ ) {
  31682. if ( clipArray[ i ].name === name ) {
  31683. return clipArray[ i ];
  31684. }
  31685. }
  31686. return null;
  31687. }
  31688. /**
  31689. * Returns an array of new AnimationClips created from the morph target
  31690. * sequences of a geometry, trying to sort morph target names into
  31691. * animation-group-based patterns like "Walk_001, Walk_002, Run_001, Run_002...".
  31692. *
  31693. * See {@link MD2Loader#parse} as an example for how the method should be used.
  31694. *
  31695. * @static
  31696. * @param {Array<Object>} morphTargets - A sequence of morph targets.
  31697. * @param {number} fps - The Frames-Per-Second value.
  31698. * @param {boolean} noLoop - Whether the clip should be no loop or not.
  31699. * @return {Array<AnimationClip>} An array of new animation clips.
  31700. */
  31701. static CreateClipsFromMorphTargetSequences( morphTargets, fps, noLoop ) {
  31702. const animationToMorphTargets = {};
  31703. // tested with https://regex101.com/ on trick sequences
  31704. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  31705. const pattern = /^([\w-]*?)([\d]+)$/;
  31706. // sort morph target names into animation groups based
  31707. // patterns like Walk_001, Walk_002, Run_001, Run_002
  31708. for ( let i = 0, il = morphTargets.length; i < il; i ++ ) {
  31709. const morphTarget = morphTargets[ i ];
  31710. const parts = morphTarget.name.match( pattern );
  31711. if ( parts && parts.length > 1 ) {
  31712. const name = parts[ 1 ];
  31713. let animationMorphTargets = animationToMorphTargets[ name ];
  31714. if ( ! animationMorphTargets ) {
  31715. animationToMorphTargets[ name ] = animationMorphTargets = [];
  31716. }
  31717. animationMorphTargets.push( morphTarget );
  31718. }
  31719. }
  31720. const clips = [];
  31721. for ( const name in animationToMorphTargets ) {
  31722. clips.push( this.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  31723. }
  31724. return clips;
  31725. }
  31726. /**
  31727. * Parses the `animation.hierarchy` format and returns a new animation clip.
  31728. *
  31729. * @static
  31730. * @deprecated since r175.
  31731. * @param {Object} animation - A serialized animation clip as JSON.
  31732. * @param {Array<Bones>} bones - An array of bones.
  31733. * @return {?AnimationClip} The new animation clip.
  31734. */
  31735. static parseAnimation( animation, bones ) {
  31736. warn( 'AnimationClip: parseAnimation() is deprecated and will be removed with r185' );
  31737. if ( ! animation ) {
  31738. error( 'AnimationClip: No animation in JSONLoader data.' );
  31739. return null;
  31740. }
  31741. const addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  31742. // only return track if there are actually keys.
  31743. if ( animationKeys.length !== 0 ) {
  31744. const times = [];
  31745. const values = [];
  31746. flattenJSON( animationKeys, times, values, propertyName );
  31747. // empty keys are filtered out, so check again
  31748. if ( times.length !== 0 ) {
  31749. destTracks.push( new trackType( trackName, times, values ) );
  31750. }
  31751. }
  31752. };
  31753. const tracks = [];
  31754. const clipName = animation.name || 'default';
  31755. const fps = animation.fps || 30;
  31756. const blendMode = animation.blendMode;
  31757. // automatic length determination in AnimationClip.
  31758. let duration = animation.length || -1;
  31759. const hierarchyTracks = animation.hierarchy || [];
  31760. for ( let h = 0; h < hierarchyTracks.length; h ++ ) {
  31761. const animationKeys = hierarchyTracks[ h ].keys;
  31762. // skip empty tracks
  31763. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  31764. // process morph targets
  31765. if ( animationKeys[ 0 ].morphTargets ) {
  31766. // figure out all morph targets used in this track
  31767. const morphTargetNames = {};
  31768. let k;
  31769. for ( k = 0; k < animationKeys.length; k ++ ) {
  31770. if ( animationKeys[ k ].morphTargets ) {
  31771. for ( let m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  31772. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = -1;
  31773. }
  31774. }
  31775. }
  31776. // create a track for each morph target with all zero
  31777. // morphTargetInfluences except for the keys in which
  31778. // the morphTarget is named.
  31779. for ( const morphTargetName in morphTargetNames ) {
  31780. const times = [];
  31781. const values = [];
  31782. for ( let m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  31783. const animationKey = animationKeys[ k ];
  31784. times.push( animationKey.time );
  31785. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  31786. }
  31787. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  31788. }
  31789. duration = morphTargetNames.length * fps;
  31790. } else {
  31791. // ...assume skeletal animation
  31792. const boneName = '.bones[' + bones[ h ].name + ']';
  31793. addNonemptyTrack(
  31794. VectorKeyframeTrack, boneName + '.position',
  31795. animationKeys, 'pos', tracks );
  31796. addNonemptyTrack(
  31797. QuaternionKeyframeTrack, boneName + '.quaternion',
  31798. animationKeys, 'rot', tracks );
  31799. addNonemptyTrack(
  31800. VectorKeyframeTrack, boneName + '.scale',
  31801. animationKeys, 'scl', tracks );
  31802. }
  31803. }
  31804. if ( tracks.length === 0 ) {
  31805. return null;
  31806. }
  31807. const clip = new this( clipName, duration, tracks, blendMode );
  31808. return clip;
  31809. }
  31810. /**
  31811. * Sets the duration of this clip to the duration of its longest keyframe track.
  31812. *
  31813. * @return {AnimationClip} A reference to this animation clip.
  31814. */
  31815. resetDuration() {
  31816. const tracks = this.tracks;
  31817. let duration = 0;
  31818. for ( let i = 0, n = tracks.length; i !== n; ++ i ) {
  31819. const track = this.tracks[ i ];
  31820. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  31821. }
  31822. this.duration = duration;
  31823. return this;
  31824. }
  31825. /**
  31826. * Trims all tracks to the clip's duration.
  31827. *
  31828. * @return {AnimationClip} A reference to this animation clip.
  31829. */
  31830. trim() {
  31831. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31832. this.tracks[ i ].trim( 0, this.duration );
  31833. }
  31834. return this;
  31835. }
  31836. /**
  31837. * Performs minimal validation on each track in the clip. Returns `true` if all
  31838. * tracks are valid.
  31839. *
  31840. * @return {boolean} Whether the clip's keyframes are valid or not.
  31841. */
  31842. validate() {
  31843. let valid = true;
  31844. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31845. valid = valid && this.tracks[ i ].validate();
  31846. }
  31847. return valid;
  31848. }
  31849. /**
  31850. * Optimizes each track by removing equivalent sequential keys (which are
  31851. * common in morph target sequences).
  31852. *
  31853. * @return {AnimationClip} A reference to this animation clip.
  31854. */
  31855. optimize() {
  31856. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31857. this.tracks[ i ].optimize();
  31858. }
  31859. return this;
  31860. }
  31861. /**
  31862. * Returns a new animation clip with copied values from this instance.
  31863. *
  31864. * @return {AnimationClip} A clone of this instance.
  31865. */
  31866. clone() {
  31867. const tracks = [];
  31868. for ( let i = 0; i < this.tracks.length; i ++ ) {
  31869. tracks.push( this.tracks[ i ].clone() );
  31870. }
  31871. const clip = new this.constructor( this.name, this.duration, tracks, this.blendMode );
  31872. clip.userData = JSON.parse( JSON.stringify( this.userData ) );
  31873. return clip;
  31874. }
  31875. /**
  31876. * Serializes this animation clip into JSON.
  31877. *
  31878. * @return {Object} The JSON object.
  31879. */
  31880. toJSON() {
  31881. return this.constructor.toJSON( this );
  31882. }
  31883. }
  31884. function getTrackTypeForValueTypeName( typeName ) {
  31885. switch ( typeName.toLowerCase() ) {
  31886. case 'scalar':
  31887. case 'double':
  31888. case 'float':
  31889. case 'number':
  31890. case 'integer':
  31891. return NumberKeyframeTrack;
  31892. case 'vector':
  31893. case 'vector2':
  31894. case 'vector3':
  31895. case 'vector4':
  31896. return VectorKeyframeTrack;
  31897. case 'color':
  31898. return ColorKeyframeTrack;
  31899. case 'quaternion':
  31900. return QuaternionKeyframeTrack;
  31901. case 'bool':
  31902. case 'boolean':
  31903. return BooleanKeyframeTrack;
  31904. case 'string':
  31905. return StringKeyframeTrack;
  31906. }
  31907. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  31908. }
  31909. function parseKeyframeTrack( json ) {
  31910. if ( json.type === undefined ) {
  31911. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  31912. }
  31913. const trackType = getTrackTypeForValueTypeName( json.type );
  31914. if ( json.times === undefined ) {
  31915. const times = [], values = [];
  31916. flattenJSON( json.keys, times, values, 'value' );
  31917. json.times = times;
  31918. json.values = values;
  31919. }
  31920. // derived classes can define a static parse method
  31921. if ( trackType.parse !== undefined ) {
  31922. return trackType.parse( json );
  31923. } else {
  31924. // by default, we assume a constructor compatible with the base
  31925. return new trackType( json.name, json.times, json.values, json.interpolation );
  31926. }
  31927. }
  31928. /**
  31929. * @class
  31930. * @classdesc A simple caching system, used internally by {@link FileLoader}.
  31931. * To enable caching across all loaders that use {@link FileLoader}, add `THREE.Cache.enabled = true.` once in your app.
  31932. * @hideconstructor
  31933. */
  31934. const Cache = {
  31935. /**
  31936. * Whether caching is enabled or not.
  31937. *
  31938. * @static
  31939. * @type {boolean}
  31940. * @default false
  31941. */
  31942. enabled: false,
  31943. /**
  31944. * A dictionary that holds cached files.
  31945. *
  31946. * @static
  31947. * @type {Object<string,Object>}
  31948. */
  31949. files: {},
  31950. /**
  31951. * Adds a cache entry with a key to reference the file. If this key already
  31952. * holds a file, it is overwritten.
  31953. *
  31954. * @static
  31955. * @param {string} key - The key to reference the cached file.
  31956. * @param {Object} file - The file to be cached.
  31957. */
  31958. add: function ( key, file ) {
  31959. if ( this.enabled === false ) return;
  31960. // log( 'Cache', 'Adding key:', key );
  31961. this.files[ key ] = file;
  31962. },
  31963. /**
  31964. * Gets the cached value for the given key.
  31965. *
  31966. * @static
  31967. * @param {string} key - The key to reference the cached file.
  31968. * @return {Object|undefined} The cached file. If the key does not exist `undefined` is returned.
  31969. */
  31970. get: function ( key ) {
  31971. if ( this.enabled === false ) return;
  31972. // log( 'Cache', 'Checking key:', key );
  31973. return this.files[ key ];
  31974. },
  31975. /**
  31976. * Removes the cached file associated with the given key.
  31977. *
  31978. * @static
  31979. * @param {string} key - The key to reference the cached file.
  31980. */
  31981. remove: function ( key ) {
  31982. delete this.files[ key ];
  31983. },
  31984. /**
  31985. * Remove all values from the cache.
  31986. *
  31987. * @static
  31988. */
  31989. clear: function () {
  31990. this.files = {};
  31991. }
  31992. };
  31993. /**
  31994. * Handles and keeps track of loaded and pending data. A default global
  31995. * instance of this class is created and used by loaders if not supplied
  31996. * manually.
  31997. *
  31998. * In general that should be sufficient, however there are times when it can
  31999. * be useful to have separate loaders - for example if you want to show
  32000. * separate loading bars for objects and textures.
  32001. *
  32002. * ```js
  32003. * const manager = new THREE.LoadingManager();
  32004. * manager.onLoad = () => console.log( 'Loading complete!' );
  32005. *
  32006. * const loader1 = new OBJLoader( manager );
  32007. * const loader2 = new ColladaLoader( manager );
  32008. * ```
  32009. */
  32010. class LoadingManager {
  32011. /**
  32012. * Constructs a new loading manager.
  32013. *
  32014. * @param {Function} [onLoad] - Executes when all items have been loaded.
  32015. * @param {Function} [onProgress] - Executes when single items have been loaded.
  32016. * @param {Function} [onError] - Executes when an error occurs.
  32017. */
  32018. constructor( onLoad, onProgress, onError ) {
  32019. const scope = this;
  32020. let isLoading = false;
  32021. let itemsLoaded = 0;
  32022. let itemsTotal = 0;
  32023. let urlModifier = undefined;
  32024. const handlers = [];
  32025. // Refer to #5689 for the reason why we don't set .onStart
  32026. // in the constructor
  32027. /**
  32028. * Executes when an item starts loading.
  32029. *
  32030. * @type {Function|undefined}
  32031. * @default undefined
  32032. */
  32033. this.onStart = undefined;
  32034. /**
  32035. * Executes when all items have been loaded.
  32036. *
  32037. * @type {Function|undefined}
  32038. * @default undefined
  32039. */
  32040. this.onLoad = onLoad;
  32041. /**
  32042. * Executes when single items have been loaded.
  32043. *
  32044. * @type {Function|undefined}
  32045. * @default undefined
  32046. */
  32047. this.onProgress = onProgress;
  32048. /**
  32049. * Executes when an error occurs.
  32050. *
  32051. * @type {Function|undefined}
  32052. * @default undefined
  32053. */
  32054. this.onError = onError;
  32055. /**
  32056. * Used for aborting ongoing requests in loaders using this manager.
  32057. *
  32058. * @private
  32059. * @type {AbortController | null}
  32060. */
  32061. this._abortController = null;
  32062. /**
  32063. * This should be called by any loader using the manager when the loader
  32064. * starts loading an item.
  32065. *
  32066. * @param {string} url - The URL to load.
  32067. */
  32068. this.itemStart = function ( url ) {
  32069. itemsTotal ++;
  32070. if ( isLoading === false ) {
  32071. if ( scope.onStart !== undefined ) {
  32072. scope.onStart( url, itemsLoaded, itemsTotal );
  32073. }
  32074. }
  32075. isLoading = true;
  32076. };
  32077. /**
  32078. * This should be called by any loader using the manager when the loader
  32079. * ended loading an item.
  32080. *
  32081. * @param {string} url - The URL of the loaded item.
  32082. */
  32083. this.itemEnd = function ( url ) {
  32084. itemsLoaded ++;
  32085. if ( scope.onProgress !== undefined ) {
  32086. scope.onProgress( url, itemsLoaded, itemsTotal );
  32087. }
  32088. if ( itemsLoaded === itemsTotal ) {
  32089. isLoading = false;
  32090. if ( scope.onLoad !== undefined ) {
  32091. scope.onLoad();
  32092. }
  32093. }
  32094. };
  32095. /**
  32096. * This should be called by any loader using the manager when the loader
  32097. * encounters an error when loading an item.
  32098. *
  32099. * @param {string} url - The URL of the item that produces an error.
  32100. */
  32101. this.itemError = function ( url ) {
  32102. if ( scope.onError !== undefined ) {
  32103. scope.onError( url );
  32104. }
  32105. };
  32106. /**
  32107. * Given a URL, uses the URL modifier callback (if any) and returns a
  32108. * resolved URL. If no URL modifier is set, returns the original URL.
  32109. *
  32110. * @param {string} url - The URL to load.
  32111. * @return {string} The resolved URL.
  32112. */
  32113. this.resolveURL = function ( url ) {
  32114. if ( urlModifier ) {
  32115. return urlModifier( url );
  32116. }
  32117. return url;
  32118. };
  32119. /**
  32120. * If provided, the callback will be passed each resource URL before a
  32121. * request is sent. The callback may return the original URL, or a new URL to
  32122. * override loading behavior. This behavior can be used to load assets from
  32123. * .ZIP files, drag-and-drop APIs, and Data URIs.
  32124. *
  32125. * ```js
  32126. * const blobs = {'fish.gltf': blob1, 'diffuse.png': blob2, 'normal.png': blob3};
  32127. *
  32128. * const manager = new THREE.LoadingManager();
  32129. *
  32130. * // Initialize loading manager with URL callback.
  32131. * const objectURLs = [];
  32132. * manager.setURLModifier( ( url ) => {
  32133. *
  32134. * url = URL.createObjectURL( blobs[ url ] );
  32135. * objectURLs.push( url );
  32136. * return url;
  32137. *
  32138. * } );
  32139. *
  32140. * // Load as usual, then revoke the blob URLs.
  32141. * const loader = new GLTFLoader( manager );
  32142. * loader.load( 'fish.gltf', (gltf) => {
  32143. *
  32144. * scene.add( gltf.scene );
  32145. * objectURLs.forEach( ( url ) => URL.revokeObjectURL( url ) );
  32146. *
  32147. * } );
  32148. * ```
  32149. *
  32150. * @param {function(string):string} transform - URL modifier callback. Called with an URL and must return a resolved URL.
  32151. * @return {LoadingManager} A reference to this loading manager.
  32152. */
  32153. this.setURLModifier = function ( transform ) {
  32154. urlModifier = transform;
  32155. return this;
  32156. };
  32157. /**
  32158. * Registers a loader with the given regular expression. Can be used to
  32159. * define what loader should be used in order to load specific files. A
  32160. * typical use case is to overwrite the default loader for textures.
  32161. *
  32162. * ```js
  32163. * // add handler for TGA textures
  32164. * manager.addHandler( /\.tga$/i, new TGALoader() );
  32165. * ```
  32166. *
  32167. * @param {string} regex - A regular expression.
  32168. * @param {Loader} loader - A loader that should handle matched cases.
  32169. * @return {LoadingManager} A reference to this loading manager.
  32170. */
  32171. this.addHandler = function ( regex, loader ) {
  32172. handlers.push( regex, loader );
  32173. return this;
  32174. };
  32175. /**
  32176. * Removes the loader for the given regular expression.
  32177. *
  32178. * @param {string} regex - A regular expression.
  32179. * @return {LoadingManager} A reference to this loading manager.
  32180. */
  32181. this.removeHandler = function ( regex ) {
  32182. const index = handlers.indexOf( regex );
  32183. if ( index !== -1 ) {
  32184. handlers.splice( index, 2 );
  32185. }
  32186. return this;
  32187. };
  32188. /**
  32189. * Can be used to retrieve the registered loader for the given file path.
  32190. *
  32191. * @param {string} file - The file path.
  32192. * @return {?Loader} The registered loader. Returns `null` if no loader was found.
  32193. */
  32194. this.getHandler = function ( file ) {
  32195. for ( let i = 0, l = handlers.length; i < l; i += 2 ) {
  32196. const regex = handlers[ i ];
  32197. const loader = handlers[ i + 1 ];
  32198. if ( regex.global ) regex.lastIndex = 0; // see #17920
  32199. if ( regex.test( file ) ) {
  32200. return loader;
  32201. }
  32202. }
  32203. return null;
  32204. };
  32205. /**
  32206. * Can be used to abort ongoing loading requests in loaders using this manager.
  32207. * The abort only works if the loaders implement {@link Loader#abort} and `AbortSignal.any()`
  32208. * is supported in the browser.
  32209. *
  32210. * @return {LoadingManager} A reference to this loading manager.
  32211. */
  32212. this.abort = function () {
  32213. this.abortController.abort();
  32214. this._abortController = null;
  32215. return this;
  32216. };
  32217. }
  32218. // TODO: Revert this back to a single member variable once this issue has been fixed
  32219. // https://github.com/cloudflare/workerd/issues/3657
  32220. /**
  32221. * Used for aborting ongoing requests in loaders using this manager.
  32222. *
  32223. * @type {AbortController}
  32224. */
  32225. get abortController() {
  32226. if ( ! this._abortController ) {
  32227. this._abortController = new AbortController();
  32228. }
  32229. return this._abortController;
  32230. }
  32231. }
  32232. /**
  32233. * The global default loading manager.
  32234. *
  32235. * @constant
  32236. * @type {LoadingManager}
  32237. */
  32238. const DefaultLoadingManager = /*@__PURE__*/ new LoadingManager();
  32239. /**
  32240. * Abstract base class for loaders.
  32241. *
  32242. * @abstract
  32243. */
  32244. class Loader {
  32245. /**
  32246. * Constructs a new loader.
  32247. *
  32248. * @param {LoadingManager} [manager] - The loading manager.
  32249. */
  32250. constructor( manager ) {
  32251. /**
  32252. * The loading manager.
  32253. *
  32254. * @type {LoadingManager}
  32255. * @default DefaultLoadingManager
  32256. */
  32257. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  32258. /**
  32259. * The crossOrigin string to implement CORS for loading the url from a
  32260. * different domain that allows CORS.
  32261. *
  32262. * @type {string}
  32263. * @default 'anonymous'
  32264. */
  32265. this.crossOrigin = 'anonymous';
  32266. /**
  32267. * Whether the XMLHttpRequest uses credentials.
  32268. *
  32269. * @type {boolean}
  32270. * @default false
  32271. */
  32272. this.withCredentials = false;
  32273. /**
  32274. * The base path from which the asset will be loaded.
  32275. *
  32276. * @type {string}
  32277. */
  32278. this.path = '';
  32279. /**
  32280. * The base path from which additional resources like textures will be loaded.
  32281. *
  32282. * @type {string}
  32283. */
  32284. this.resourcePath = '';
  32285. /**
  32286. * The [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32287. * used in HTTP request.
  32288. *
  32289. * @type {Object<string, any>}
  32290. */
  32291. this.requestHeader = {};
  32292. }
  32293. /**
  32294. * This method needs to be implemented by all concrete loaders. It holds the
  32295. * logic for loading assets from the backend.
  32296. *
  32297. * @abstract
  32298. * @param {string} url - The path/URL of the file to be loaded.
  32299. * @param {Function} onLoad - Executed when the loading process has been finished.
  32300. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32301. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32302. */
  32303. load( /* url, onLoad, onProgress, onError */ ) {}
  32304. /**
  32305. * A async version of {@link Loader#load}.
  32306. *
  32307. * @param {string} url - The path/URL of the file to be loaded.
  32308. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32309. * @return {Promise} A Promise that resolves when the asset has been loaded.
  32310. */
  32311. loadAsync( url, onProgress ) {
  32312. const scope = this;
  32313. return new Promise( function ( resolve, reject ) {
  32314. scope.load( url, resolve, onProgress, reject );
  32315. } );
  32316. }
  32317. /**
  32318. * This method needs to be implemented by all concrete loaders. It holds the
  32319. * logic for parsing the asset into three.js entities.
  32320. *
  32321. * @abstract
  32322. * @param {any} data - The data to parse.
  32323. */
  32324. parse( /* data */ ) {}
  32325. /**
  32326. * Sets the `crossOrigin` String to implement CORS for loading the URL
  32327. * from a different domain that allows CORS.
  32328. *
  32329. * @param {string} crossOrigin - The `crossOrigin` value.
  32330. * @return {Loader} A reference to this instance.
  32331. */
  32332. setCrossOrigin( crossOrigin ) {
  32333. this.crossOrigin = crossOrigin;
  32334. return this;
  32335. }
  32336. /**
  32337. * Whether the XMLHttpRequest uses credentials such as cookies, authorization
  32338. * headers or TLS client certificates, see [XMLHttpRequest.withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials).
  32339. *
  32340. * Note: This setting has no effect if you are loading files locally or from the same domain.
  32341. *
  32342. * @param {boolean} value - The `withCredentials` value.
  32343. * @return {Loader} A reference to this instance.
  32344. */
  32345. setWithCredentials( value ) {
  32346. this.withCredentials = value;
  32347. return this;
  32348. }
  32349. /**
  32350. * Sets the base path for the asset.
  32351. *
  32352. * @param {string} path - The base path.
  32353. * @return {Loader} A reference to this instance.
  32354. */
  32355. setPath( path ) {
  32356. this.path = path;
  32357. return this;
  32358. }
  32359. /**
  32360. * Sets the base path for dependent resources like textures.
  32361. *
  32362. * @param {string} resourcePath - The resource path.
  32363. * @return {Loader} A reference to this instance.
  32364. */
  32365. setResourcePath( resourcePath ) {
  32366. this.resourcePath = resourcePath;
  32367. return this;
  32368. }
  32369. /**
  32370. * Sets the given request header.
  32371. *
  32372. * @param {Object} requestHeader - A [request header](https://developer.mozilla.org/en-US/docs/Glossary/Request_header)
  32373. * for configuring the HTTP request.
  32374. * @return {Loader} A reference to this instance.
  32375. */
  32376. setRequestHeader( requestHeader ) {
  32377. this.requestHeader = requestHeader;
  32378. return this;
  32379. }
  32380. /**
  32381. * This method can be implemented in loaders for aborting ongoing requests.
  32382. *
  32383. * @abstract
  32384. * @return {Loader} A reference to this instance.
  32385. */
  32386. abort() {
  32387. return this;
  32388. }
  32389. }
  32390. /**
  32391. * Callback for onProgress in loaders.
  32392. *
  32393. * @callback onProgressCallback
  32394. * @param {ProgressEvent} event - An instance of `ProgressEvent` that represents the current loading status.
  32395. */
  32396. /**
  32397. * Callback for onError in loaders.
  32398. *
  32399. * @callback onErrorCallback
  32400. * @param {Error} error - The error which occurred during the loading process.
  32401. */
  32402. /**
  32403. * The default material name that is used by loaders
  32404. * when creating materials for loaded 3D objects.
  32405. *
  32406. * Note: Not all loaders might honor this setting.
  32407. *
  32408. * @static
  32409. * @type {string}
  32410. * @default '__DEFAULT'
  32411. */
  32412. Loader.DEFAULT_MATERIAL_NAME = '__DEFAULT';
  32413. const loading = {};
  32414. class HttpError extends Error {
  32415. constructor( message, response ) {
  32416. super( message );
  32417. this.response = response;
  32418. }
  32419. }
  32420. /**
  32421. * A low level class for loading resources with the Fetch API, used internally by
  32422. * most loaders. It can also be used directly to load any file type that does
  32423. * not have a loader.
  32424. *
  32425. * This loader supports caching. If you want to use it, add `THREE.Cache.enabled = true;`
  32426. * once to your application.
  32427. *
  32428. * ```js
  32429. * const loader = new THREE.FileLoader();
  32430. * const data = await loader.loadAsync( 'example.txt' );
  32431. * ```
  32432. *
  32433. * @augments Loader
  32434. */
  32435. class FileLoader extends Loader {
  32436. /**
  32437. * Constructs a new file loader.
  32438. *
  32439. * @param {LoadingManager} [manager] - The loading manager.
  32440. */
  32441. constructor( manager ) {
  32442. super( manager );
  32443. /**
  32444. * The expected mime type. Valid values can be found
  32445. * [here](hhttps://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#mimetype)
  32446. *
  32447. * @type {string}
  32448. */
  32449. this.mimeType = '';
  32450. /**
  32451. * The expected response type.
  32452. *
  32453. * @type {('arraybuffer'|'blob'|'document'|'json'|'')}
  32454. * @default ''
  32455. */
  32456. this.responseType = '';
  32457. /**
  32458. * Used for aborting requests.
  32459. *
  32460. * @private
  32461. * @type {AbortController}
  32462. */
  32463. this._abortController = new AbortController();
  32464. }
  32465. /**
  32466. * Starts loading from the given URL and pass the loaded response to the `onLoad()` callback.
  32467. *
  32468. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32469. * @param {function(any)} onLoad - Executed when the loading process has been finished.
  32470. * @param {onProgressCallback} [onProgress] - Executed while the loading is in progress.
  32471. * @param {onErrorCallback} [onError] - Executed when errors occur.
  32472. * @return {any|undefined} The cached resource if available.
  32473. */
  32474. load( url, onLoad, onProgress, onError ) {
  32475. if ( url === undefined ) url = '';
  32476. if ( this.path !== undefined ) url = this.path + url;
  32477. url = this.manager.resolveURL( url );
  32478. const cached = Cache.get( `file:${url}` );
  32479. if ( cached !== undefined ) {
  32480. this.manager.itemStart( url );
  32481. setTimeout( () => {
  32482. if ( onLoad ) onLoad( cached );
  32483. this.manager.itemEnd( url );
  32484. }, 0 );
  32485. return cached;
  32486. }
  32487. // Check if request is duplicate
  32488. if ( loading[ url ] !== undefined ) {
  32489. loading[ url ].push( {
  32490. onLoad: onLoad,
  32491. onProgress: onProgress,
  32492. onError: onError
  32493. } );
  32494. return;
  32495. }
  32496. // Initialise array for duplicate requests
  32497. loading[ url ] = [];
  32498. loading[ url ].push( {
  32499. onLoad: onLoad,
  32500. onProgress: onProgress,
  32501. onError: onError,
  32502. } );
  32503. // create request
  32504. const req = new Request( url, {
  32505. headers: new Headers( this.requestHeader ),
  32506. credentials: this.withCredentials ? 'include' : 'same-origin',
  32507. signal: ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal
  32508. } );
  32509. // record states ( avoid data race )
  32510. const mimeType = this.mimeType;
  32511. const responseType = this.responseType;
  32512. // start the fetch
  32513. fetch( req )
  32514. .then( response => {
  32515. if ( response.status === 200 || response.status === 0 ) {
  32516. // Some browsers return HTTP Status 0 when using non-http protocol
  32517. // e.g. 'file://' or 'data://'. Handle as success.
  32518. if ( response.status === 0 ) {
  32519. warn( 'FileLoader: HTTP Status 0 received.' );
  32520. }
  32521. // Workaround: Checking if response.body === undefined for Alipay browser #23548
  32522. if ( typeof ReadableStream === 'undefined' || response.body === undefined || response.body.getReader === undefined ) {
  32523. return response;
  32524. }
  32525. const callbacks = loading[ url ];
  32526. const reader = response.body.getReader();
  32527. // Nginx needs X-File-Size check
  32528. // https://serverfault.com/questions/482875/why-does-nginx-remove-content-length-header-for-chunked-content
  32529. const contentLength = response.headers.get( 'X-File-Size' ) || response.headers.get( 'Content-Length' );
  32530. const total = contentLength ? parseInt( contentLength ) : 0;
  32531. const lengthComputable = total !== 0;
  32532. let loaded = 0;
  32533. // periodically read data into the new stream tracking while download progress
  32534. const stream = new ReadableStream( {
  32535. start( controller ) {
  32536. readData();
  32537. function readData() {
  32538. reader.read().then( ( { done, value } ) => {
  32539. if ( done ) {
  32540. controller.close();
  32541. } else {
  32542. loaded += value.byteLength;
  32543. const event = new ProgressEvent( 'progress', { lengthComputable, loaded, total } );
  32544. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32545. const callback = callbacks[ i ];
  32546. if ( callback.onProgress ) callback.onProgress( event );
  32547. }
  32548. controller.enqueue( value );
  32549. readData();
  32550. }
  32551. }, ( e ) => {
  32552. controller.error( e );
  32553. } );
  32554. }
  32555. }
  32556. } );
  32557. return new Response( stream );
  32558. } else {
  32559. throw new HttpError( `fetch for "${response.url}" responded with ${response.status}: ${response.statusText}`, response );
  32560. }
  32561. } )
  32562. .then( response => {
  32563. switch ( responseType ) {
  32564. case 'arraybuffer':
  32565. return response.arrayBuffer();
  32566. case 'blob':
  32567. return response.blob();
  32568. case 'document':
  32569. return response.text()
  32570. .then( text => {
  32571. const parser = new DOMParser();
  32572. return parser.parseFromString( text, mimeType );
  32573. } );
  32574. case 'json':
  32575. return response.json();
  32576. default:
  32577. if ( mimeType === '' ) {
  32578. return response.text();
  32579. } else {
  32580. // sniff encoding
  32581. const re = /charset="?([^;"\s]*)"?/i;
  32582. const exec = re.exec( mimeType );
  32583. const label = exec && exec[ 1 ] ? exec[ 1 ].toLowerCase() : undefined;
  32584. const decoder = new TextDecoder( label );
  32585. return response.arrayBuffer().then( ab => decoder.decode( ab ) );
  32586. }
  32587. }
  32588. } )
  32589. .then( data => {
  32590. // Add to cache only on HTTP success, so that we do not cache
  32591. // error response bodies as proper responses to requests.
  32592. Cache.add( `file:${url}`, data );
  32593. const callbacks = loading[ url ];
  32594. delete loading[ url ];
  32595. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32596. const callback = callbacks[ i ];
  32597. if ( callback.onLoad ) callback.onLoad( data );
  32598. }
  32599. } )
  32600. .catch( err => {
  32601. // Abort errors and other errors are handled the same
  32602. const callbacks = loading[ url ];
  32603. if ( callbacks === undefined ) {
  32604. // When onLoad was called and url was deleted in `loading`
  32605. this.manager.itemError( url );
  32606. throw err;
  32607. }
  32608. delete loading[ url ];
  32609. for ( let i = 0, il = callbacks.length; i < il; i ++ ) {
  32610. const callback = callbacks[ i ];
  32611. if ( callback.onError ) callback.onError( err );
  32612. }
  32613. this.manager.itemError( url );
  32614. } )
  32615. .finally( () => {
  32616. this.manager.itemEnd( url );
  32617. } );
  32618. this.manager.itemStart( url );
  32619. }
  32620. /**
  32621. * Sets the expected response type.
  32622. *
  32623. * @param {('arraybuffer'|'blob'|'document'|'json'|'')} value - The response type.
  32624. * @return {FileLoader} A reference to this file loader.
  32625. */
  32626. setResponseType( value ) {
  32627. this.responseType = value;
  32628. return this;
  32629. }
  32630. /**
  32631. * Sets the expected mime type of the loaded file.
  32632. *
  32633. * @param {string} value - The mime type.
  32634. * @return {FileLoader} A reference to this file loader.
  32635. */
  32636. setMimeType( value ) {
  32637. this.mimeType = value;
  32638. return this;
  32639. }
  32640. /**
  32641. * Aborts ongoing fetch requests.
  32642. *
  32643. * @return {FileLoader} A reference to this instance.
  32644. */
  32645. abort() {
  32646. this._abortController.abort();
  32647. this._abortController = new AbortController();
  32648. return this;
  32649. }
  32650. }
  32651. /**
  32652. * Class for loading animation clips in the JSON format. The files are internally
  32653. * loaded via {@link FileLoader}.
  32654. *
  32655. * ```js
  32656. * const loader = new THREE.AnimationLoader();
  32657. * const animations = await loader.loadAsync( 'animations/animation.js' );
  32658. * ```
  32659. *
  32660. * @augments Loader
  32661. */
  32662. class AnimationLoader extends Loader {
  32663. /**
  32664. * Constructs a new animation loader.
  32665. *
  32666. * @param {LoadingManager} [manager] - The loading manager.
  32667. */
  32668. constructor( manager ) {
  32669. super( manager );
  32670. }
  32671. /**
  32672. * Starts loading from the given URL and pass the loaded animations as an array
  32673. * holding instances of {@link AnimationClip} to the `onLoad()` callback.
  32674. *
  32675. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32676. * @param {function(Array<AnimationClip>)} onLoad - Executed when the loading process has been finished.
  32677. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32678. * @param {onErrorCallback} onError - Executed when errors occur.
  32679. */
  32680. load( url, onLoad, onProgress, onError ) {
  32681. const scope = this;
  32682. const loader = new FileLoader( this.manager );
  32683. loader.setPath( this.path );
  32684. loader.setRequestHeader( this.requestHeader );
  32685. loader.setWithCredentials( this.withCredentials );
  32686. loader.load( url, function ( text ) {
  32687. try {
  32688. onLoad( scope.parse( JSON.parse( text ) ) );
  32689. } catch ( e ) {
  32690. if ( onError ) {
  32691. onError( e );
  32692. } else {
  32693. error( e );
  32694. }
  32695. scope.manager.itemError( url );
  32696. }
  32697. }, onProgress, onError );
  32698. }
  32699. /**
  32700. * Parses the given JSON object and returns an array of animation clips.
  32701. *
  32702. * @param {Object} json - The serialized animation clips.
  32703. * @return {Array<AnimationClip>} The parsed animation clips.
  32704. */
  32705. parse( json ) {
  32706. const animations = [];
  32707. for ( let i = 0; i < json.length; i ++ ) {
  32708. const clip = AnimationClip.parse( json[ i ] );
  32709. animations.push( clip );
  32710. }
  32711. return animations;
  32712. }
  32713. }
  32714. /**
  32715. * Abstract base class for loading compressed texture formats S3TC, ASTC or ETC.
  32716. * Textures are internally loaded via {@link FileLoader}.
  32717. *
  32718. * Derived classes have to implement the `parse()` method which holds the parsing
  32719. * for the respective format.
  32720. *
  32721. * @abstract
  32722. * @augments Loader
  32723. */
  32724. class CompressedTextureLoader extends Loader {
  32725. /**
  32726. * Constructs a new compressed texture loader.
  32727. *
  32728. * @param {LoadingManager} [manager] - The loading manager.
  32729. */
  32730. constructor( manager ) {
  32731. super( manager );
  32732. }
  32733. /**
  32734. * Starts loading from the given URL and passes the loaded compressed texture
  32735. * to the `onLoad()` callback. The method also returns a new texture object which can
  32736. * directly be used for material creation. If you do it this way, the texture
  32737. * may pop up in your scene once the respective loading process is finished.
  32738. *
  32739. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32740. * @param {function(CompressedTexture)} onLoad - Executed when the loading process has been finished.
  32741. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  32742. * @param {onErrorCallback} onError - Executed when errors occur.
  32743. * @return {CompressedTexture} The compressed texture.
  32744. */
  32745. load( url, onLoad, onProgress, onError ) {
  32746. const scope = this;
  32747. const images = [];
  32748. const texture = new CompressedTexture();
  32749. const loader = new FileLoader( this.manager );
  32750. loader.setPath( this.path );
  32751. loader.setResponseType( 'arraybuffer' );
  32752. loader.setRequestHeader( this.requestHeader );
  32753. loader.setWithCredentials( scope.withCredentials );
  32754. let loaded = 0;
  32755. function loadTexture( i ) {
  32756. loader.load( url[ i ], function ( buffer ) {
  32757. const texDatas = scope.parse( buffer, true );
  32758. images[ i ] = {
  32759. width: texDatas.width,
  32760. height: texDatas.height,
  32761. format: texDatas.format,
  32762. mipmaps: texDatas.mipmaps
  32763. };
  32764. loaded += 1;
  32765. if ( loaded === 6 ) {
  32766. if ( texDatas.mipmapCount === 1 ) texture.minFilter = LinearFilter;
  32767. texture.image = images;
  32768. texture.format = texDatas.format;
  32769. texture.needsUpdate = true;
  32770. if ( onLoad ) onLoad( texture );
  32771. }
  32772. }, onProgress, onError );
  32773. }
  32774. if ( Array.isArray( url ) ) {
  32775. for ( let i = 0, il = url.length; i < il; ++ i ) {
  32776. loadTexture( i );
  32777. }
  32778. } else {
  32779. // compressed cubemap texture stored in a single DDS file
  32780. loader.load( url, function ( buffer ) {
  32781. const texDatas = scope.parse( buffer, true );
  32782. if ( texDatas.isCubemap ) {
  32783. const faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  32784. for ( let f = 0; f < faces; f ++ ) {
  32785. images[ f ] = { mipmaps: [] };
  32786. for ( let i = 0; i < texDatas.mipmapCount; i ++ ) {
  32787. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  32788. images[ f ].format = texDatas.format;
  32789. images[ f ].width = texDatas.width;
  32790. images[ f ].height = texDatas.height;
  32791. }
  32792. }
  32793. texture.image = images;
  32794. } else {
  32795. texture.image.width = texDatas.width;
  32796. texture.image.height = texDatas.height;
  32797. texture.mipmaps = texDatas.mipmaps;
  32798. }
  32799. if ( texDatas.mipmapCount === 1 ) {
  32800. texture.minFilter = LinearFilter;
  32801. }
  32802. texture.format = texDatas.format;
  32803. texture.needsUpdate = true;
  32804. if ( onLoad ) onLoad( texture );
  32805. }, onProgress, onError );
  32806. }
  32807. return texture;
  32808. }
  32809. }
  32810. const _loading = new WeakMap();
  32811. /**
  32812. * A loader for loading images. The class loads images with the HTML `Image` API.
  32813. *
  32814. * ```js
  32815. * const loader = new THREE.ImageLoader();
  32816. * const image = await loader.loadAsync( 'image.png' );
  32817. * ```
  32818. * Please note that `ImageLoader` has dropped support for progress
  32819. * events in `r84`. For an `ImageLoader` that supports progress events, see
  32820. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-275785639).
  32821. *
  32822. * @augments Loader
  32823. */
  32824. class ImageLoader extends Loader {
  32825. /**
  32826. * Constructs a new image loader.
  32827. *
  32828. * @param {LoadingManager} [manager] - The loading manager.
  32829. */
  32830. constructor( manager ) {
  32831. super( manager );
  32832. }
  32833. /**
  32834. * Starts loading from the given URL and passes the loaded image
  32835. * to the `onLoad()` callback. The method also returns a new `Image` object which can
  32836. * directly be used for texture creation. If you do it this way, the texture
  32837. * may pop up in your scene once the respective loading process is finished.
  32838. *
  32839. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  32840. * @param {function(Image)} onLoad - Executed when the loading process has been finished.
  32841. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32842. * @param {onErrorCallback} onError - Executed when errors occur.
  32843. * @return {Image} The image.
  32844. */
  32845. load( url, onLoad, onProgress, onError ) {
  32846. if ( this.path !== undefined ) url = this.path + url;
  32847. url = this.manager.resolveURL( url );
  32848. const scope = this;
  32849. const cached = Cache.get( `image:${url}` );
  32850. if ( cached !== undefined ) {
  32851. if ( cached.complete === true ) {
  32852. scope.manager.itemStart( url );
  32853. setTimeout( function () {
  32854. if ( onLoad ) onLoad( cached );
  32855. scope.manager.itemEnd( url );
  32856. }, 0 );
  32857. } else {
  32858. let arr = _loading.get( cached );
  32859. if ( arr === undefined ) {
  32860. arr = [];
  32861. _loading.set( cached, arr );
  32862. }
  32863. arr.push( { onLoad, onError } );
  32864. }
  32865. return cached;
  32866. }
  32867. const image = createElementNS( 'img' );
  32868. function onImageLoad() {
  32869. removeEventListeners();
  32870. if ( onLoad ) onLoad( this );
  32871. //
  32872. const callbacks = _loading.get( this ) || [];
  32873. for ( let i = 0; i < callbacks.length; i ++ ) {
  32874. const callback = callbacks[ i ];
  32875. if ( callback.onLoad ) callback.onLoad( this );
  32876. }
  32877. _loading.delete( this );
  32878. scope.manager.itemEnd( url );
  32879. }
  32880. function onImageError( event ) {
  32881. removeEventListeners();
  32882. if ( onError ) onError( event );
  32883. Cache.remove( `image:${url}` );
  32884. //
  32885. const callbacks = _loading.get( this ) || [];
  32886. for ( let i = 0; i < callbacks.length; i ++ ) {
  32887. const callback = callbacks[ i ];
  32888. if ( callback.onError ) callback.onError( event );
  32889. }
  32890. _loading.delete( this );
  32891. scope.manager.itemError( url );
  32892. scope.manager.itemEnd( url );
  32893. }
  32894. function removeEventListeners() {
  32895. image.removeEventListener( 'load', onImageLoad, false );
  32896. image.removeEventListener( 'error', onImageError, false );
  32897. }
  32898. image.addEventListener( 'load', onImageLoad, false );
  32899. image.addEventListener( 'error', onImageError, false );
  32900. if ( url.slice( 0, 5 ) !== 'data:' ) {
  32901. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  32902. }
  32903. Cache.add( `image:${url}`, image );
  32904. scope.manager.itemStart( url );
  32905. image.src = url;
  32906. return image;
  32907. }
  32908. }
  32909. /**
  32910. * Class for loading cube textures. Images are internally loaded via {@link ImageLoader}.
  32911. *
  32912. * The loader returns an instance of {@link CubeTexture} and expects the cube map to
  32913. * be defined as six separate images representing the sides of a cube. Other cube map definitions
  32914. * like vertical and horizontal cross, column and row layouts are not supported.
  32915. *
  32916. * Note that, by convention, cube maps are specified in a coordinate system
  32917. * in which positive-x is to the right when looking up the positive-z axis --
  32918. * in other words, using a left-handed coordinate system. Since three.js uses
  32919. * a right-handed coordinate system, environment maps used in three.js will
  32920. * have pos-x and neg-x swapped.
  32921. *
  32922. * The loaded cube texture is in sRGB color space. Meaning {@link Texture#colorSpace}
  32923. * is set to `SRGBColorSpace` by default.
  32924. *
  32925. * ```js
  32926. * const loader = new THREE.CubeTextureLoader().setPath( 'textures/cubeMaps/' );
  32927. * const cubeTexture = await loader.loadAsync( [
  32928. * 'px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'
  32929. * ] );
  32930. * scene.background = cubeTexture;
  32931. * ```
  32932. *
  32933. * @augments Loader
  32934. */
  32935. class CubeTextureLoader extends Loader {
  32936. /**
  32937. * Constructs a new cube texture loader.
  32938. *
  32939. * @param {LoadingManager} [manager] - The loading manager.
  32940. */
  32941. constructor( manager ) {
  32942. super( manager );
  32943. }
  32944. /**
  32945. * Starts loading from the given URL and pass the fully loaded cube texture
  32946. * to the `onLoad()` callback. The method also returns a new cube texture object which can
  32947. * directly be used for material creation. If you do it this way, the cube texture
  32948. * may pop up in your scene once the respective loading process is finished.
  32949. *
  32950. * @param {Array<string>} urls - Array of 6 URLs to images, one for each side of the
  32951. * cube texture. The urls should be specified in the following order: pos-x,
  32952. * neg-x, pos-y, neg-y, pos-z, neg-z. An array of data URIs are allowed as well.
  32953. * @param {function(CubeTexture)} onLoad - Executed when the loading process has been finished.
  32954. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  32955. * @param {onErrorCallback} onError - Executed when errors occur.
  32956. * @return {CubeTexture} The cube texture.
  32957. */
  32958. load( urls, onLoad, onProgress, onError ) {
  32959. const texture = new CubeTexture();
  32960. texture.colorSpace = SRGBColorSpace;
  32961. const loader = new ImageLoader( this.manager );
  32962. loader.setCrossOrigin( this.crossOrigin );
  32963. loader.setPath( this.path );
  32964. let loaded = 0;
  32965. function loadTexture( i ) {
  32966. loader.load( urls[ i ], function ( image ) {
  32967. texture.images[ i ] = image;
  32968. loaded ++;
  32969. if ( loaded === 6 ) {
  32970. texture.needsUpdate = true;
  32971. if ( onLoad ) onLoad( texture );
  32972. }
  32973. }, undefined, onError );
  32974. }
  32975. for ( let i = 0; i < urls.length; ++ i ) {
  32976. loadTexture( i );
  32977. }
  32978. return texture;
  32979. }
  32980. }
  32981. /**
  32982. * Abstract base class for loading binary texture formats RGBE, EXR or TGA.
  32983. * Textures are internally loaded via {@link FileLoader}.
  32984. *
  32985. * Derived classes have to implement the `parse()` method which holds the parsing
  32986. * for the respective format.
  32987. *
  32988. * @abstract
  32989. * @augments Loader
  32990. */
  32991. class DataTextureLoader extends Loader {
  32992. /**
  32993. * Constructs a new data texture loader.
  32994. *
  32995. * @param {LoadingManager} [manager] - The loading manager.
  32996. */
  32997. constructor( manager ) {
  32998. super( manager );
  32999. }
  33000. /**
  33001. * Starts loading from the given URL and passes the loaded data texture
  33002. * to the `onLoad()` callback. The method also returns a new texture object which can
  33003. * directly be used for material creation. If you do it this way, the texture
  33004. * may pop up in your scene once the respective loading process is finished.
  33005. *
  33006. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33007. * @param {function(DataTexture)} onLoad - Executed when the loading process has been finished.
  33008. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  33009. * @param {onErrorCallback} onError - Executed when errors occur.
  33010. * @return {DataTexture} The data texture.
  33011. */
  33012. load( url, onLoad, onProgress, onError ) {
  33013. const scope = this;
  33014. const texture = new DataTexture();
  33015. const loader = new FileLoader( this.manager );
  33016. loader.setResponseType( 'arraybuffer' );
  33017. loader.setRequestHeader( this.requestHeader );
  33018. loader.setPath( this.path );
  33019. loader.setWithCredentials( scope.withCredentials );
  33020. loader.load( url, function ( buffer ) {
  33021. let texData;
  33022. try {
  33023. texData = scope.parse( buffer );
  33024. } catch ( error ) {
  33025. if ( onError !== undefined ) {
  33026. onError( error );
  33027. } else {
  33028. error( error );
  33029. return;
  33030. }
  33031. }
  33032. if ( texData.image !== undefined ) {
  33033. texture.image = texData.image;
  33034. } else if ( texData.data !== undefined ) {
  33035. texture.image.width = texData.width;
  33036. texture.image.height = texData.height;
  33037. texture.image.data = texData.data;
  33038. }
  33039. texture.wrapS = texData.wrapS !== undefined ? texData.wrapS : ClampToEdgeWrapping;
  33040. texture.wrapT = texData.wrapT !== undefined ? texData.wrapT : ClampToEdgeWrapping;
  33041. texture.magFilter = texData.magFilter !== undefined ? texData.magFilter : LinearFilter;
  33042. texture.minFilter = texData.minFilter !== undefined ? texData.minFilter : LinearFilter;
  33043. texture.anisotropy = texData.anisotropy !== undefined ? texData.anisotropy : 1;
  33044. if ( texData.colorSpace !== undefined ) {
  33045. texture.colorSpace = texData.colorSpace;
  33046. }
  33047. if ( texData.flipY !== undefined ) {
  33048. texture.flipY = texData.flipY;
  33049. }
  33050. if ( texData.format !== undefined ) {
  33051. texture.format = texData.format;
  33052. }
  33053. if ( texData.type !== undefined ) {
  33054. texture.type = texData.type;
  33055. }
  33056. if ( texData.mipmaps !== undefined ) {
  33057. texture.mipmaps = texData.mipmaps;
  33058. texture.minFilter = LinearMipmapLinearFilter; // presumably...
  33059. }
  33060. if ( texData.mipmapCount === 1 ) {
  33061. texture.minFilter = LinearFilter;
  33062. }
  33063. if ( texData.generateMipmaps !== undefined ) {
  33064. texture.generateMipmaps = texData.generateMipmaps;
  33065. }
  33066. texture.needsUpdate = true;
  33067. if ( onLoad ) onLoad( texture, texData );
  33068. }, onProgress, onError );
  33069. return texture;
  33070. }
  33071. }
  33072. /**
  33073. * Class for loading textures. Images are internally
  33074. * loaded via {@link ImageLoader}.
  33075. *
  33076. * ```js
  33077. * const loader = new THREE.TextureLoader();
  33078. * const texture = await loader.loadAsync( 'textures/land_ocean_ice_cloud_2048.jpg' );
  33079. *
  33080. * const material = new THREE.MeshBasicMaterial( { map:texture } );
  33081. * ```
  33082. * Please note that `TextureLoader` has dropped support for progress
  33083. * events in `r84`. For a `TextureLoader` that supports progress events, see
  33084. * [this thread](https://github.com/mrdoob/three.js/issues/10439#issuecomment-293260145).
  33085. *
  33086. * @augments Loader
  33087. */
  33088. class TextureLoader extends Loader {
  33089. /**
  33090. * Constructs a new texture loader.
  33091. *
  33092. * @param {LoadingManager} [manager] - The loading manager.
  33093. */
  33094. constructor( manager ) {
  33095. super( manager );
  33096. }
  33097. /**
  33098. * Starts loading from the given URL and pass the fully loaded texture
  33099. * to the `onLoad()` callback. The method also returns a new texture object which can
  33100. * directly be used for material creation. If you do it this way, the texture
  33101. * may pop up in your scene once the respective loading process is finished.
  33102. *
  33103. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  33104. * @param {function(Texture)} onLoad - Executed when the loading process has been finished.
  33105. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  33106. * @param {onErrorCallback} onError - Executed when errors occur.
  33107. * @return {Texture} The texture.
  33108. */
  33109. load( url, onLoad, onProgress, onError ) {
  33110. const texture = new Texture();
  33111. const loader = new ImageLoader( this.manager );
  33112. loader.setCrossOrigin( this.crossOrigin );
  33113. loader.setPath( this.path );
  33114. loader.load( url, function ( image ) {
  33115. texture.image = image;
  33116. texture.needsUpdate = true;
  33117. if ( onLoad !== undefined ) {
  33118. onLoad( texture );
  33119. }
  33120. }, onProgress, onError );
  33121. return texture;
  33122. }
  33123. }
  33124. /**
  33125. * Abstract base class for lights - all other light types inherit the
  33126. * properties and methods described here.
  33127. *
  33128. * @abstract
  33129. * @augments Object3D
  33130. */
  33131. class Light extends Object3D {
  33132. /**
  33133. * Constructs a new light.
  33134. *
  33135. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33136. * @param {number} [intensity=1] - The light's strength/intensity.
  33137. */
  33138. constructor( color, intensity = 1 ) {
  33139. super();
  33140. /**
  33141. * This flag can be used for type testing.
  33142. *
  33143. * @type {boolean}
  33144. * @readonly
  33145. * @default true
  33146. */
  33147. this.isLight = true;
  33148. this.type = 'Light';
  33149. /**
  33150. * The light's color.
  33151. *
  33152. * @type {Color}
  33153. */
  33154. this.color = new Color( color );
  33155. /**
  33156. * The light's intensity.
  33157. *
  33158. * @type {number}
  33159. * @default 1
  33160. */
  33161. this.intensity = intensity;
  33162. }
  33163. /**
  33164. * Frees the GPU-related resources allocated by this instance. Call this
  33165. * method whenever this instance is no longer used in your app.
  33166. */
  33167. dispose() {
  33168. // Empty here in base class; some subclasses override.
  33169. }
  33170. copy( source, recursive ) {
  33171. super.copy( source, recursive );
  33172. this.color.copy( source.color );
  33173. this.intensity = source.intensity;
  33174. return this;
  33175. }
  33176. toJSON( meta ) {
  33177. const data = super.toJSON( meta );
  33178. data.object.color = this.color.getHex();
  33179. data.object.intensity = this.intensity;
  33180. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  33181. if ( this.distance !== undefined ) data.object.distance = this.distance;
  33182. if ( this.angle !== undefined ) data.object.angle = this.angle;
  33183. if ( this.decay !== undefined ) data.object.decay = this.decay;
  33184. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  33185. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  33186. if ( this.target !== undefined ) data.object.target = this.target.uuid;
  33187. return data;
  33188. }
  33189. }
  33190. /**
  33191. * A light source positioned directly above the scene, with color fading from
  33192. * the sky color to the ground color.
  33193. *
  33194. * This light cannot be used to cast shadows.
  33195. *
  33196. * ```js
  33197. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  33198. * scene.add( light );
  33199. * ```
  33200. *
  33201. * @augments Light
  33202. */
  33203. class HemisphereLight extends Light {
  33204. /**
  33205. * Constructs a new hemisphere light.
  33206. *
  33207. * @param {(number|Color|string)} [skyColor=0xffffff] - The light's sky color.
  33208. * @param {(number|Color|string)} [groundColor=0xffffff] - The light's ground color.
  33209. * @param {number} [intensity=1] - The light's strength/intensity.
  33210. */
  33211. constructor( skyColor, groundColor, intensity ) {
  33212. super( skyColor, intensity );
  33213. /**
  33214. * This flag can be used for type testing.
  33215. *
  33216. * @type {boolean}
  33217. * @readonly
  33218. * @default true
  33219. */
  33220. this.isHemisphereLight = true;
  33221. this.type = 'HemisphereLight';
  33222. this.position.copy( Object3D.DEFAULT_UP );
  33223. this.updateMatrix();
  33224. /**
  33225. * The light's ground color.
  33226. *
  33227. * @type {Color}
  33228. */
  33229. this.groundColor = new Color( groundColor );
  33230. }
  33231. copy( source, recursive ) {
  33232. super.copy( source, recursive );
  33233. this.groundColor.copy( source.groundColor );
  33234. return this;
  33235. }
  33236. }
  33237. const _projScreenMatrix$1 = /*@__PURE__*/ new Matrix4();
  33238. const _lightPositionWorld$1 = /*@__PURE__*/ new Vector3();
  33239. const _lookTarget$1 = /*@__PURE__*/ new Vector3();
  33240. /**
  33241. * Abstract base class for light shadow classes. These classes
  33242. * represent the shadow configuration for different light types.
  33243. *
  33244. * @abstract
  33245. */
  33246. class LightShadow {
  33247. /**
  33248. * Constructs a new light shadow.
  33249. *
  33250. * @param {Camera} camera - The light's view of the world.
  33251. */
  33252. constructor( camera ) {
  33253. /**
  33254. * The light's view of the world.
  33255. *
  33256. * @type {Camera}
  33257. */
  33258. this.camera = camera;
  33259. /**
  33260. * The intensity of the shadow. The default is `1`.
  33261. * Valid values are in the range `[0, 1]`.
  33262. *
  33263. * @type {number}
  33264. * @default 1
  33265. */
  33266. this.intensity = 1;
  33267. /**
  33268. * Shadow map bias, how much to add or subtract from the normalized depth
  33269. * when deciding whether a surface is in shadow.
  33270. *
  33271. * The default is `0`. Very tiny adjustments here (in the order of `0.0001`)
  33272. * may help reduce artifacts in shadows.
  33273. *
  33274. * @type {number}
  33275. * @default 0
  33276. */
  33277. this.bias = 0;
  33278. /**
  33279. * Defines how much the position used to query the shadow map is offset along
  33280. * the object normal. The default is `0`. Increasing this value can be used to
  33281. * reduce shadow acne especially in large scenes where light shines onto
  33282. * geometry at a shallow angle. The cost is that shadows may appear distorted.
  33283. *
  33284. * @type {number}
  33285. * @default 0
  33286. */
  33287. this.normalBias = 0;
  33288. /**
  33289. * Setting this to values greater than 1 will blur the edges of the shadow.
  33290. * High values will cause unwanted banding effects in the shadows - a greater
  33291. * map size will allow for a higher value to be used here before these effects
  33292. * become visible.
  33293. *
  33294. * The property has no effect when the shadow map type is `BasicShadowMap`.
  33295. *
  33296. * @type {number}
  33297. * @default 1
  33298. */
  33299. this.radius = 1;
  33300. /**
  33301. * The amount of samples to use when blurring a VSM shadow map.
  33302. *
  33303. * @type {number}
  33304. * @default 8
  33305. */
  33306. this.blurSamples = 8;
  33307. /**
  33308. * Defines the width and height of the shadow map. Higher values give better quality
  33309. * shadows at the cost of computation time. Values must be powers of two.
  33310. *
  33311. * @type {Vector2}
  33312. * @default (512,512)
  33313. */
  33314. this.mapSize = new Vector2( 512, 512 );
  33315. /**
  33316. * The type of shadow texture. The default is `UnsignedByteType`.
  33317. *
  33318. * @type {number}
  33319. * @default UnsignedByteType
  33320. */
  33321. this.mapType = UnsignedByteType;
  33322. /**
  33323. * The depth map generated using the internal camera; a location beyond a
  33324. * pixel's depth is in shadow. Computed internally during rendering.
  33325. *
  33326. * @type {?RenderTarget}
  33327. * @default null
  33328. */
  33329. this.map = null;
  33330. /**
  33331. * The distribution map generated using the internal camera; an occlusion is
  33332. * calculated based on the distribution of depths. Computed internally during
  33333. * rendering.
  33334. *
  33335. * @type {?RenderTarget}
  33336. * @default null
  33337. */
  33338. this.mapPass = null;
  33339. /**
  33340. * Model to shadow camera space, to compute location and depth in shadow map.
  33341. * This is computed internally during rendering.
  33342. *
  33343. * @type {Matrix4}
  33344. */
  33345. this.matrix = new Matrix4();
  33346. /**
  33347. * Enables automatic updates of the light's shadow. If you do not require dynamic
  33348. * lighting / shadows, you may set this to `false`.
  33349. *
  33350. * @type {boolean}
  33351. * @default true
  33352. */
  33353. this.autoUpdate = true;
  33354. /**
  33355. * When set to `true`, shadow maps will be updated in the next `render` call.
  33356. * If you have set {@link LightShadow#autoUpdate} to `false`, you will need to
  33357. * set this property to `true` and then make a render call to update the light's shadow.
  33358. *
  33359. * @type {boolean}
  33360. * @default false
  33361. */
  33362. this.needsUpdate = false;
  33363. this._frustum = new Frustum();
  33364. this._frameExtents = new Vector2( 1, 1 );
  33365. this._viewportCount = 1;
  33366. this._viewports = [
  33367. new Vector4( 0, 0, 1, 1 )
  33368. ];
  33369. }
  33370. /**
  33371. * Used internally by the renderer to get the number of viewports that need
  33372. * to be rendered for this shadow.
  33373. *
  33374. * @return {number} The viewport count.
  33375. */
  33376. getViewportCount() {
  33377. return this._viewportCount;
  33378. }
  33379. /**
  33380. * Gets the shadow cameras frustum. Used internally by the renderer to cull objects.
  33381. *
  33382. * @return {Frustum} The shadow camera frustum.
  33383. */
  33384. getFrustum() {
  33385. return this._frustum;
  33386. }
  33387. /**
  33388. * Update the matrices for the camera and shadow, used internally by the renderer.
  33389. *
  33390. * @param {Light} light - The light for which the shadow is being rendered.
  33391. */
  33392. updateMatrices( light ) {
  33393. const shadowCamera = this.camera;
  33394. const shadowMatrix = this.matrix;
  33395. _lightPositionWorld$1.setFromMatrixPosition( light.matrixWorld );
  33396. shadowCamera.position.copy( _lightPositionWorld$1 );
  33397. _lookTarget$1.setFromMatrixPosition( light.target.matrixWorld );
  33398. shadowCamera.lookAt( _lookTarget$1 );
  33399. shadowCamera.updateMatrixWorld();
  33400. _projScreenMatrix$1.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  33401. this._frustum.setFromProjectionMatrix( _projScreenMatrix$1, shadowCamera.coordinateSystem, shadowCamera.reversedDepth );
  33402. if ( shadowCamera.reversedDepth ) {
  33403. shadowMatrix.set(
  33404. 0.5, 0.0, 0.0, 0.5,
  33405. 0.0, 0.5, 0.0, 0.5,
  33406. 0.0, 0.0, 1.0, 0.0,
  33407. 0.0, 0.0, 0.0, 1.0
  33408. );
  33409. } else {
  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, 0.5, 0.5,
  33414. 0.0, 0.0, 0.0, 1.0
  33415. );
  33416. }
  33417. shadowMatrix.multiply( _projScreenMatrix$1 );
  33418. }
  33419. /**
  33420. * Returns a viewport definition for the given viewport index.
  33421. *
  33422. * @param {number} viewportIndex - The viewport index.
  33423. * @return {Vector4} The viewport.
  33424. */
  33425. getViewport( viewportIndex ) {
  33426. return this._viewports[ viewportIndex ];
  33427. }
  33428. /**
  33429. * Returns the frame extends.
  33430. *
  33431. * @return {Vector2} The frame extends.
  33432. */
  33433. getFrameExtents() {
  33434. return this._frameExtents;
  33435. }
  33436. /**
  33437. * Frees the GPU-related resources allocated by this instance. Call this
  33438. * method whenever this instance is no longer used in your app.
  33439. */
  33440. dispose() {
  33441. if ( this.map ) {
  33442. this.map.dispose();
  33443. }
  33444. if ( this.mapPass ) {
  33445. this.mapPass.dispose();
  33446. }
  33447. }
  33448. /**
  33449. * Copies the values of the given light shadow instance to this instance.
  33450. *
  33451. * @param {LightShadow} source - The light shadow to copy.
  33452. * @return {LightShadow} A reference to this light shadow instance.
  33453. */
  33454. copy( source ) {
  33455. this.camera = source.camera.clone();
  33456. this.intensity = source.intensity;
  33457. this.bias = source.bias;
  33458. this.radius = source.radius;
  33459. this.autoUpdate = source.autoUpdate;
  33460. this.needsUpdate = source.needsUpdate;
  33461. this.normalBias = source.normalBias;
  33462. this.blurSamples = source.blurSamples;
  33463. this.mapSize.copy( source.mapSize );
  33464. return this;
  33465. }
  33466. /**
  33467. * Returns a new light shadow instance with copied values from this instance.
  33468. *
  33469. * @return {LightShadow} A clone of this instance.
  33470. */
  33471. clone() {
  33472. return new this.constructor().copy( this );
  33473. }
  33474. /**
  33475. * Serializes the light shadow into JSON.
  33476. *
  33477. * @return {Object} A JSON object representing the serialized light shadow.
  33478. * @see {@link ObjectLoader#parse}
  33479. */
  33480. toJSON() {
  33481. const object = {};
  33482. if ( this.intensity !== 1 ) object.intensity = this.intensity;
  33483. if ( this.bias !== 0 ) object.bias = this.bias;
  33484. if ( this.normalBias !== 0 ) object.normalBias = this.normalBias;
  33485. if ( this.radius !== 1 ) object.radius = this.radius;
  33486. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  33487. object.camera = this.camera.toJSON( false ).object;
  33488. delete object.camera.matrix;
  33489. return object;
  33490. }
  33491. }
  33492. /**
  33493. * Represents the shadow configuration of directional lights.
  33494. *
  33495. * @augments LightShadow
  33496. */
  33497. class SpotLightShadow extends LightShadow {
  33498. /**
  33499. * Constructs a new spot light shadow.
  33500. */
  33501. constructor() {
  33502. super( new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  33503. /**
  33504. * This flag can be used for type testing.
  33505. *
  33506. * @type {boolean}
  33507. * @readonly
  33508. * @default true
  33509. */
  33510. this.isSpotLightShadow = true;
  33511. /**
  33512. * Used to focus the shadow camera. The camera's field of view is set as a
  33513. * percentage of the spotlight's field-of-view. Range is `[0, 1]`.
  33514. *
  33515. * @type {number}
  33516. * @default 1
  33517. */
  33518. this.focus = 1;
  33519. /**
  33520. * Texture aspect ratio.
  33521. *
  33522. * @type {number}
  33523. * @default 1
  33524. */
  33525. this.aspect = 1;
  33526. }
  33527. updateMatrices( light ) {
  33528. const camera = this.camera;
  33529. const fov = RAD2DEG * 2 * light.angle * this.focus;
  33530. const aspect = ( this.mapSize.width / this.mapSize.height ) * this.aspect;
  33531. const far = light.distance || camera.far;
  33532. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  33533. camera.fov = fov;
  33534. camera.aspect = aspect;
  33535. camera.far = far;
  33536. camera.updateProjectionMatrix();
  33537. }
  33538. super.updateMatrices( light );
  33539. }
  33540. copy( source ) {
  33541. super.copy( source );
  33542. this.focus = source.focus;
  33543. return this;
  33544. }
  33545. }
  33546. /**
  33547. * This light gets emitted from a single point in one direction, along a cone
  33548. * that increases in size the further from the light it gets.
  33549. *
  33550. * This light can cast shadows - see the {@link SpotLightShadow} for details.
  33551. *
  33552. * ```js
  33553. * // white spotlight shining from the side, modulated by a texture
  33554. * const spotLight = new THREE.SpotLight( 0xffffff );
  33555. * spotLight.position.set( 100, 1000, 100 );
  33556. * spotLight.map = new THREE.TextureLoader().load( url );
  33557. *
  33558. * spotLight.castShadow = true;
  33559. * spotLight.shadow.mapSize.width = 1024;
  33560. * spotLight.shadow.mapSize.height = 1024;
  33561. * spotLight.shadow.camera.near = 500;
  33562. * spotLight.shadow.camera.far = 4000;
  33563. * spotLight.shadow.camera.fov = 30;s
  33564. * ```
  33565. *
  33566. * @augments Light
  33567. */
  33568. class SpotLight extends Light {
  33569. /**
  33570. * Constructs a new spot light.
  33571. *
  33572. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33573. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33574. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33575. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33576. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  33577. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33578. */
  33579. constructor( color, intensity, distance = 0, angle = Math.PI / 3, penumbra = 0, decay = 2 ) {
  33580. super( color, intensity );
  33581. /**
  33582. * This flag can be used for type testing.
  33583. *
  33584. * @type {boolean}
  33585. * @readonly
  33586. * @default true
  33587. */
  33588. this.isSpotLight = true;
  33589. this.type = 'SpotLight';
  33590. this.position.copy( Object3D.DEFAULT_UP );
  33591. this.updateMatrix();
  33592. /**
  33593. * The spot light points from its position to the
  33594. * target's position.
  33595. *
  33596. * For the target's position to be changed to anything other
  33597. * than the default, it must be added to the scene.
  33598. *
  33599. * It is also possible to set the target to be another 3D object
  33600. * in the scene. The light will now track the target object.
  33601. *
  33602. * @type {Object3D}
  33603. */
  33604. this.target = new Object3D();
  33605. /**
  33606. * Maximum range of the light. `0` means no limit.
  33607. *
  33608. * @type {number}
  33609. * @default 0
  33610. */
  33611. this.distance = distance;
  33612. /**
  33613. * Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  33614. *
  33615. * @type {number}
  33616. * @default Math.PI/3
  33617. */
  33618. this.angle = angle;
  33619. /**
  33620. * Percent of the spotlight cone that is attenuated due to penumbra.
  33621. * Value range is `[0,1]`.
  33622. *
  33623. * @type {number}
  33624. * @default 0
  33625. */
  33626. this.penumbra = penumbra;
  33627. /**
  33628. * The amount the light dims along the distance of the light. In context of
  33629. * physically-correct rendering the default value should not be changed.
  33630. *
  33631. * @type {number}
  33632. * @default 2
  33633. */
  33634. this.decay = decay;
  33635. /**
  33636. * A texture used to modulate the color of the light. The spot light
  33637. * color is mixed with the RGB value of this texture, with a ratio
  33638. * corresponding to its alpha value. The cookie-like masking effect is
  33639. * reproduced using pixel values (0, 0, 0, 1-cookie_value).
  33640. *
  33641. * *Warning*: This property is disabled if {@link Object3D#castShadow} is set to `false`.
  33642. *
  33643. * @type {?Texture}
  33644. * @default null
  33645. */
  33646. this.map = null;
  33647. /**
  33648. * This property holds the light's shadow configuration.
  33649. *
  33650. * @type {SpotLightShadow}
  33651. */
  33652. this.shadow = new SpotLightShadow();
  33653. }
  33654. /**
  33655. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33656. * Changing the power will also change the light's intensity.
  33657. *
  33658. * @type {number}
  33659. */
  33660. get power() {
  33661. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33662. // by convention for a spotlight, luminous power (lm) = π * luminous intensity (cd)
  33663. return this.intensity * Math.PI;
  33664. }
  33665. set power( power ) {
  33666. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33667. this.intensity = power / Math.PI;
  33668. }
  33669. dispose() {
  33670. this.shadow.dispose();
  33671. }
  33672. copy( source, recursive ) {
  33673. super.copy( source, recursive );
  33674. this.distance = source.distance;
  33675. this.angle = source.angle;
  33676. this.penumbra = source.penumbra;
  33677. this.decay = source.decay;
  33678. this.target = source.target.clone();
  33679. this.shadow = source.shadow.clone();
  33680. return this;
  33681. }
  33682. }
  33683. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  33684. const _lightPositionWorld = /*@__PURE__*/ new Vector3();
  33685. const _lookTarget = /*@__PURE__*/ new Vector3();
  33686. /**
  33687. * Represents the shadow configuration of point lights.
  33688. *
  33689. * @augments LightShadow
  33690. */
  33691. class PointLightShadow extends LightShadow {
  33692. /**
  33693. * Constructs a new point light shadow.
  33694. */
  33695. constructor() {
  33696. super( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  33697. /**
  33698. * This flag can be used for type testing.
  33699. *
  33700. * @type {boolean}
  33701. * @readonly
  33702. * @default true
  33703. */
  33704. this.isPointLightShadow = true;
  33705. this._cubeDirections = [
  33706. new Vector3( 1, 0, 0 ), new Vector3( -1, 0, 0 ), new Vector3( 0, 1, 0 ),
  33707. new Vector3( 0, -1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, -1 )
  33708. ];
  33709. this._cubeUps = [
  33710. new Vector3( 0, -1, 0 ), new Vector3( 0, -1, 0 ), new Vector3( 0, 0, 1 ),
  33711. new Vector3( 0, 0, -1 ), new Vector3( 0, -1, 0 ), new Vector3( 0, -1, 0 )
  33712. ];
  33713. }
  33714. /**
  33715. * Update the matrices for the camera and shadow, used internally by the renderer.
  33716. *
  33717. * @param {Light} light - The light for which the shadow is being rendered.
  33718. * @param {number} [faceIndex=0] - The cube face index (0-5).
  33719. */
  33720. updateMatrices( light, faceIndex = 0 ) {
  33721. const camera = this.camera;
  33722. const shadowMatrix = this.matrix;
  33723. const far = light.distance || camera.far;
  33724. if ( far !== camera.far ) {
  33725. camera.far = far;
  33726. camera.updateProjectionMatrix();
  33727. }
  33728. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  33729. camera.position.copy( _lightPositionWorld );
  33730. _lookTarget.copy( camera.position );
  33731. _lookTarget.add( this._cubeDirections[ faceIndex ] );
  33732. camera.up.copy( this._cubeUps[ faceIndex ] );
  33733. camera.lookAt( _lookTarget );
  33734. camera.updateMatrixWorld();
  33735. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  33736. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  33737. this._frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  33738. }
  33739. }
  33740. /**
  33741. * A light that gets emitted from a single point in all directions. A common
  33742. * use case for this is to replicate the light emitted from a bare
  33743. * lightbulb.
  33744. *
  33745. * This light can cast shadows - see the {@link PointLightShadow} for details.
  33746. *
  33747. * ```js
  33748. * const light = new THREE.PointLight( 0xff0000, 1, 100 );
  33749. * light.position.set( 50, 50, 50 );
  33750. * scene.add( light );
  33751. * ```
  33752. *
  33753. * @augments Light
  33754. */
  33755. class PointLight extends Light {
  33756. /**
  33757. * Constructs a new point light.
  33758. *
  33759. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  33760. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  33761. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  33762. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  33763. */
  33764. constructor( color, intensity, distance = 0, decay = 2 ) {
  33765. super( color, intensity );
  33766. /**
  33767. * This flag can be used for type testing.
  33768. *
  33769. * @type {boolean}
  33770. * @readonly
  33771. * @default true
  33772. */
  33773. this.isPointLight = true;
  33774. this.type = 'PointLight';
  33775. /**
  33776. * When distance is zero, light will attenuate according to inverse-square
  33777. * law to infinite distance. When distance is non-zero, light will attenuate
  33778. * according to inverse-square law until near the distance cutoff, where it
  33779. * will then attenuate quickly and smoothly to 0. Inherently, cutoffs are not
  33780. * physically correct.
  33781. *
  33782. * @type {number}
  33783. * @default 0
  33784. */
  33785. this.distance = distance;
  33786. /**
  33787. * The amount the light dims along the distance of the light. In context of
  33788. * physically-correct rendering the default value should not be changed.
  33789. *
  33790. * @type {number}
  33791. * @default 2
  33792. */
  33793. this.decay = decay;
  33794. /**
  33795. * This property holds the light's shadow configuration.
  33796. *
  33797. * @type {PointLightShadow}
  33798. */
  33799. this.shadow = new PointLightShadow();
  33800. }
  33801. /**
  33802. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  33803. * Changing the power will also change the light's intensity.
  33804. *
  33805. * @type {number}
  33806. */
  33807. get power() {
  33808. // compute the light's luminous power (in lumens) from its intensity (in candela)
  33809. // for an isotropic light source, luminous power (lm) = 4 π luminous intensity (cd)
  33810. return this.intensity * 4 * Math.PI;
  33811. }
  33812. set power( power ) {
  33813. // set the light's intensity (in candela) from the desired luminous power (in lumens)
  33814. this.intensity = power / ( 4 * Math.PI );
  33815. }
  33816. dispose() {
  33817. this.shadow.dispose();
  33818. }
  33819. copy( source, recursive ) {
  33820. super.copy( source, recursive );
  33821. this.distance = source.distance;
  33822. this.decay = source.decay;
  33823. this.shadow = source.shadow.clone();
  33824. return this;
  33825. }
  33826. }
  33827. /**
  33828. * Camera that uses [orthographic projection](https://en.wikipedia.org/wiki/Orthographic_projection).
  33829. *
  33830. * In this projection mode, an object's size in the rendered image stays
  33831. * constant regardless of its distance from the camera. This can be useful
  33832. * for rendering 2D scenes and UI elements, amongst other things.
  33833. *
  33834. * ```js
  33835. * const camera = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, 1, 1000 );
  33836. * scene.add( camera );
  33837. * ```
  33838. *
  33839. * @augments Camera
  33840. */
  33841. class OrthographicCamera extends Camera {
  33842. /**
  33843. * Constructs a new orthographic camera.
  33844. *
  33845. * @param {number} [left=-1] - The left plane of the camera's frustum.
  33846. * @param {number} [right=1] - The right plane of the camera's frustum.
  33847. * @param {number} [top=1] - The top plane of the camera's frustum.
  33848. * @param {number} [bottom=-1] - The bottom plane of the camera's frustum.
  33849. * @param {number} [near=0.1] - The camera's near plane.
  33850. * @param {number} [far=2000] - The camera's far plane.
  33851. */
  33852. constructor( left = -1, right = 1, top = 1, bottom = -1, near = 0.1, far = 2000 ) {
  33853. super();
  33854. /**
  33855. * This flag can be used for type testing.
  33856. *
  33857. * @type {boolean}
  33858. * @readonly
  33859. * @default true
  33860. */
  33861. this.isOrthographicCamera = true;
  33862. this.type = 'OrthographicCamera';
  33863. /**
  33864. * The zoom factor of the camera.
  33865. *
  33866. * @type {number}
  33867. * @default 1
  33868. */
  33869. this.zoom = 1;
  33870. /**
  33871. * Represents the frustum window specification. This property should not be edited
  33872. * directly but via {@link PerspectiveCamera#setViewOffset} and {@link PerspectiveCamera#clearViewOffset}.
  33873. *
  33874. * @type {?Object}
  33875. * @default null
  33876. */
  33877. this.view = null;
  33878. /**
  33879. * The left plane of the camera's frustum.
  33880. *
  33881. * @type {number}
  33882. * @default -1
  33883. */
  33884. this.left = left;
  33885. /**
  33886. * The right plane of the camera's frustum.
  33887. *
  33888. * @type {number}
  33889. * @default 1
  33890. */
  33891. this.right = right;
  33892. /**
  33893. * The top plane of the camera's frustum.
  33894. *
  33895. * @type {number}
  33896. * @default 1
  33897. */
  33898. this.top = top;
  33899. /**
  33900. * The bottom plane of the camera's frustum.
  33901. *
  33902. * @type {number}
  33903. * @default -1
  33904. */
  33905. this.bottom = bottom;
  33906. /**
  33907. * The camera's near plane. The valid range is greater than `0`
  33908. * and less than the current value of {@link OrthographicCamera#far}.
  33909. *
  33910. * Note that, unlike for the {@link PerspectiveCamera}, `0` is a
  33911. * valid value for an orthographic camera's near plane.
  33912. *
  33913. * @type {number}
  33914. * @default 0.1
  33915. */
  33916. this.near = near;
  33917. /**
  33918. * The camera's far plane. Must be greater than the
  33919. * current value of {@link OrthographicCamera#near}.
  33920. *
  33921. * @type {number}
  33922. * @default 2000
  33923. */
  33924. this.far = far;
  33925. this.updateProjectionMatrix();
  33926. }
  33927. copy( source, recursive ) {
  33928. super.copy( source, recursive );
  33929. this.left = source.left;
  33930. this.right = source.right;
  33931. this.top = source.top;
  33932. this.bottom = source.bottom;
  33933. this.near = source.near;
  33934. this.far = source.far;
  33935. this.zoom = source.zoom;
  33936. this.view = source.view === null ? null : Object.assign( {}, source.view );
  33937. return this;
  33938. }
  33939. /**
  33940. * Sets an offset in a larger frustum. This is useful for multi-window or
  33941. * multi-monitor/multi-machine setups.
  33942. *
  33943. * @param {number} fullWidth - The full width of multiview setup.
  33944. * @param {number} fullHeight - The full height of multiview setup.
  33945. * @param {number} x - The horizontal offset of the subcamera.
  33946. * @param {number} y - The vertical offset of the subcamera.
  33947. * @param {number} width - The width of subcamera.
  33948. * @param {number} height - The height of subcamera.
  33949. * @see {@link PerspectiveCamera#setViewOffset}
  33950. */
  33951. setViewOffset( fullWidth, fullHeight, x, y, width, height ) {
  33952. if ( this.view === null ) {
  33953. this.view = {
  33954. enabled: true,
  33955. fullWidth: 1,
  33956. fullHeight: 1,
  33957. offsetX: 0,
  33958. offsetY: 0,
  33959. width: 1,
  33960. height: 1
  33961. };
  33962. }
  33963. this.view.enabled = true;
  33964. this.view.fullWidth = fullWidth;
  33965. this.view.fullHeight = fullHeight;
  33966. this.view.offsetX = x;
  33967. this.view.offsetY = y;
  33968. this.view.width = width;
  33969. this.view.height = height;
  33970. this.updateProjectionMatrix();
  33971. }
  33972. /**
  33973. * Removes the view offset from the projection matrix.
  33974. */
  33975. clearViewOffset() {
  33976. if ( this.view !== null ) {
  33977. this.view.enabled = false;
  33978. }
  33979. this.updateProjectionMatrix();
  33980. }
  33981. /**
  33982. * Updates the camera's projection matrix. Must be called after any change of
  33983. * camera properties.
  33984. */
  33985. updateProjectionMatrix() {
  33986. const dx = ( this.right - this.left ) / ( 2 * this.zoom );
  33987. const dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  33988. const cx = ( this.right + this.left ) / 2;
  33989. const cy = ( this.top + this.bottom ) / 2;
  33990. let left = cx - dx;
  33991. let right = cx + dx;
  33992. let top = cy + dy;
  33993. let bottom = cy - dy;
  33994. if ( this.view !== null && this.view.enabled ) {
  33995. const scaleW = ( this.right - this.left ) / this.view.fullWidth / this.zoom;
  33996. const scaleH = ( this.top - this.bottom ) / this.view.fullHeight / this.zoom;
  33997. left += scaleW * this.view.offsetX;
  33998. right = left + scaleW * this.view.width;
  33999. top -= scaleH * this.view.offsetY;
  34000. bottom = top - scaleH * this.view.height;
  34001. }
  34002. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far, this.coordinateSystem, this.reversedDepth );
  34003. this.projectionMatrixInverse.copy( this.projectionMatrix ).invert();
  34004. }
  34005. toJSON( meta ) {
  34006. const data = super.toJSON( meta );
  34007. data.object.zoom = this.zoom;
  34008. data.object.left = this.left;
  34009. data.object.right = this.right;
  34010. data.object.top = this.top;
  34011. data.object.bottom = this.bottom;
  34012. data.object.near = this.near;
  34013. data.object.far = this.far;
  34014. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  34015. return data;
  34016. }
  34017. }
  34018. /**
  34019. * Represents the shadow configuration of directional lights.
  34020. *
  34021. * @augments LightShadow
  34022. */
  34023. class DirectionalLightShadow extends LightShadow {
  34024. /**
  34025. * Constructs a new directional light shadow.
  34026. */
  34027. constructor() {
  34028. super( new OrthographicCamera( -5, 5, 5, -5, 0.5, 500 ) );
  34029. /**
  34030. * This flag can be used for type testing.
  34031. *
  34032. * @type {boolean}
  34033. * @readonly
  34034. * @default true
  34035. */
  34036. this.isDirectionalLightShadow = true;
  34037. }
  34038. }
  34039. /**
  34040. * A light that gets emitted in a specific direction. This light will behave
  34041. * as though it is infinitely far away and the rays produced from it are all
  34042. * parallel. The common use case for this is to simulate daylight; the sun is
  34043. * far enough away that its position can be considered to be infinite, and
  34044. * all light rays coming from it are parallel.
  34045. *
  34046. * A common point of confusion for directional lights is that setting the
  34047. * rotation has no effect. This is because three.js's DirectionalLight is the
  34048. * equivalent to what is often called a 'Target Direct Light' in other
  34049. * applications.
  34050. *
  34051. * This means that its direction is calculated as pointing from the light's
  34052. * {@link Object3D#position} to the {@link DirectionalLight#target} position
  34053. * (as opposed to a 'Free Direct Light' that just has a rotation
  34054. * component).
  34055. *
  34056. * This light can cast shadows - see the {@link DirectionalLightShadow} for details.
  34057. *
  34058. * ```js
  34059. * // White directional light at half intensity shining from the top.
  34060. * const directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
  34061. * scene.add( directionalLight );
  34062. * ```
  34063. *
  34064. * @augments Light
  34065. */
  34066. class DirectionalLight extends Light {
  34067. /**
  34068. * Constructs a new directional light.
  34069. *
  34070. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34071. * @param {number} [intensity=1] - The light's strength/intensity.
  34072. */
  34073. constructor( color, intensity ) {
  34074. super( color, intensity );
  34075. /**
  34076. * This flag can be used for type testing.
  34077. *
  34078. * @type {boolean}
  34079. * @readonly
  34080. * @default true
  34081. */
  34082. this.isDirectionalLight = true;
  34083. this.type = 'DirectionalLight';
  34084. this.position.copy( Object3D.DEFAULT_UP );
  34085. this.updateMatrix();
  34086. /**
  34087. * The directional light points from its position to the
  34088. * target's position.
  34089. *
  34090. * For the target's position to be changed to anything other
  34091. * than the default, it must be added to the scene.
  34092. *
  34093. * It is also possible to set the target to be another 3D object
  34094. * in the scene. The light will now track the target object.
  34095. *
  34096. * @type {Object3D}
  34097. */
  34098. this.target = new Object3D();
  34099. /**
  34100. * This property holds the light's shadow configuration.
  34101. *
  34102. * @type {DirectionalLightShadow}
  34103. */
  34104. this.shadow = new DirectionalLightShadow();
  34105. }
  34106. dispose() {
  34107. this.shadow.dispose();
  34108. }
  34109. copy( source ) {
  34110. super.copy( source );
  34111. this.target = source.target.clone();
  34112. this.shadow = source.shadow.clone();
  34113. return this;
  34114. }
  34115. }
  34116. /**
  34117. * This light globally illuminates all objects in the scene equally.
  34118. *
  34119. * It cannot be used to cast shadows as it does not have a direction.
  34120. *
  34121. * ```js
  34122. * const light = new THREE.AmbientLight( 0x404040 ); // soft white light
  34123. * scene.add( light );
  34124. * ```
  34125. *
  34126. * @augments Light
  34127. */
  34128. class AmbientLight extends Light {
  34129. /**
  34130. * Constructs a new ambient light.
  34131. *
  34132. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34133. * @param {number} [intensity=1] - The light's strength/intensity.
  34134. */
  34135. constructor( color, intensity ) {
  34136. super( color, intensity );
  34137. /**
  34138. * This flag can be used for type testing.
  34139. *
  34140. * @type {boolean}
  34141. * @readonly
  34142. * @default true
  34143. */
  34144. this.isAmbientLight = true;
  34145. this.type = 'AmbientLight';
  34146. }
  34147. }
  34148. /**
  34149. * This class emits light uniformly across the face a rectangular plane.
  34150. * This light type can be used to simulate light sources such as bright
  34151. * windows or strip lighting.
  34152. *
  34153. * Important Notes:
  34154. *
  34155. * - There is no shadow support.
  34156. * - Only PBR materials are supported.
  34157. * - You have to include `RectAreaLightUniformsLib` (`WebGLRenderer`) or `RectAreaLightTexturesLib` (`WebGPURenderer`)
  34158. * into your app and init the uniforms/textures.
  34159. *
  34160. * ```js
  34161. * RectAreaLightUniformsLib.init(); // only relevant for WebGLRenderer
  34162. * THREE.RectAreaLightNode.setLTC( RectAreaLightTexturesLib.init() ); // only relevant for WebGPURenderer
  34163. *
  34164. * const intensity = 1; const width = 10; const height = 10;
  34165. * const rectLight = new THREE.RectAreaLight( 0xffffff, intensity, width, height );
  34166. * rectLight.position.set( 5, 5, 0 );
  34167. * rectLight.lookAt( 0, 0, 0 );
  34168. * scene.add( rectLight )
  34169. * ```
  34170. *
  34171. * @augments Light
  34172. */
  34173. class RectAreaLight extends Light {
  34174. /**
  34175. * Constructs a new area light.
  34176. *
  34177. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  34178. * @param {number} [intensity=1] - The light's strength/intensity.
  34179. * @param {number} [width=10] - The width of the light.
  34180. * @param {number} [height=10] - The height of the light.
  34181. */
  34182. constructor( color, intensity, width = 10, height = 10 ) {
  34183. super( color, intensity );
  34184. /**
  34185. * This flag can be used for type testing.
  34186. *
  34187. * @type {boolean}
  34188. * @readonly
  34189. * @default true
  34190. */
  34191. this.isRectAreaLight = true;
  34192. this.type = 'RectAreaLight';
  34193. /**
  34194. * The width of the light.
  34195. *
  34196. * @type {number}
  34197. * @default 10
  34198. */
  34199. this.width = width;
  34200. /**
  34201. * The height of the light.
  34202. *
  34203. * @type {number}
  34204. * @default 10
  34205. */
  34206. this.height = height;
  34207. }
  34208. /**
  34209. * The light's power. Power is the luminous power of the light measured in lumens (lm).
  34210. * Changing the power will also change the light's intensity.
  34211. *
  34212. * @type {number}
  34213. */
  34214. get power() {
  34215. // compute the light's luminous power (in lumens) from its intensity (in nits)
  34216. return this.intensity * this.width * this.height * Math.PI;
  34217. }
  34218. set power( power ) {
  34219. // set the light's intensity (in nits) from the desired luminous power (in lumens)
  34220. this.intensity = power / ( this.width * this.height * Math.PI );
  34221. }
  34222. copy( source ) {
  34223. super.copy( source );
  34224. this.width = source.width;
  34225. this.height = source.height;
  34226. return this;
  34227. }
  34228. toJSON( meta ) {
  34229. const data = super.toJSON( meta );
  34230. data.object.width = this.width;
  34231. data.object.height = this.height;
  34232. return data;
  34233. }
  34234. }
  34235. /**
  34236. * Represents a third-order spherical harmonics (SH). Light probes use this class
  34237. * to encode lighting information.
  34238. *
  34239. * - Primary reference: {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf}
  34240. * - Secondary reference: {@link https://www.ppsloan.org/publications/StupidSH36.pdf}
  34241. */
  34242. class SphericalHarmonics3 {
  34243. /**
  34244. * Constructs a new spherical harmonics.
  34245. */
  34246. constructor() {
  34247. /**
  34248. * This flag can be used for type testing.
  34249. *
  34250. * @type {boolean}
  34251. * @readonly
  34252. * @default true
  34253. */
  34254. this.isSphericalHarmonics3 = true;
  34255. /**
  34256. * An array holding the (9) SH coefficients.
  34257. *
  34258. * @type {Array<Vector3>}
  34259. */
  34260. this.coefficients = [];
  34261. for ( let i = 0; i < 9; i ++ ) {
  34262. this.coefficients.push( new Vector3() );
  34263. }
  34264. }
  34265. /**
  34266. * Sets the given SH coefficients to this instance by copying
  34267. * the values.
  34268. *
  34269. * @param {Array<Vector3>} coefficients - The SH coefficients.
  34270. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34271. */
  34272. set( coefficients ) {
  34273. for ( let i = 0; i < 9; i ++ ) {
  34274. this.coefficients[ i ].copy( coefficients[ i ] );
  34275. }
  34276. return this;
  34277. }
  34278. /**
  34279. * Sets all SH coefficients to `0`.
  34280. *
  34281. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34282. */
  34283. zero() {
  34284. for ( let i = 0; i < 9; i ++ ) {
  34285. this.coefficients[ i ].set( 0, 0, 0 );
  34286. }
  34287. return this;
  34288. }
  34289. /**
  34290. * Returns the radiance in the direction of the given normal.
  34291. *
  34292. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34293. * @param {Vector3} target - The target vector that is used to store the method's result.
  34294. * @return {Vector3} The radiance.
  34295. */
  34296. getAt( normal, target ) {
  34297. // normal is assumed to be unit length
  34298. const x = normal.x, y = normal.y, z = normal.z;
  34299. const coeff = this.coefficients;
  34300. // band 0
  34301. target.copy( coeff[ 0 ] ).multiplyScalar( 0.282095 );
  34302. // band 1
  34303. target.addScaledVector( coeff[ 1 ], 0.488603 * y );
  34304. target.addScaledVector( coeff[ 2 ], 0.488603 * z );
  34305. target.addScaledVector( coeff[ 3 ], 0.488603 * x );
  34306. // band 2
  34307. target.addScaledVector( coeff[ 4 ], 1.092548 * ( x * y ) );
  34308. target.addScaledVector( coeff[ 5 ], 1.092548 * ( y * z ) );
  34309. target.addScaledVector( coeff[ 6 ], 0.315392 * ( 3.0 * z * z - 1.0 ) );
  34310. target.addScaledVector( coeff[ 7 ], 1.092548 * ( x * z ) );
  34311. target.addScaledVector( coeff[ 8 ], 0.546274 * ( x * x - y * y ) );
  34312. return target;
  34313. }
  34314. /**
  34315. * Returns the irradiance (radiance convolved with cosine lobe) in the
  34316. * direction of the given normal.
  34317. *
  34318. * @param {Vector3} normal - The normal vector (assumed to be unit length)
  34319. * @param {Vector3} target - The target vector that is used to store the method's result.
  34320. * @return {Vector3} The irradiance.
  34321. */
  34322. getIrradianceAt( normal, target ) {
  34323. // normal is assumed to be unit length
  34324. const x = normal.x, y = normal.y, z = normal.z;
  34325. const coeff = this.coefficients;
  34326. // band 0
  34327. target.copy( coeff[ 0 ] ).multiplyScalar( 0.886227 ); // π * 0.282095
  34328. // band 1
  34329. target.addScaledVector( coeff[ 1 ], 2.0 * 0.511664 * y ); // ( 2 * π / 3 ) * 0.488603
  34330. target.addScaledVector( coeff[ 2 ], 2.0 * 0.511664 * z );
  34331. target.addScaledVector( coeff[ 3 ], 2.0 * 0.511664 * x );
  34332. // band 2
  34333. target.addScaledVector( coeff[ 4 ], 2.0 * 0.429043 * x * y ); // ( π / 4 ) * 1.092548
  34334. target.addScaledVector( coeff[ 5 ], 2.0 * 0.429043 * y * z );
  34335. target.addScaledVector( coeff[ 6 ], 0.743125 * z * z - 0.247708 ); // ( π / 4 ) * 0.315392 * 3
  34336. target.addScaledVector( coeff[ 7 ], 2.0 * 0.429043 * x * z );
  34337. target.addScaledVector( coeff[ 8 ], 0.429043 * ( x * x - y * y ) ); // ( π / 4 ) * 0.546274
  34338. return target;
  34339. }
  34340. /**
  34341. * Adds the given SH to this instance.
  34342. *
  34343. * @param {SphericalHarmonics3} sh - The SH to add.
  34344. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34345. */
  34346. add( sh ) {
  34347. for ( let i = 0; i < 9; i ++ ) {
  34348. this.coefficients[ i ].add( sh.coefficients[ i ] );
  34349. }
  34350. return this;
  34351. }
  34352. /**
  34353. * A convenience method for performing {@link SphericalHarmonics3#add} and
  34354. * {@link SphericalHarmonics3#scale} at once.
  34355. *
  34356. * @param {SphericalHarmonics3} sh - The SH to add.
  34357. * @param {number} s - The scale factor.
  34358. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34359. */
  34360. addScaledSH( sh, s ) {
  34361. for ( let i = 0; i < 9; i ++ ) {
  34362. this.coefficients[ i ].addScaledVector( sh.coefficients[ i ], s );
  34363. }
  34364. return this;
  34365. }
  34366. /**
  34367. * Scales this SH by the given scale factor.
  34368. *
  34369. * @param {number} s - The scale factor.
  34370. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34371. */
  34372. scale( s ) {
  34373. for ( let i = 0; i < 9; i ++ ) {
  34374. this.coefficients[ i ].multiplyScalar( s );
  34375. }
  34376. return this;
  34377. }
  34378. /**
  34379. * Linear interpolates between the given SH and this instance by the given
  34380. * alpha factor.
  34381. *
  34382. * @param {SphericalHarmonics3} sh - The SH to interpolate with.
  34383. * @param {number} alpha - The alpha factor.
  34384. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34385. */
  34386. lerp( sh, alpha ) {
  34387. for ( let i = 0; i < 9; i ++ ) {
  34388. this.coefficients[ i ].lerp( sh.coefficients[ i ], alpha );
  34389. }
  34390. return this;
  34391. }
  34392. /**
  34393. * Returns `true` if this spherical harmonics is equal with the given one.
  34394. *
  34395. * @param {SphericalHarmonics3} sh - The spherical harmonics to test for equality.
  34396. * @return {boolean} Whether this spherical harmonics is equal with the given one.
  34397. */
  34398. equals( sh ) {
  34399. for ( let i = 0; i < 9; i ++ ) {
  34400. if ( ! this.coefficients[ i ].equals( sh.coefficients[ i ] ) ) {
  34401. return false;
  34402. }
  34403. }
  34404. return true;
  34405. }
  34406. /**
  34407. * Copies the values of the given spherical harmonics to this instance.
  34408. *
  34409. * @param {SphericalHarmonics3} sh - The spherical harmonics to copy.
  34410. * @return {SphericalHarmonics3} A reference to this spherical harmonics.
  34411. */
  34412. copy( sh ) {
  34413. return this.set( sh.coefficients );
  34414. }
  34415. /**
  34416. * Returns a new spherical harmonics with copied values from this instance.
  34417. *
  34418. * @return {SphericalHarmonics3} A clone of this instance.
  34419. */
  34420. clone() {
  34421. return new this.constructor().copy( this );
  34422. }
  34423. /**
  34424. * Sets the SH coefficients of this instance from the given array.
  34425. *
  34426. * @param {Array<number>} array - An array holding the SH coefficients.
  34427. * @param {number} [offset=0] - The array offset where to start copying.
  34428. * @return {SphericalHarmonics3} A clone of this instance.
  34429. */
  34430. fromArray( array, offset = 0 ) {
  34431. const coefficients = this.coefficients;
  34432. for ( let i = 0; i < 9; i ++ ) {
  34433. coefficients[ i ].fromArray( array, offset + ( i * 3 ) );
  34434. }
  34435. return this;
  34436. }
  34437. /**
  34438. * Returns an array with the SH coefficients, or copies them into the provided
  34439. * array. The coefficients are represented as numbers.
  34440. *
  34441. * @param {Array<number>} [array=[]] - The target array.
  34442. * @param {number} [offset=0] - The array offset where to start copying.
  34443. * @return {Array<number>} An array with flat SH coefficients.
  34444. */
  34445. toArray( array = [], offset = 0 ) {
  34446. const coefficients = this.coefficients;
  34447. for ( let i = 0; i < 9; i ++ ) {
  34448. coefficients[ i ].toArray( array, offset + ( i * 3 ) );
  34449. }
  34450. return array;
  34451. }
  34452. /**
  34453. * Computes the SH basis for the given normal vector.
  34454. *
  34455. * @param {Vector3} normal - The normal.
  34456. * @param {Array<number>} shBasis - The target array holding the SH basis.
  34457. */
  34458. static getBasisAt( normal, shBasis ) {
  34459. // normal is assumed to be unit length
  34460. const x = normal.x, y = normal.y, z = normal.z;
  34461. // band 0
  34462. shBasis[ 0 ] = 0.282095;
  34463. // band 1
  34464. shBasis[ 1 ] = 0.488603 * y;
  34465. shBasis[ 2 ] = 0.488603 * z;
  34466. shBasis[ 3 ] = 0.488603 * x;
  34467. // band 2
  34468. shBasis[ 4 ] = 1.092548 * x * y;
  34469. shBasis[ 5 ] = 1.092548 * y * z;
  34470. shBasis[ 6 ] = 0.315392 * ( 3 * z * z - 1 );
  34471. shBasis[ 7 ] = 1.092548 * x * z;
  34472. shBasis[ 8 ] = 0.546274 * ( x * x - y * y );
  34473. }
  34474. }
  34475. /**
  34476. * Light probes are an alternative way of adding light to a 3D scene. Unlike
  34477. * classical light sources (e.g. directional, point or spot lights), light
  34478. * probes do not emit light. Instead they store information about light
  34479. * passing through 3D space. During rendering, the light that hits a 3D
  34480. * object is approximated by using the data from the light probe.
  34481. *
  34482. * Light probes are usually created from (radiance) environment maps. The
  34483. * class {@link LightProbeGenerator} can be used to create light probes from
  34484. * cube textures or render targets. However, light estimation data could also
  34485. * be provided in other forms e.g. by WebXR. This enables the rendering of
  34486. * augmented reality content that reacts to real world lighting.
  34487. *
  34488. * The current probe implementation in three.js supports so-called diffuse
  34489. * light probes. This type of light probe is functionally equivalent to an
  34490. * irradiance environment map.
  34491. *
  34492. * @augments Light
  34493. */
  34494. class LightProbe extends Light {
  34495. /**
  34496. * Constructs a new light probe.
  34497. *
  34498. * @param {SphericalHarmonics3} sh - The spherical harmonics which represents encoded lighting information.
  34499. * @param {number} [intensity=1] - The light's strength/intensity.
  34500. */
  34501. constructor( sh = new SphericalHarmonics3(), intensity = 1 ) {
  34502. super( undefined, intensity );
  34503. /**
  34504. * This flag can be used for type testing.
  34505. *
  34506. * @type {boolean}
  34507. * @readonly
  34508. * @default true
  34509. */
  34510. this.isLightProbe = true;
  34511. /**
  34512. * A light probe uses spherical harmonics to encode lighting information.
  34513. *
  34514. * @type {SphericalHarmonics3}
  34515. */
  34516. this.sh = sh;
  34517. }
  34518. copy( source ) {
  34519. super.copy( source );
  34520. this.sh.copy( source.sh );
  34521. return this;
  34522. }
  34523. /**
  34524. * Deserializes the light prove from the given JSON.
  34525. *
  34526. * @param {Object} json - The JSON holding the serialized light probe.
  34527. * @return {LightProbe} A reference to this light probe.
  34528. */
  34529. fromJSON( json ) {
  34530. this.intensity = json.intensity; // TODO: Move this bit to Light.fromJSON();
  34531. this.sh.fromArray( json.sh );
  34532. return this;
  34533. }
  34534. toJSON( meta ) {
  34535. const data = super.toJSON( meta );
  34536. data.object.sh = this.sh.toArray();
  34537. return data;
  34538. }
  34539. }
  34540. /**
  34541. * Class for loading materials. The files are internally
  34542. * loaded via {@link FileLoader}.
  34543. *
  34544. * ```js
  34545. * const loader = new THREE.MaterialLoader();
  34546. * const material = await loader.loadAsync( 'material.json' );
  34547. * ```
  34548. * This loader does not support node materials. Use {@link NodeMaterialLoader} instead.
  34549. *
  34550. * @augments Loader
  34551. */
  34552. class MaterialLoader extends Loader {
  34553. /**
  34554. * Constructs a new material loader.
  34555. *
  34556. * @param {LoadingManager} [manager] - The loading manager.
  34557. */
  34558. constructor( manager ) {
  34559. super( manager );
  34560. /**
  34561. * A dictionary holding textures used by the material.
  34562. *
  34563. * @type {Object<string,Texture>}
  34564. */
  34565. this.textures = {};
  34566. }
  34567. /**
  34568. * Starts loading from the given URL and pass the loaded material to the `onLoad()` callback.
  34569. *
  34570. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34571. * @param {function(Material)} onLoad - Executed when the loading process has been finished.
  34572. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34573. * @param {onErrorCallback} onError - Executed when errors occur.
  34574. */
  34575. load( url, onLoad, onProgress, onError ) {
  34576. const scope = this;
  34577. const loader = new FileLoader( scope.manager );
  34578. loader.setPath( scope.path );
  34579. loader.setRequestHeader( scope.requestHeader );
  34580. loader.setWithCredentials( scope.withCredentials );
  34581. loader.load( url, function ( text ) {
  34582. try {
  34583. onLoad( scope.parse( JSON.parse( text ) ) );
  34584. } catch ( e ) {
  34585. if ( onError ) {
  34586. onError( e );
  34587. } else {
  34588. error( e );
  34589. }
  34590. scope.manager.itemError( url );
  34591. }
  34592. }, onProgress, onError );
  34593. }
  34594. /**
  34595. * Parses the given JSON object and returns a material.
  34596. *
  34597. * @param {Object} json - The serialized material.
  34598. * @return {Material} The parsed material.
  34599. */
  34600. parse( json ) {
  34601. const textures = this.textures;
  34602. function getTexture( name ) {
  34603. if ( textures[ name ] === undefined ) {
  34604. warn( 'MaterialLoader: Undefined texture', name );
  34605. }
  34606. return textures[ name ];
  34607. }
  34608. const material = this.createMaterialFromType( json.type );
  34609. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  34610. if ( json.name !== undefined ) material.name = json.name;
  34611. if ( json.color !== undefined && material.color !== undefined ) material.color.setHex( json.color );
  34612. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  34613. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  34614. if ( json.sheen !== undefined ) material.sheen = json.sheen;
  34615. if ( json.sheenColor !== undefined ) material.sheenColor = new Color().setHex( json.sheenColor );
  34616. if ( json.sheenRoughness !== undefined ) material.sheenRoughness = json.sheenRoughness;
  34617. if ( json.emissive !== undefined && material.emissive !== undefined ) material.emissive.setHex( json.emissive );
  34618. if ( json.specular !== undefined && material.specular !== undefined ) material.specular.setHex( json.specular );
  34619. if ( json.specularIntensity !== undefined ) material.specularIntensity = json.specularIntensity;
  34620. if ( json.specularColor !== undefined && material.specularColor !== undefined ) material.specularColor.setHex( json.specularColor );
  34621. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  34622. if ( json.clearcoat !== undefined ) material.clearcoat = json.clearcoat;
  34623. if ( json.clearcoatRoughness !== undefined ) material.clearcoatRoughness = json.clearcoatRoughness;
  34624. if ( json.dispersion !== undefined ) material.dispersion = json.dispersion;
  34625. if ( json.iridescence !== undefined ) material.iridescence = json.iridescence;
  34626. if ( json.iridescenceIOR !== undefined ) material.iridescenceIOR = json.iridescenceIOR;
  34627. if ( json.iridescenceThicknessRange !== undefined ) material.iridescenceThicknessRange = json.iridescenceThicknessRange;
  34628. if ( json.transmission !== undefined ) material.transmission = json.transmission;
  34629. if ( json.thickness !== undefined ) material.thickness = json.thickness;
  34630. if ( json.attenuationDistance !== undefined ) material.attenuationDistance = json.attenuationDistance;
  34631. if ( json.attenuationColor !== undefined && material.attenuationColor !== undefined ) material.attenuationColor.setHex( json.attenuationColor );
  34632. if ( json.anisotropy !== undefined ) material.anisotropy = json.anisotropy;
  34633. if ( json.anisotropyRotation !== undefined ) material.anisotropyRotation = json.anisotropyRotation;
  34634. if ( json.fog !== undefined ) material.fog = json.fog;
  34635. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  34636. if ( json.blending !== undefined ) material.blending = json.blending;
  34637. if ( json.combine !== undefined ) material.combine = json.combine;
  34638. if ( json.side !== undefined ) material.side = json.side;
  34639. if ( json.shadowSide !== undefined ) material.shadowSide = json.shadowSide;
  34640. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  34641. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  34642. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  34643. if ( json.alphaHash !== undefined ) material.alphaHash = json.alphaHash;
  34644. if ( json.depthFunc !== undefined ) material.depthFunc = json.depthFunc;
  34645. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  34646. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  34647. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  34648. if ( json.blendSrc !== undefined ) material.blendSrc = json.blendSrc;
  34649. if ( json.blendDst !== undefined ) material.blendDst = json.blendDst;
  34650. if ( json.blendEquation !== undefined ) material.blendEquation = json.blendEquation;
  34651. if ( json.blendSrcAlpha !== undefined ) material.blendSrcAlpha = json.blendSrcAlpha;
  34652. if ( json.blendDstAlpha !== undefined ) material.blendDstAlpha = json.blendDstAlpha;
  34653. if ( json.blendEquationAlpha !== undefined ) material.blendEquationAlpha = json.blendEquationAlpha;
  34654. if ( json.blendColor !== undefined && material.blendColor !== undefined ) material.blendColor.setHex( json.blendColor );
  34655. if ( json.blendAlpha !== undefined ) material.blendAlpha = json.blendAlpha;
  34656. if ( json.stencilWriteMask !== undefined ) material.stencilWriteMask = json.stencilWriteMask;
  34657. if ( json.stencilFunc !== undefined ) material.stencilFunc = json.stencilFunc;
  34658. if ( json.stencilRef !== undefined ) material.stencilRef = json.stencilRef;
  34659. if ( json.stencilFuncMask !== undefined ) material.stencilFuncMask = json.stencilFuncMask;
  34660. if ( json.stencilFail !== undefined ) material.stencilFail = json.stencilFail;
  34661. if ( json.stencilZFail !== undefined ) material.stencilZFail = json.stencilZFail;
  34662. if ( json.stencilZPass !== undefined ) material.stencilZPass = json.stencilZPass;
  34663. if ( json.stencilWrite !== undefined ) material.stencilWrite = json.stencilWrite;
  34664. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  34665. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  34666. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  34667. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  34668. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  34669. if ( json.linewidth !== undefined ) material.linewidth = json.linewidth;
  34670. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  34671. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  34672. if ( json.scale !== undefined ) material.scale = json.scale;
  34673. if ( json.polygonOffset !== undefined ) material.polygonOffset = json.polygonOffset;
  34674. if ( json.polygonOffsetFactor !== undefined ) material.polygonOffsetFactor = json.polygonOffsetFactor;
  34675. if ( json.polygonOffsetUnits !== undefined ) material.polygonOffsetUnits = json.polygonOffsetUnits;
  34676. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  34677. if ( json.alphaToCoverage !== undefined ) material.alphaToCoverage = json.alphaToCoverage;
  34678. if ( json.premultipliedAlpha !== undefined ) material.premultipliedAlpha = json.premultipliedAlpha;
  34679. if ( json.forceSinglePass !== undefined ) material.forceSinglePass = json.forceSinglePass;
  34680. if ( json.allowOverride !== undefined ) material.allowOverride = json.allowOverride;
  34681. if ( json.visible !== undefined ) material.visible = json.visible;
  34682. if ( json.toneMapped !== undefined ) material.toneMapped = json.toneMapped;
  34683. if ( json.userData !== undefined ) material.userData = json.userData;
  34684. if ( json.vertexColors !== undefined ) {
  34685. if ( typeof json.vertexColors === 'number' ) {
  34686. material.vertexColors = ( json.vertexColors > 0 ) ? true : false;
  34687. } else {
  34688. material.vertexColors = json.vertexColors;
  34689. }
  34690. }
  34691. // Shader Material
  34692. if ( json.uniforms !== undefined ) {
  34693. for ( const name in json.uniforms ) {
  34694. const uniform = json.uniforms[ name ];
  34695. material.uniforms[ name ] = {};
  34696. switch ( uniform.type ) {
  34697. case 't':
  34698. material.uniforms[ name ].value = getTexture( uniform.value );
  34699. break;
  34700. case 'c':
  34701. material.uniforms[ name ].value = new Color().setHex( uniform.value );
  34702. break;
  34703. case 'v2':
  34704. material.uniforms[ name ].value = new Vector2().fromArray( uniform.value );
  34705. break;
  34706. case 'v3':
  34707. material.uniforms[ name ].value = new Vector3().fromArray( uniform.value );
  34708. break;
  34709. case 'v4':
  34710. material.uniforms[ name ].value = new Vector4().fromArray( uniform.value );
  34711. break;
  34712. case 'm3':
  34713. material.uniforms[ name ].value = new Matrix3().fromArray( uniform.value );
  34714. break;
  34715. case 'm4':
  34716. material.uniforms[ name ].value = new Matrix4().fromArray( uniform.value );
  34717. break;
  34718. default:
  34719. material.uniforms[ name ].value = uniform.value;
  34720. }
  34721. }
  34722. }
  34723. if ( json.defines !== undefined ) material.defines = json.defines;
  34724. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  34725. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  34726. if ( json.glslVersion !== undefined ) material.glslVersion = json.glslVersion;
  34727. if ( json.extensions !== undefined ) {
  34728. for ( const key in json.extensions ) {
  34729. material.extensions[ key ] = json.extensions[ key ];
  34730. }
  34731. }
  34732. if ( json.lights !== undefined ) material.lights = json.lights;
  34733. if ( json.clipping !== undefined ) material.clipping = json.clipping;
  34734. // for PointsMaterial
  34735. if ( json.size !== undefined ) material.size = json.size;
  34736. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  34737. // maps
  34738. if ( json.map !== undefined ) material.map = getTexture( json.map );
  34739. if ( json.matcap !== undefined ) material.matcap = getTexture( json.matcap );
  34740. if ( json.alphaMap !== undefined ) material.alphaMap = getTexture( json.alphaMap );
  34741. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  34742. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  34743. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  34744. if ( json.normalMapType !== undefined ) material.normalMapType = json.normalMapType;
  34745. if ( json.normalScale !== undefined ) {
  34746. let normalScale = json.normalScale;
  34747. if ( Array.isArray( normalScale ) === false ) {
  34748. // Blender exporter used to export a scalar. See #7459
  34749. normalScale = [ normalScale, normalScale ];
  34750. }
  34751. material.normalScale = new Vector2().fromArray( normalScale );
  34752. }
  34753. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  34754. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  34755. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  34756. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  34757. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  34758. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  34759. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  34760. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  34761. if ( json.specularIntensityMap !== undefined ) material.specularIntensityMap = getTexture( json.specularIntensityMap );
  34762. if ( json.specularColorMap !== undefined ) material.specularColorMap = getTexture( json.specularColorMap );
  34763. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  34764. if ( json.envMapRotation !== undefined ) material.envMapRotation.fromArray( json.envMapRotation );
  34765. if ( json.envMapIntensity !== undefined ) material.envMapIntensity = json.envMapIntensity;
  34766. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  34767. if ( json.refractionRatio !== undefined ) material.refractionRatio = json.refractionRatio;
  34768. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  34769. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  34770. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  34771. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  34772. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  34773. if ( json.clearcoatMap !== undefined ) material.clearcoatMap = getTexture( json.clearcoatMap );
  34774. if ( json.clearcoatRoughnessMap !== undefined ) material.clearcoatRoughnessMap = getTexture( json.clearcoatRoughnessMap );
  34775. if ( json.clearcoatNormalMap !== undefined ) material.clearcoatNormalMap = getTexture( json.clearcoatNormalMap );
  34776. if ( json.clearcoatNormalScale !== undefined ) material.clearcoatNormalScale = new Vector2().fromArray( json.clearcoatNormalScale );
  34777. if ( json.iridescenceMap !== undefined ) material.iridescenceMap = getTexture( json.iridescenceMap );
  34778. if ( json.iridescenceThicknessMap !== undefined ) material.iridescenceThicknessMap = getTexture( json.iridescenceThicknessMap );
  34779. if ( json.transmissionMap !== undefined ) material.transmissionMap = getTexture( json.transmissionMap );
  34780. if ( json.thicknessMap !== undefined ) material.thicknessMap = getTexture( json.thicknessMap );
  34781. if ( json.anisotropyMap !== undefined ) material.anisotropyMap = getTexture( json.anisotropyMap );
  34782. if ( json.sheenColorMap !== undefined ) material.sheenColorMap = getTexture( json.sheenColorMap );
  34783. if ( json.sheenRoughnessMap !== undefined ) material.sheenRoughnessMap = getTexture( json.sheenRoughnessMap );
  34784. return material;
  34785. }
  34786. /**
  34787. * Textures are not embedded in the material JSON so they have
  34788. * to be injected before the loading process starts.
  34789. *
  34790. * @param {Object} value - A dictionary holding textures for material properties.
  34791. * @return {MaterialLoader} A reference to this material loader.
  34792. */
  34793. setTextures( value ) {
  34794. this.textures = value;
  34795. return this;
  34796. }
  34797. /**
  34798. * Creates a material for the given type.
  34799. *
  34800. * @param {string} type - The material type.
  34801. * @return {Material} The new material.
  34802. */
  34803. createMaterialFromType( type ) {
  34804. return MaterialLoader.createMaterialFromType( type );
  34805. }
  34806. /**
  34807. * Creates a material for the given type.
  34808. *
  34809. * @static
  34810. * @param {string} type - The material type.
  34811. * @return {Material} The new material.
  34812. */
  34813. static createMaterialFromType( type ) {
  34814. const materialLib = {
  34815. ShadowMaterial,
  34816. SpriteMaterial,
  34817. RawShaderMaterial,
  34818. ShaderMaterial,
  34819. PointsMaterial,
  34820. MeshPhysicalMaterial,
  34821. MeshStandardMaterial,
  34822. MeshPhongMaterial,
  34823. MeshToonMaterial,
  34824. MeshNormalMaterial,
  34825. MeshLambertMaterial,
  34826. MeshDepthMaterial,
  34827. MeshDistanceMaterial,
  34828. MeshBasicMaterial,
  34829. MeshMatcapMaterial,
  34830. LineDashedMaterial,
  34831. LineBasicMaterial,
  34832. Material
  34833. };
  34834. return new materialLib[ type ]();
  34835. }
  34836. }
  34837. /**
  34838. * A class with loader utility functions.
  34839. */
  34840. class LoaderUtils {
  34841. /**
  34842. * Extracts the base URL from the given URL.
  34843. *
  34844. * @param {string} url -The URL to extract the base URL from.
  34845. * @return {string} The extracted base URL.
  34846. */
  34847. static extractUrlBase( url ) {
  34848. const index = url.lastIndexOf( '/' );
  34849. if ( index === -1 ) return './';
  34850. return url.slice( 0, index + 1 );
  34851. }
  34852. /**
  34853. * Resolves relative URLs against the given path. Absolute paths, data urls,
  34854. * and blob URLs will be returned as is. Invalid URLs will return an empty
  34855. * string.
  34856. *
  34857. * @param {string} url -The URL to resolve.
  34858. * @param {string} path - The base path for relative URLs to be resolved against.
  34859. * @return {string} The resolved URL.
  34860. */
  34861. static resolveURL( url, path ) {
  34862. // Invalid URL
  34863. if ( typeof url !== 'string' || url === '' ) return '';
  34864. // Host Relative URL
  34865. if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) {
  34866. path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' );
  34867. }
  34868. // Absolute URL http://,https://,//
  34869. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34870. // Data URI
  34871. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34872. // Blob URL
  34873. if ( /^blob:.*$/i.test( url ) ) return url;
  34874. // Relative URL
  34875. return path + url;
  34876. }
  34877. }
  34878. /**
  34879. * An instanced version of a geometry.
  34880. */
  34881. class InstancedBufferGeometry extends BufferGeometry {
  34882. /**
  34883. * Constructs a new instanced buffer geometry.
  34884. */
  34885. constructor() {
  34886. super();
  34887. /**
  34888. * This flag can be used for type testing.
  34889. *
  34890. * @type {boolean}
  34891. * @readonly
  34892. * @default true
  34893. */
  34894. this.isInstancedBufferGeometry = true;
  34895. this.type = 'InstancedBufferGeometry';
  34896. /**
  34897. * The instance count.
  34898. *
  34899. * @type {number}
  34900. * @default Infinity
  34901. */
  34902. this.instanceCount = Infinity;
  34903. }
  34904. copy( source ) {
  34905. super.copy( source );
  34906. this.instanceCount = source.instanceCount;
  34907. return this;
  34908. }
  34909. toJSON() {
  34910. const data = super.toJSON();
  34911. data.instanceCount = this.instanceCount;
  34912. data.isInstancedBufferGeometry = true;
  34913. return data;
  34914. }
  34915. }
  34916. /**
  34917. * Class for loading geometries. The files are internally
  34918. * loaded via {@link FileLoader}.
  34919. *
  34920. * ```js
  34921. * const loader = new THREE.BufferGeometryLoader();
  34922. * const geometry = await loader.loadAsync( 'models/json/pressure.json' );
  34923. *
  34924. * const material = new THREE.MeshBasicMaterial( { color: 0xF5F5F5 } );
  34925. * const object = new THREE.Mesh( geometry, material );
  34926. * scene.add( object );
  34927. * ```
  34928. *
  34929. * @augments Loader
  34930. */
  34931. class BufferGeometryLoader extends Loader {
  34932. /**
  34933. * Constructs a new geometry loader.
  34934. *
  34935. * @param {LoadingManager} [manager] - The loading manager.
  34936. */
  34937. constructor( manager ) {
  34938. super( manager );
  34939. }
  34940. /**
  34941. * Starts loading from the given URL and pass the loaded geometry to the `onLoad()` callback.
  34942. *
  34943. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  34944. * @param {function(BufferGeometry)} onLoad - Executed when the loading process has been finished.
  34945. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  34946. * @param {onErrorCallback} onError - Executed when errors occur.
  34947. */
  34948. load( url, onLoad, onProgress, onError ) {
  34949. const scope = this;
  34950. const loader = new FileLoader( scope.manager );
  34951. loader.setPath( scope.path );
  34952. loader.setRequestHeader( scope.requestHeader );
  34953. loader.setWithCredentials( scope.withCredentials );
  34954. loader.load( url, function ( text ) {
  34955. try {
  34956. onLoad( scope.parse( JSON.parse( text ) ) );
  34957. } catch ( e ) {
  34958. if ( onError ) {
  34959. onError( e );
  34960. } else {
  34961. error( e );
  34962. }
  34963. scope.manager.itemError( url );
  34964. }
  34965. }, onProgress, onError );
  34966. }
  34967. /**
  34968. * Parses the given JSON object and returns a geometry.
  34969. *
  34970. * @param {Object} json - The serialized geometry.
  34971. * @return {BufferGeometry} The parsed geometry.
  34972. */
  34973. parse( json ) {
  34974. const interleavedBufferMap = {};
  34975. const arrayBufferMap = {};
  34976. function getInterleavedBuffer( json, uuid ) {
  34977. if ( interleavedBufferMap[ uuid ] !== undefined ) return interleavedBufferMap[ uuid ];
  34978. const interleavedBuffers = json.interleavedBuffers;
  34979. const interleavedBuffer = interleavedBuffers[ uuid ];
  34980. const buffer = getArrayBuffer( json, interleavedBuffer.buffer );
  34981. const array = getTypedArray( interleavedBuffer.type, buffer );
  34982. const ib = new InterleavedBuffer( array, interleavedBuffer.stride );
  34983. ib.uuid = interleavedBuffer.uuid;
  34984. interleavedBufferMap[ uuid ] = ib;
  34985. return ib;
  34986. }
  34987. function getArrayBuffer( json, uuid ) {
  34988. if ( arrayBufferMap[ uuid ] !== undefined ) return arrayBufferMap[ uuid ];
  34989. const arrayBuffers = json.arrayBuffers;
  34990. const arrayBuffer = arrayBuffers[ uuid ];
  34991. const ab = new Uint32Array( arrayBuffer ).buffer;
  34992. arrayBufferMap[ uuid ] = ab;
  34993. return ab;
  34994. }
  34995. const geometry = json.isInstancedBufferGeometry ? new InstancedBufferGeometry() : new BufferGeometry();
  34996. const index = json.data.index;
  34997. if ( index !== undefined ) {
  34998. const typedArray = getTypedArray( index.type, index.array );
  34999. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  35000. }
  35001. const attributes = json.data.attributes;
  35002. for ( const key in attributes ) {
  35003. const attribute = attributes[ key ];
  35004. let bufferAttribute;
  35005. if ( attribute.isInterleavedBufferAttribute ) {
  35006. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35007. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35008. } else {
  35009. const typedArray = getTypedArray( attribute.type, attribute.array );
  35010. const bufferAttributeConstr = attribute.isInstancedBufferAttribute ? InstancedBufferAttribute : BufferAttribute;
  35011. bufferAttribute = new bufferAttributeConstr( typedArray, attribute.itemSize, attribute.normalized );
  35012. }
  35013. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35014. if ( attribute.usage !== undefined ) bufferAttribute.setUsage( attribute.usage );
  35015. geometry.setAttribute( key, bufferAttribute );
  35016. }
  35017. const morphAttributes = json.data.morphAttributes;
  35018. if ( morphAttributes ) {
  35019. for ( const key in morphAttributes ) {
  35020. const attributeArray = morphAttributes[ key ];
  35021. const array = [];
  35022. for ( let i = 0, il = attributeArray.length; i < il; i ++ ) {
  35023. const attribute = attributeArray[ i ];
  35024. let bufferAttribute;
  35025. if ( attribute.isInterleavedBufferAttribute ) {
  35026. const interleavedBuffer = getInterleavedBuffer( json.data, attribute.data );
  35027. bufferAttribute = new InterleavedBufferAttribute( interleavedBuffer, attribute.itemSize, attribute.offset, attribute.normalized );
  35028. } else {
  35029. const typedArray = getTypedArray( attribute.type, attribute.array );
  35030. bufferAttribute = new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized );
  35031. }
  35032. if ( attribute.name !== undefined ) bufferAttribute.name = attribute.name;
  35033. array.push( bufferAttribute );
  35034. }
  35035. geometry.morphAttributes[ key ] = array;
  35036. }
  35037. }
  35038. const morphTargetsRelative = json.data.morphTargetsRelative;
  35039. if ( morphTargetsRelative ) {
  35040. geometry.morphTargetsRelative = true;
  35041. }
  35042. const groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  35043. if ( groups !== undefined ) {
  35044. for ( let i = 0, n = groups.length; i !== n; ++ i ) {
  35045. const group = groups[ i ];
  35046. geometry.addGroup( group.start, group.count, group.materialIndex );
  35047. }
  35048. }
  35049. const boundingSphere = json.data.boundingSphere;
  35050. if ( boundingSphere !== undefined ) {
  35051. geometry.boundingSphere = new Sphere().fromJSON( boundingSphere );
  35052. }
  35053. if ( json.name ) geometry.name = json.name;
  35054. if ( json.userData ) geometry.userData = json.userData;
  35055. return geometry;
  35056. }
  35057. }
  35058. /**
  35059. * 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).
  35060. * The files are internally loaded via {@link FileLoader}.
  35061. *
  35062. * ```js
  35063. * const loader = new THREE.ObjectLoader();
  35064. * const obj = await loader.loadAsync( 'models/json/example.json' );
  35065. * scene.add( obj );
  35066. *
  35067. * // Alternatively, to parse a previously loaded JSON structure
  35068. * const object = await loader.parseAsync( a_json_object );
  35069. * scene.add( object );
  35070. * ```
  35071. *
  35072. * @augments Loader
  35073. */
  35074. class ObjectLoader extends Loader {
  35075. /**
  35076. * Constructs a new object loader.
  35077. *
  35078. * @param {LoadingManager} [manager] - The loading manager.
  35079. */
  35080. constructor( manager ) {
  35081. super( manager );
  35082. }
  35083. /**
  35084. * Starts loading from the given URL and pass the loaded 3D object to the `onLoad()` callback.
  35085. *
  35086. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35087. * @param {function(Object3D)} onLoad - Executed when the loading process has been finished.
  35088. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35089. * @param {onErrorCallback} onError - Executed when errors occur.
  35090. */
  35091. load( url, onLoad, onProgress, onError ) {
  35092. const scope = this;
  35093. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35094. this.resourcePath = this.resourcePath || path;
  35095. const loader = new FileLoader( this.manager );
  35096. loader.setPath( this.path );
  35097. loader.setRequestHeader( this.requestHeader );
  35098. loader.setWithCredentials( this.withCredentials );
  35099. loader.load( url, function ( text ) {
  35100. let json = null;
  35101. try {
  35102. json = JSON.parse( text );
  35103. } catch ( error ) {
  35104. if ( onError !== undefined ) onError( error );
  35105. error( 'ObjectLoader: Can\'t parse ' + url + '.', error.message );
  35106. return;
  35107. }
  35108. const metadata = json.metadata;
  35109. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35110. if ( onError !== undefined ) onError( new Error( 'THREE.ObjectLoader: Can\'t load ' + url ) );
  35111. error( 'ObjectLoader: Can\'t load ' + url );
  35112. return;
  35113. }
  35114. scope.parse( json, onLoad );
  35115. }, onProgress, onError );
  35116. }
  35117. /**
  35118. * Async version of {@link ObjectLoader#load}.
  35119. *
  35120. * @async
  35121. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35122. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35123. * @return {Promise<Object3D>} A Promise that resolves with the loaded 3D object.
  35124. */
  35125. async loadAsync( url, onProgress ) {
  35126. const scope = this;
  35127. const path = ( this.path === '' ) ? LoaderUtils.extractUrlBase( url ) : this.path;
  35128. this.resourcePath = this.resourcePath || path;
  35129. const loader = new FileLoader( this.manager );
  35130. loader.setPath( this.path );
  35131. loader.setRequestHeader( this.requestHeader );
  35132. loader.setWithCredentials( this.withCredentials );
  35133. const text = await loader.loadAsync( url, onProgress );
  35134. const json = JSON.parse( text );
  35135. const metadata = json.metadata;
  35136. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  35137. throw new Error( 'THREE.ObjectLoader: Can\'t load ' + url );
  35138. }
  35139. return await scope.parseAsync( json );
  35140. }
  35141. /**
  35142. * Parses the given JSON. This is used internally by {@link ObjectLoader#load}
  35143. * but can also be used directly to parse a previously loaded JSON structure.
  35144. *
  35145. * @param {Object} json - The serialized 3D object.
  35146. * @param {onLoad} onLoad - Executed when all resources (e.g. textures) have been fully loaded.
  35147. * @return {Object3D} The parsed 3D object.
  35148. */
  35149. parse( json, onLoad ) {
  35150. const animations = this.parseAnimations( json.animations );
  35151. const shapes = this.parseShapes( json.shapes );
  35152. const geometries = this.parseGeometries( json.geometries, shapes );
  35153. const images = this.parseImages( json.images, function () {
  35154. if ( onLoad !== undefined ) onLoad( object );
  35155. } );
  35156. const textures = this.parseTextures( json.textures, images );
  35157. const materials = this.parseMaterials( json.materials, textures );
  35158. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35159. const skeletons = this.parseSkeletons( json.skeletons, object );
  35160. this.bindSkeletons( object, skeletons );
  35161. this.bindLightTargets( object );
  35162. //
  35163. if ( onLoad !== undefined ) {
  35164. let hasImages = false;
  35165. for ( const uuid in images ) {
  35166. if ( images[ uuid ].data instanceof HTMLImageElement ) {
  35167. hasImages = true;
  35168. break;
  35169. }
  35170. }
  35171. if ( hasImages === false ) onLoad( object );
  35172. }
  35173. return object;
  35174. }
  35175. /**
  35176. * Async version of {@link ObjectLoader#parse}.
  35177. *
  35178. * @param {Object} json - The serialized 3D object.
  35179. * @return {Promise<Object3D>} A Promise that resolves with the parsed 3D object.
  35180. */
  35181. async parseAsync( json ) {
  35182. const animations = this.parseAnimations( json.animations );
  35183. const shapes = this.parseShapes( json.shapes );
  35184. const geometries = this.parseGeometries( json.geometries, shapes );
  35185. const images = await this.parseImagesAsync( json.images );
  35186. const textures = this.parseTextures( json.textures, images );
  35187. const materials = this.parseMaterials( json.materials, textures );
  35188. const object = this.parseObject( json.object, geometries, materials, textures, animations );
  35189. const skeletons = this.parseSkeletons( json.skeletons, object );
  35190. this.bindSkeletons( object, skeletons );
  35191. this.bindLightTargets( object );
  35192. return object;
  35193. }
  35194. // internals
  35195. parseShapes( json ) {
  35196. const shapes = {};
  35197. if ( json !== undefined ) {
  35198. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35199. const shape = new Shape().fromJSON( json[ i ] );
  35200. shapes[ shape.uuid ] = shape;
  35201. }
  35202. }
  35203. return shapes;
  35204. }
  35205. parseSkeletons( json, object ) {
  35206. const skeletons = {};
  35207. const bones = {};
  35208. // generate bone lookup table
  35209. object.traverse( function ( child ) {
  35210. if ( child.isBone ) bones[ child.uuid ] = child;
  35211. } );
  35212. // create skeletons
  35213. if ( json !== undefined ) {
  35214. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35215. const skeleton = new Skeleton().fromJSON( json[ i ], bones );
  35216. skeletons[ skeleton.uuid ] = skeleton;
  35217. }
  35218. }
  35219. return skeletons;
  35220. }
  35221. parseGeometries( json, shapes ) {
  35222. const geometries = {};
  35223. if ( json !== undefined ) {
  35224. const bufferGeometryLoader = new BufferGeometryLoader();
  35225. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35226. let geometry;
  35227. const data = json[ i ];
  35228. switch ( data.type ) {
  35229. case 'BufferGeometry':
  35230. case 'InstancedBufferGeometry':
  35231. geometry = bufferGeometryLoader.parse( data );
  35232. break;
  35233. default:
  35234. if ( data.type in Geometries ) {
  35235. geometry = Geometries[ data.type ].fromJSON( data, shapes );
  35236. } else {
  35237. warn( `ObjectLoader: Unsupported geometry type "${ data.type }"` );
  35238. }
  35239. }
  35240. geometry.uuid = data.uuid;
  35241. if ( data.name !== undefined ) geometry.name = data.name;
  35242. if ( data.userData !== undefined ) geometry.userData = data.userData;
  35243. geometries[ data.uuid ] = geometry;
  35244. }
  35245. }
  35246. return geometries;
  35247. }
  35248. parseMaterials( json, textures ) {
  35249. const cache = {}; // MultiMaterial
  35250. const materials = {};
  35251. if ( json !== undefined ) {
  35252. const loader = new MaterialLoader();
  35253. loader.setTextures( textures );
  35254. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35255. const data = json[ i ];
  35256. if ( cache[ data.uuid ] === undefined ) {
  35257. cache[ data.uuid ] = loader.parse( data );
  35258. }
  35259. materials[ data.uuid ] = cache[ data.uuid ];
  35260. }
  35261. }
  35262. return materials;
  35263. }
  35264. parseAnimations( json ) {
  35265. const animations = {};
  35266. if ( json !== undefined ) {
  35267. for ( let i = 0; i < json.length; i ++ ) {
  35268. const data = json[ i ];
  35269. const clip = AnimationClip.parse( data );
  35270. animations[ clip.uuid ] = clip;
  35271. }
  35272. }
  35273. return animations;
  35274. }
  35275. parseImages( json, onLoad ) {
  35276. const scope = this;
  35277. const images = {};
  35278. let loader;
  35279. function loadImage( url ) {
  35280. scope.manager.itemStart( url );
  35281. return loader.load( url, function () {
  35282. scope.manager.itemEnd( url );
  35283. }, undefined, function () {
  35284. scope.manager.itemError( url );
  35285. scope.manager.itemEnd( url );
  35286. } );
  35287. }
  35288. function deserializeImage( image ) {
  35289. if ( typeof image === 'string' ) {
  35290. const url = image;
  35291. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35292. return loadImage( path );
  35293. } else {
  35294. if ( image.data ) {
  35295. return {
  35296. data: getTypedArray( image.type, image.data ),
  35297. width: image.width,
  35298. height: image.height
  35299. };
  35300. } else {
  35301. return null;
  35302. }
  35303. }
  35304. }
  35305. if ( json !== undefined && json.length > 0 ) {
  35306. const manager = new LoadingManager( onLoad );
  35307. loader = new ImageLoader( manager );
  35308. loader.setCrossOrigin( this.crossOrigin );
  35309. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35310. const image = json[ i ];
  35311. const url = image.url;
  35312. if ( Array.isArray( url ) ) {
  35313. // load array of images e.g CubeTexture
  35314. const imageArray = [];
  35315. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35316. const currentUrl = url[ j ];
  35317. const deserializedImage = deserializeImage( currentUrl );
  35318. if ( deserializedImage !== null ) {
  35319. if ( deserializedImage instanceof HTMLImageElement ) {
  35320. imageArray.push( deserializedImage );
  35321. } else {
  35322. // special case: handle array of data textures for cube textures
  35323. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35324. }
  35325. }
  35326. }
  35327. images[ image.uuid ] = new Source( imageArray );
  35328. } else {
  35329. // load single image
  35330. const deserializedImage = deserializeImage( image.url );
  35331. images[ image.uuid ] = new Source( deserializedImage );
  35332. }
  35333. }
  35334. }
  35335. return images;
  35336. }
  35337. async parseImagesAsync( json ) {
  35338. const scope = this;
  35339. const images = {};
  35340. let loader;
  35341. async function deserializeImage( image ) {
  35342. if ( typeof image === 'string' ) {
  35343. const url = image;
  35344. const path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( url ) ? url : scope.resourcePath + url;
  35345. return await loader.loadAsync( path );
  35346. } else {
  35347. if ( image.data ) {
  35348. return {
  35349. data: getTypedArray( image.type, image.data ),
  35350. width: image.width,
  35351. height: image.height
  35352. };
  35353. } else {
  35354. return null;
  35355. }
  35356. }
  35357. }
  35358. if ( json !== undefined && json.length > 0 ) {
  35359. loader = new ImageLoader( this.manager );
  35360. loader.setCrossOrigin( this.crossOrigin );
  35361. for ( let i = 0, il = json.length; i < il; i ++ ) {
  35362. const image = json[ i ];
  35363. const url = image.url;
  35364. if ( Array.isArray( url ) ) {
  35365. // load array of images e.g CubeTexture
  35366. const imageArray = [];
  35367. for ( let j = 0, jl = url.length; j < jl; j ++ ) {
  35368. const currentUrl = url[ j ];
  35369. const deserializedImage = await deserializeImage( currentUrl );
  35370. if ( deserializedImage !== null ) {
  35371. if ( deserializedImage instanceof HTMLImageElement ) {
  35372. imageArray.push( deserializedImage );
  35373. } else {
  35374. // special case: handle array of data textures for cube textures
  35375. imageArray.push( new DataTexture( deserializedImage.data, deserializedImage.width, deserializedImage.height ) );
  35376. }
  35377. }
  35378. }
  35379. images[ image.uuid ] = new Source( imageArray );
  35380. } else {
  35381. // load single image
  35382. const deserializedImage = await deserializeImage( image.url );
  35383. images[ image.uuid ] = new Source( deserializedImage );
  35384. }
  35385. }
  35386. }
  35387. return images;
  35388. }
  35389. parseTextures( json, images ) {
  35390. function parseConstant( value, type ) {
  35391. if ( typeof value === 'number' ) return value;
  35392. warn( 'ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  35393. return type[ value ];
  35394. }
  35395. const textures = {};
  35396. if ( json !== undefined ) {
  35397. for ( let i = 0, l = json.length; i < l; i ++ ) {
  35398. const data = json[ i ];
  35399. if ( data.image === undefined ) {
  35400. warn( 'ObjectLoader: No "image" specified for', data.uuid );
  35401. }
  35402. if ( images[ data.image ] === undefined ) {
  35403. warn( 'ObjectLoader: Undefined image', data.image );
  35404. }
  35405. const source = images[ data.image ];
  35406. const image = source.data;
  35407. let texture;
  35408. if ( Array.isArray( image ) ) {
  35409. texture = new CubeTexture();
  35410. if ( image.length === 6 ) texture.needsUpdate = true;
  35411. } else {
  35412. if ( image && image.data ) {
  35413. texture = new DataTexture();
  35414. } else {
  35415. texture = new Texture();
  35416. }
  35417. if ( image ) texture.needsUpdate = true; // textures can have undefined image data
  35418. }
  35419. texture.source = source;
  35420. texture.uuid = data.uuid;
  35421. if ( data.name !== undefined ) texture.name = data.name;
  35422. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  35423. if ( data.channel !== undefined ) texture.channel = data.channel;
  35424. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  35425. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  35426. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  35427. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  35428. if ( data.wrap !== undefined ) {
  35429. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  35430. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  35431. }
  35432. if ( data.format !== undefined ) texture.format = data.format;
  35433. if ( data.internalFormat !== undefined ) texture.internalFormat = data.internalFormat;
  35434. if ( data.type !== undefined ) texture.type = data.type;
  35435. if ( data.colorSpace !== undefined ) texture.colorSpace = data.colorSpace;
  35436. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  35437. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  35438. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  35439. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  35440. if ( data.generateMipmaps !== undefined ) texture.generateMipmaps = data.generateMipmaps;
  35441. if ( data.premultiplyAlpha !== undefined ) texture.premultiplyAlpha = data.premultiplyAlpha;
  35442. if ( data.unpackAlignment !== undefined ) texture.unpackAlignment = data.unpackAlignment;
  35443. if ( data.compareFunction !== undefined ) texture.compareFunction = data.compareFunction;
  35444. if ( data.userData !== undefined ) texture.userData = data.userData;
  35445. textures[ data.uuid ] = texture;
  35446. }
  35447. }
  35448. return textures;
  35449. }
  35450. parseObject( data, geometries, materials, textures, animations ) {
  35451. let object;
  35452. function getGeometry( name ) {
  35453. if ( geometries[ name ] === undefined ) {
  35454. warn( 'ObjectLoader: Undefined geometry', name );
  35455. }
  35456. return geometries[ name ];
  35457. }
  35458. function getMaterial( name ) {
  35459. if ( name === undefined ) return undefined;
  35460. if ( Array.isArray( name ) ) {
  35461. const array = [];
  35462. for ( let i = 0, l = name.length; i < l; i ++ ) {
  35463. const uuid = name[ i ];
  35464. if ( materials[ uuid ] === undefined ) {
  35465. warn( 'ObjectLoader: Undefined material', uuid );
  35466. }
  35467. array.push( materials[ uuid ] );
  35468. }
  35469. return array;
  35470. }
  35471. if ( materials[ name ] === undefined ) {
  35472. warn( 'ObjectLoader: Undefined material', name );
  35473. }
  35474. return materials[ name ];
  35475. }
  35476. function getTexture( uuid ) {
  35477. if ( textures[ uuid ] === undefined ) {
  35478. warn( 'ObjectLoader: Undefined texture', uuid );
  35479. }
  35480. return textures[ uuid ];
  35481. }
  35482. let geometry, material;
  35483. switch ( data.type ) {
  35484. case 'Scene':
  35485. object = new Scene();
  35486. if ( data.background !== undefined ) {
  35487. if ( Number.isInteger( data.background ) ) {
  35488. object.background = new Color( data.background );
  35489. } else {
  35490. object.background = getTexture( data.background );
  35491. }
  35492. }
  35493. if ( data.environment !== undefined ) {
  35494. object.environment = getTexture( data.environment );
  35495. }
  35496. if ( data.fog !== undefined ) {
  35497. if ( data.fog.type === 'Fog' ) {
  35498. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  35499. } else if ( data.fog.type === 'FogExp2' ) {
  35500. object.fog = new FogExp2( data.fog.color, data.fog.density );
  35501. }
  35502. if ( data.fog.name !== '' ) {
  35503. object.fog.name = data.fog.name;
  35504. }
  35505. }
  35506. if ( data.backgroundBlurriness !== undefined ) object.backgroundBlurriness = data.backgroundBlurriness;
  35507. if ( data.backgroundIntensity !== undefined ) object.backgroundIntensity = data.backgroundIntensity;
  35508. if ( data.backgroundRotation !== undefined ) object.backgroundRotation.fromArray( data.backgroundRotation );
  35509. if ( data.environmentIntensity !== undefined ) object.environmentIntensity = data.environmentIntensity;
  35510. if ( data.environmentRotation !== undefined ) object.environmentRotation.fromArray( data.environmentRotation );
  35511. break;
  35512. case 'PerspectiveCamera':
  35513. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  35514. if ( data.focus !== undefined ) object.focus = data.focus;
  35515. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35516. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  35517. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  35518. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35519. break;
  35520. case 'OrthographicCamera':
  35521. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  35522. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  35523. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  35524. break;
  35525. case 'AmbientLight':
  35526. object = new AmbientLight( data.color, data.intensity );
  35527. break;
  35528. case 'DirectionalLight':
  35529. object = new DirectionalLight( data.color, data.intensity );
  35530. object.target = data.target || '';
  35531. break;
  35532. case 'PointLight':
  35533. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  35534. break;
  35535. case 'RectAreaLight':
  35536. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  35537. break;
  35538. case 'SpotLight':
  35539. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  35540. object.target = data.target || '';
  35541. break;
  35542. case 'HemisphereLight':
  35543. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  35544. break;
  35545. case 'LightProbe':
  35546. object = new LightProbe().fromJSON( data );
  35547. break;
  35548. case 'SkinnedMesh':
  35549. geometry = getGeometry( data.geometry );
  35550. material = getMaterial( data.material );
  35551. object = new SkinnedMesh( geometry, material );
  35552. if ( data.bindMode !== undefined ) object.bindMode = data.bindMode;
  35553. if ( data.bindMatrix !== undefined ) object.bindMatrix.fromArray( data.bindMatrix );
  35554. if ( data.skeleton !== undefined ) object.skeleton = data.skeleton;
  35555. break;
  35556. case 'Mesh':
  35557. geometry = getGeometry( data.geometry );
  35558. material = getMaterial( data.material );
  35559. object = new Mesh( geometry, material );
  35560. break;
  35561. case 'InstancedMesh':
  35562. geometry = getGeometry( data.geometry );
  35563. material = getMaterial( data.material );
  35564. const count = data.count;
  35565. const instanceMatrix = data.instanceMatrix;
  35566. const instanceColor = data.instanceColor;
  35567. object = new InstancedMesh( geometry, material, count );
  35568. object.instanceMatrix = new InstancedBufferAttribute( new Float32Array( instanceMatrix.array ), 16 );
  35569. if ( instanceColor !== undefined ) object.instanceColor = new InstancedBufferAttribute( new Float32Array( instanceColor.array ), instanceColor.itemSize );
  35570. break;
  35571. case 'BatchedMesh':
  35572. geometry = getGeometry( data.geometry );
  35573. material = getMaterial( data.material );
  35574. object = new BatchedMesh( data.maxInstanceCount, data.maxVertexCount, data.maxIndexCount, material );
  35575. object.geometry = geometry;
  35576. object.perObjectFrustumCulled = data.perObjectFrustumCulled;
  35577. object.sortObjects = data.sortObjects;
  35578. object._drawRanges = data.drawRanges;
  35579. object._reservedRanges = data.reservedRanges;
  35580. object._geometryInfo = data.geometryInfo.map( info => {
  35581. let box = null;
  35582. let sphere = null;
  35583. if ( info.boundingBox !== undefined ) {
  35584. box = new Box3().fromJSON( info.boundingBox );
  35585. }
  35586. if ( info.boundingSphere !== undefined ) {
  35587. sphere = new Sphere().fromJSON( info.boundingSphere );
  35588. }
  35589. return {
  35590. ...info,
  35591. boundingBox: box,
  35592. boundingSphere: sphere
  35593. };
  35594. } );
  35595. object._instanceInfo = data.instanceInfo;
  35596. object._availableInstanceIds = data._availableInstanceIds;
  35597. object._availableGeometryIds = data._availableGeometryIds;
  35598. object._nextIndexStart = data.nextIndexStart;
  35599. object._nextVertexStart = data.nextVertexStart;
  35600. object._geometryCount = data.geometryCount;
  35601. object._maxInstanceCount = data.maxInstanceCount;
  35602. object._maxVertexCount = data.maxVertexCount;
  35603. object._maxIndexCount = data.maxIndexCount;
  35604. object._geometryInitialized = data.geometryInitialized;
  35605. object._matricesTexture = getTexture( data.matricesTexture.uuid );
  35606. object._indirectTexture = getTexture( data.indirectTexture.uuid );
  35607. if ( data.colorsTexture !== undefined ) {
  35608. object._colorsTexture = getTexture( data.colorsTexture.uuid );
  35609. }
  35610. if ( data.boundingSphere !== undefined ) {
  35611. object.boundingSphere = new Sphere().fromJSON( data.boundingSphere );
  35612. }
  35613. if ( data.boundingBox !== undefined ) {
  35614. object.boundingBox = new Box3().fromJSON( data.boundingBox );
  35615. }
  35616. break;
  35617. case 'LOD':
  35618. object = new LOD();
  35619. break;
  35620. case 'Line':
  35621. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ) );
  35622. break;
  35623. case 'LineLoop':
  35624. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  35625. break;
  35626. case 'LineSegments':
  35627. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  35628. break;
  35629. case 'PointCloud':
  35630. case 'Points':
  35631. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  35632. break;
  35633. case 'Sprite':
  35634. object = new Sprite( getMaterial( data.material ) );
  35635. break;
  35636. case 'Group':
  35637. object = new Group();
  35638. break;
  35639. case 'Bone':
  35640. object = new Bone();
  35641. break;
  35642. default:
  35643. object = new Object3D();
  35644. }
  35645. object.uuid = data.uuid;
  35646. if ( data.name !== undefined ) object.name = data.name;
  35647. if ( data.matrix !== undefined ) {
  35648. object.matrix.fromArray( data.matrix );
  35649. if ( data.matrixAutoUpdate !== undefined ) object.matrixAutoUpdate = data.matrixAutoUpdate;
  35650. if ( object.matrixAutoUpdate ) object.matrix.decompose( object.position, object.quaternion, object.scale );
  35651. } else {
  35652. if ( data.position !== undefined ) object.position.fromArray( data.position );
  35653. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  35654. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  35655. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  35656. }
  35657. if ( data.up !== undefined ) object.up.fromArray( data.up );
  35658. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  35659. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  35660. if ( data.shadow ) {
  35661. if ( data.shadow.intensity !== undefined ) object.shadow.intensity = data.shadow.intensity;
  35662. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  35663. if ( data.shadow.normalBias !== undefined ) object.shadow.normalBias = data.shadow.normalBias;
  35664. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  35665. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  35666. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  35667. }
  35668. if ( data.visible !== undefined ) object.visible = data.visible;
  35669. if ( data.frustumCulled !== undefined ) object.frustumCulled = data.frustumCulled;
  35670. if ( data.renderOrder !== undefined ) object.renderOrder = data.renderOrder;
  35671. if ( data.userData !== undefined ) object.userData = data.userData;
  35672. if ( data.layers !== undefined ) object.layers.mask = data.layers;
  35673. if ( data.children !== undefined ) {
  35674. const children = data.children;
  35675. for ( let i = 0; i < children.length; i ++ ) {
  35676. object.add( this.parseObject( children[ i ], geometries, materials, textures, animations ) );
  35677. }
  35678. }
  35679. if ( data.animations !== undefined ) {
  35680. const objectAnimations = data.animations;
  35681. for ( let i = 0; i < objectAnimations.length; i ++ ) {
  35682. const uuid = objectAnimations[ i ];
  35683. object.animations.push( animations[ uuid ] );
  35684. }
  35685. }
  35686. if ( data.type === 'LOD' ) {
  35687. if ( data.autoUpdate !== undefined ) object.autoUpdate = data.autoUpdate;
  35688. const levels = data.levels;
  35689. for ( let l = 0; l < levels.length; l ++ ) {
  35690. const level = levels[ l ];
  35691. const child = object.getObjectByProperty( 'uuid', level.object );
  35692. if ( child !== undefined ) {
  35693. object.addLevel( child, level.distance, level.hysteresis );
  35694. }
  35695. }
  35696. }
  35697. return object;
  35698. }
  35699. bindSkeletons( object, skeletons ) {
  35700. if ( Object.keys( skeletons ).length === 0 ) return;
  35701. object.traverse( function ( child ) {
  35702. if ( child.isSkinnedMesh === true && child.skeleton !== undefined ) {
  35703. const skeleton = skeletons[ child.skeleton ];
  35704. if ( skeleton === undefined ) {
  35705. warn( 'ObjectLoader: No skeleton found with UUID:', child.skeleton );
  35706. } else {
  35707. child.bind( skeleton, child.bindMatrix );
  35708. }
  35709. }
  35710. } );
  35711. }
  35712. bindLightTargets( object ) {
  35713. object.traverse( function ( child ) {
  35714. if ( child.isDirectionalLight || child.isSpotLight ) {
  35715. const uuid = child.target;
  35716. const target = object.getObjectByProperty( 'uuid', uuid );
  35717. if ( target !== undefined ) {
  35718. child.target = target;
  35719. } else {
  35720. child.target = new Object3D();
  35721. }
  35722. }
  35723. } );
  35724. }
  35725. }
  35726. const TEXTURE_MAPPING = {
  35727. UVMapping: UVMapping,
  35728. CubeReflectionMapping: CubeReflectionMapping,
  35729. CubeRefractionMapping: CubeRefractionMapping,
  35730. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  35731. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  35732. CubeUVReflectionMapping: CubeUVReflectionMapping
  35733. };
  35734. const TEXTURE_WRAPPING = {
  35735. RepeatWrapping: RepeatWrapping,
  35736. ClampToEdgeWrapping: ClampToEdgeWrapping,
  35737. MirroredRepeatWrapping: MirroredRepeatWrapping
  35738. };
  35739. const TEXTURE_FILTER = {
  35740. NearestFilter: NearestFilter,
  35741. NearestMipmapNearestFilter: NearestMipmapNearestFilter,
  35742. NearestMipmapLinearFilter: NearestMipmapLinearFilter,
  35743. LinearFilter: LinearFilter,
  35744. LinearMipmapNearestFilter: LinearMipmapNearestFilter,
  35745. LinearMipmapLinearFilter: LinearMipmapLinearFilter
  35746. };
  35747. const _errorMap = new WeakMap();
  35748. /**
  35749. * A loader for loading images as an [ImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap).
  35750. * An `ImageBitmap` provides an asynchronous and resource efficient pathway to prepare
  35751. * textures for rendering.
  35752. *
  35753. * Note that {@link Texture#flipY} and {@link Texture#premultiplyAlpha} are ignored with image bitmaps.
  35754. * They needs these configuration on bitmap creation unlike regular images need them on uploading to GPU.
  35755. *
  35756. * You need to set the equivalent options via {@link ImageBitmapLoader#setOptions} instead.
  35757. *
  35758. * Also note that unlike {@link FileLoader}, this loader avoids multiple concurrent requests to the same URL only if `Cache` is enabled.
  35759. *
  35760. * ```js
  35761. * const loader = new THREE.ImageBitmapLoader();
  35762. * loader.setOptions( { imageOrientation: 'flipY' } ); // set options if needed
  35763. * const imageBitmap = await loader.loadAsync( 'image.png' );
  35764. *
  35765. * const texture = new THREE.Texture( imageBitmap );
  35766. * texture.needsUpdate = true;
  35767. * ```
  35768. *
  35769. * @augments Loader
  35770. */
  35771. class ImageBitmapLoader extends Loader {
  35772. /**
  35773. * Constructs a new image bitmap loader.
  35774. *
  35775. * @param {LoadingManager} [manager] - The loading manager.
  35776. */
  35777. constructor( manager ) {
  35778. super( manager );
  35779. /**
  35780. * This flag can be used for type testing.
  35781. *
  35782. * @type {boolean}
  35783. * @readonly
  35784. * @default true
  35785. */
  35786. this.isImageBitmapLoader = true;
  35787. if ( typeof createImageBitmap === 'undefined' ) {
  35788. warn( 'ImageBitmapLoader: createImageBitmap() not supported.' );
  35789. }
  35790. if ( typeof fetch === 'undefined' ) {
  35791. warn( 'ImageBitmapLoader: fetch() not supported.' );
  35792. }
  35793. /**
  35794. * Represents the loader options.
  35795. *
  35796. * @type {Object}
  35797. * @default {premultiplyAlpha:'none'}
  35798. */
  35799. this.options = { premultiplyAlpha: 'none' };
  35800. /**
  35801. * Used for aborting requests.
  35802. *
  35803. * @private
  35804. * @type {AbortController}
  35805. */
  35806. this._abortController = new AbortController();
  35807. }
  35808. /**
  35809. * Sets the given loader options. The structure of the object must match the `options` parameter of
  35810. * [createImageBitmap](https://developer.mozilla.org/en-US/docs/Web/API/Window/createImageBitmap).
  35811. *
  35812. * @param {Object} options - The loader options to set.
  35813. * @return {ImageBitmapLoader} A reference to this image bitmap loader.
  35814. */
  35815. setOptions( options ) {
  35816. this.options = options;
  35817. return this;
  35818. }
  35819. /**
  35820. * Starts loading from the given URL and pass the loaded image bitmap to the `onLoad()` callback.
  35821. *
  35822. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35823. * @param {function(ImageBitmap)} onLoad - Executed when the loading process has been finished.
  35824. * @param {onProgressCallback} onProgress - Unsupported in this loader.
  35825. * @param {onErrorCallback} onError - Executed when errors occur.
  35826. * @return {ImageBitmap|undefined} The image bitmap.
  35827. */
  35828. load( url, onLoad, onProgress, onError ) {
  35829. if ( url === undefined ) url = '';
  35830. if ( this.path !== undefined ) url = this.path + url;
  35831. url = this.manager.resolveURL( url );
  35832. const scope = this;
  35833. const cached = Cache.get( `image-bitmap:${url}` );
  35834. if ( cached !== undefined ) {
  35835. scope.manager.itemStart( url );
  35836. // If cached is a promise, wait for it to resolve
  35837. if ( cached.then ) {
  35838. cached.then( imageBitmap => {
  35839. // check if there is an error for the cached promise
  35840. if ( _errorMap.has( cached ) === true ) {
  35841. if ( onError ) onError( _errorMap.get( cached ) );
  35842. scope.manager.itemError( url );
  35843. scope.manager.itemEnd( url );
  35844. } else {
  35845. if ( onLoad ) onLoad( imageBitmap );
  35846. scope.manager.itemEnd( url );
  35847. return imageBitmap;
  35848. }
  35849. } );
  35850. return;
  35851. }
  35852. // If cached is not a promise (i.e., it's already an imageBitmap)
  35853. setTimeout( function () {
  35854. if ( onLoad ) onLoad( cached );
  35855. scope.manager.itemEnd( url );
  35856. }, 0 );
  35857. return cached;
  35858. }
  35859. const fetchOptions = {};
  35860. fetchOptions.credentials = ( this.crossOrigin === 'anonymous' ) ? 'same-origin' : 'include';
  35861. fetchOptions.headers = this.requestHeader;
  35862. fetchOptions.signal = ( typeof AbortSignal.any === 'function' ) ? AbortSignal.any( [ this._abortController.signal, this.manager.abortController.signal ] ) : this._abortController.signal;
  35863. const promise = fetch( url, fetchOptions ).then( function ( res ) {
  35864. return res.blob();
  35865. } ).then( function ( blob ) {
  35866. return createImageBitmap( blob, Object.assign( scope.options, { colorSpaceConversion: 'none' } ) );
  35867. } ).then( function ( imageBitmap ) {
  35868. Cache.add( `image-bitmap:${url}`, imageBitmap );
  35869. if ( onLoad ) onLoad( imageBitmap );
  35870. scope.manager.itemEnd( url );
  35871. return imageBitmap;
  35872. } ).catch( function ( e ) {
  35873. if ( onError ) onError( e );
  35874. _errorMap.set( promise, e );
  35875. Cache.remove( `image-bitmap:${url}` );
  35876. scope.manager.itemError( url );
  35877. scope.manager.itemEnd( url );
  35878. } );
  35879. Cache.add( `image-bitmap:${url}`, promise );
  35880. scope.manager.itemStart( url );
  35881. }
  35882. /**
  35883. * Aborts ongoing fetch requests.
  35884. *
  35885. * @return {ImageBitmapLoader} A reference to this instance.
  35886. */
  35887. abort() {
  35888. this._abortController.abort();
  35889. this._abortController = new AbortController();
  35890. return this;
  35891. }
  35892. }
  35893. let _context;
  35894. /**
  35895. * Manages the global audio context in the engine.
  35896. *
  35897. * @hideconstructor
  35898. */
  35899. class AudioContext {
  35900. /**
  35901. * Returns the global native audio context.
  35902. *
  35903. * @return {AudioContext} The native audio context.
  35904. */
  35905. static getContext() {
  35906. if ( _context === undefined ) {
  35907. _context = new ( window.AudioContext || window.webkitAudioContext )();
  35908. }
  35909. return _context;
  35910. }
  35911. /**
  35912. * Allows to set the global native audio context from outside.
  35913. *
  35914. * @param {AudioContext} value - The native context to set.
  35915. */
  35916. static setContext( value ) {
  35917. _context = value;
  35918. }
  35919. }
  35920. /**
  35921. * Class for loading audio buffers. Audios are internally
  35922. * loaded via {@link FileLoader}.
  35923. *
  35924. * ```js
  35925. * const audioListener = new THREE.AudioListener();
  35926. * const ambientSound = new THREE.Audio( audioListener );
  35927. *
  35928. * const loader = new THREE.AudioLoader();
  35929. * const audioBuffer = await loader.loadAsync( 'audio/ambient_ocean.ogg' );
  35930. *
  35931. * ambientSound.setBuffer( audioBuffer );
  35932. * ambientSound.play();
  35933. * ```
  35934. *
  35935. * @augments Loader
  35936. */
  35937. class AudioLoader extends Loader {
  35938. /**
  35939. * Constructs a new audio loader.
  35940. *
  35941. * @param {LoadingManager} [manager] - The loading manager.
  35942. */
  35943. constructor( manager ) {
  35944. super( manager );
  35945. }
  35946. /**
  35947. * Starts loading from the given URL and passes the loaded audio buffer
  35948. * to the `onLoad()` callback.
  35949. *
  35950. * @param {string} url - The path/URL of the file to be loaded. This can also be a data URI.
  35951. * @param {function(AudioBuffer)} onLoad - Executed when the loading process has been finished.
  35952. * @param {onProgressCallback} onProgress - Executed while the loading is in progress.
  35953. * @param {onErrorCallback} onError - Executed when errors occur.
  35954. */
  35955. load( url, onLoad, onProgress, onError ) {
  35956. const scope = this;
  35957. const loader = new FileLoader( this.manager );
  35958. loader.setResponseType( 'arraybuffer' );
  35959. loader.setPath( this.path );
  35960. loader.setRequestHeader( this.requestHeader );
  35961. loader.setWithCredentials( this.withCredentials );
  35962. loader.load( url, function ( buffer ) {
  35963. try {
  35964. // Create a copy of the buffer. The `decodeAudioData` method
  35965. // detaches the buffer when complete, preventing reuse.
  35966. const bufferCopy = buffer.slice( 0 );
  35967. const context = AudioContext.getContext();
  35968. context.decodeAudioData( bufferCopy, function ( audioBuffer ) {
  35969. onLoad( audioBuffer );
  35970. } ).catch( handleError );
  35971. } catch ( e ) {
  35972. handleError( e );
  35973. }
  35974. }, onProgress, onError );
  35975. function handleError( e ) {
  35976. if ( onError ) {
  35977. onError( e );
  35978. } else {
  35979. error( e );
  35980. }
  35981. scope.manager.itemError( url );
  35982. }
  35983. }
  35984. }
  35985. const _eyeRight = /*@__PURE__*/ new Matrix4();
  35986. const _eyeLeft = /*@__PURE__*/ new Matrix4();
  35987. const _projectionMatrix = /*@__PURE__*/ new Matrix4();
  35988. /**
  35989. * A special type of camera that uses two perspective cameras with
  35990. * stereoscopic projection. Can be used for rendering stereo effects
  35991. * like [3D Anaglyph](https://en.wikipedia.org/wiki/Anaglyph_3D) or
  35992. * [Parallax Barrier](https://en.wikipedia.org/wiki/parallax_barrier).
  35993. */
  35994. class StereoCamera {
  35995. /**
  35996. * Constructs a new stereo camera.
  35997. */
  35998. constructor() {
  35999. /**
  36000. * The type property is used for detecting the object type
  36001. * in context of serialization/deserialization.
  36002. *
  36003. * @type {string}
  36004. * @readonly
  36005. */
  36006. this.type = 'StereoCamera';
  36007. /**
  36008. * The aspect.
  36009. *
  36010. * @type {number}
  36011. * @default 1
  36012. */
  36013. this.aspect = 1;
  36014. /**
  36015. * The eye separation which represents the distance
  36016. * between the left and right camera.
  36017. *
  36018. * @type {number}
  36019. * @default 0.064
  36020. */
  36021. this.eyeSep = 0.064;
  36022. /**
  36023. * The camera representing the left eye. This is added to layer `1` so objects to be
  36024. * rendered by the left camera must also be added to this layer.
  36025. *
  36026. * @type {PerspectiveCamera}
  36027. */
  36028. this.cameraL = new PerspectiveCamera();
  36029. this.cameraL.layers.enable( 1 );
  36030. this.cameraL.matrixAutoUpdate = false;
  36031. /**
  36032. * The camera representing the right eye. This is added to layer `2` so objects to be
  36033. * rendered by the right camera must also be added to this layer.
  36034. *
  36035. * @type {PerspectiveCamera}
  36036. */
  36037. this.cameraR = new PerspectiveCamera();
  36038. this.cameraR.layers.enable( 2 );
  36039. this.cameraR.matrixAutoUpdate = false;
  36040. this._cache = {
  36041. focus: null,
  36042. fov: null,
  36043. aspect: null,
  36044. near: null,
  36045. far: null,
  36046. zoom: null,
  36047. eyeSep: null
  36048. };
  36049. }
  36050. /**
  36051. * Updates the stereo camera based on the given perspective camera.
  36052. *
  36053. * @param {PerspectiveCamera} camera - The perspective camera.
  36054. */
  36055. update( camera ) {
  36056. const cache = this._cache;
  36057. const needsUpdate = cache.focus !== camera.focus || cache.fov !== camera.fov ||
  36058. cache.aspect !== camera.aspect * this.aspect || cache.near !== camera.near ||
  36059. cache.far !== camera.far || cache.zoom !== camera.zoom || cache.eyeSep !== this.eyeSep;
  36060. if ( needsUpdate ) {
  36061. cache.focus = camera.focus;
  36062. cache.fov = camera.fov;
  36063. cache.aspect = camera.aspect * this.aspect;
  36064. cache.near = camera.near;
  36065. cache.far = camera.far;
  36066. cache.zoom = camera.zoom;
  36067. cache.eyeSep = this.eyeSep;
  36068. // Off-axis stereoscopic effect based on
  36069. // http://paulbourke.net/stereographics/stereorender/
  36070. _projectionMatrix.copy( camera.projectionMatrix );
  36071. const eyeSepHalf = cache.eyeSep / 2;
  36072. const eyeSepOnProjection = eyeSepHalf * cache.near / cache.focus;
  36073. const ymax = ( cache.near * Math.tan( DEG2RAD * cache.fov * 0.5 ) ) / cache.zoom;
  36074. let xmin, xmax;
  36075. // translate xOffset
  36076. _eyeLeft.elements[ 12 ] = - eyeSepHalf;
  36077. _eyeRight.elements[ 12 ] = eyeSepHalf;
  36078. // for left eye
  36079. xmin = - ymax * cache.aspect + eyeSepOnProjection;
  36080. xmax = ymax * cache.aspect + eyeSepOnProjection;
  36081. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36082. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36083. this.cameraL.projectionMatrix.copy( _projectionMatrix );
  36084. // for right eye
  36085. xmin = - ymax * cache.aspect - eyeSepOnProjection;
  36086. xmax = ymax * cache.aspect - eyeSepOnProjection;
  36087. _projectionMatrix.elements[ 0 ] = 2 * cache.near / ( xmax - xmin );
  36088. _projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  36089. this.cameraR.projectionMatrix.copy( _projectionMatrix );
  36090. }
  36091. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeLeft );
  36092. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( _eyeRight );
  36093. }
  36094. }
  36095. /**
  36096. * This type of camera can be used in order to efficiently render a scene with a
  36097. * predefined set of cameras. This is an important performance aspect for
  36098. * rendering VR scenes.
  36099. *
  36100. * An instance of `ArrayCamera` always has an array of sub cameras. It's mandatory
  36101. * to define for each sub camera the `viewport` property which determines the
  36102. * part of the viewport that is rendered with this camera.
  36103. *
  36104. * @augments PerspectiveCamera
  36105. */
  36106. class ArrayCamera extends PerspectiveCamera {
  36107. /**
  36108. * Constructs a new array camera.
  36109. *
  36110. * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras.
  36111. */
  36112. constructor( array = [] ) {
  36113. super();
  36114. /**
  36115. * This flag can be used for type testing.
  36116. *
  36117. * @type {boolean}
  36118. * @readonly
  36119. * @default true
  36120. */
  36121. this.isArrayCamera = true;
  36122. /**
  36123. * Whether this camera is used with multiview rendering or not.
  36124. *
  36125. * @type {boolean}
  36126. * @readonly
  36127. * @default false
  36128. */
  36129. this.isMultiViewCamera = false;
  36130. /**
  36131. * An array of perspective sub cameras.
  36132. *
  36133. * @type {Array<PerspectiveCamera>}
  36134. */
  36135. this.cameras = array;
  36136. }
  36137. }
  36138. /**
  36139. * Class for keeping track of time.
  36140. */
  36141. class Clock {
  36142. /**
  36143. * Constructs a new clock.
  36144. *
  36145. * @param {boolean} [autoStart=true] - Whether to automatically start the clock when
  36146. * `getDelta()` is called for the first time.
  36147. */
  36148. constructor( autoStart = true ) {
  36149. /**
  36150. * If set to `true`, the clock starts automatically when `getDelta()` is called
  36151. * for the first time.
  36152. *
  36153. * @type {boolean}
  36154. * @default true
  36155. */
  36156. this.autoStart = autoStart;
  36157. /**
  36158. * Holds the time at which the clock's `start()` method was last called.
  36159. *
  36160. * @type {number}
  36161. * @default 0
  36162. */
  36163. this.startTime = 0;
  36164. /**
  36165. * Holds the time at which the clock's `start()`, `getElapsedTime()` or
  36166. * `getDelta()` methods were last called.
  36167. *
  36168. * @type {number}
  36169. * @default 0
  36170. */
  36171. this.oldTime = 0;
  36172. /**
  36173. * Keeps track of the total time that the clock has been running.
  36174. *
  36175. * @type {number}
  36176. * @default 0
  36177. */
  36178. this.elapsedTime = 0;
  36179. /**
  36180. * Whether the clock is running or not.
  36181. *
  36182. * @type {boolean}
  36183. * @default true
  36184. */
  36185. this.running = false;
  36186. }
  36187. /**
  36188. * Starts the clock. When `autoStart` is set to `true`, the method is automatically
  36189. * called by the class.
  36190. */
  36191. start() {
  36192. this.startTime = performance.now();
  36193. this.oldTime = this.startTime;
  36194. this.elapsedTime = 0;
  36195. this.running = true;
  36196. }
  36197. /**
  36198. * Stops the clock.
  36199. */
  36200. stop() {
  36201. this.getElapsedTime();
  36202. this.running = false;
  36203. this.autoStart = false;
  36204. }
  36205. /**
  36206. * Returns the elapsed time in seconds.
  36207. *
  36208. * @return {number} The elapsed time.
  36209. */
  36210. getElapsedTime() {
  36211. this.getDelta();
  36212. return this.elapsedTime;
  36213. }
  36214. /**
  36215. * Returns the delta time in seconds.
  36216. *
  36217. * @return {number} The delta time.
  36218. */
  36219. getDelta() {
  36220. let diff = 0;
  36221. if ( this.autoStart && ! this.running ) {
  36222. this.start();
  36223. return 0;
  36224. }
  36225. if ( this.running ) {
  36226. const newTime = performance.now();
  36227. diff = ( newTime - this.oldTime ) / 1000;
  36228. this.oldTime = newTime;
  36229. this.elapsedTime += diff;
  36230. }
  36231. return diff;
  36232. }
  36233. }
  36234. const _position$1 = /*@__PURE__*/ new Vector3();
  36235. const _quaternion$1 = /*@__PURE__*/ new Quaternion();
  36236. const _scale$1 = /*@__PURE__*/ new Vector3();
  36237. const _forward = /*@__PURE__*/ new Vector3();
  36238. const _up = /*@__PURE__*/ new Vector3();
  36239. /**
  36240. * The class represents a virtual listener of the all positional and non-positional audio effects
  36241. * in the scene. A three.js application usually creates a single listener. It is a mandatory
  36242. * constructor parameter for audios entities like {@link Audio} and {@link PositionalAudio}.
  36243. *
  36244. * In most cases, the listener object is a child of the camera. So the 3D transformation of the
  36245. * camera represents the 3D transformation of the listener.
  36246. *
  36247. * @augments Object3D
  36248. */
  36249. class AudioListener extends Object3D {
  36250. /**
  36251. * Constructs a new audio listener.
  36252. */
  36253. constructor() {
  36254. super();
  36255. this.type = 'AudioListener';
  36256. /**
  36257. * The native audio context.
  36258. *
  36259. * @type {AudioContext}
  36260. * @readonly
  36261. */
  36262. this.context = AudioContext.getContext();
  36263. /**
  36264. * The gain node used for volume control.
  36265. *
  36266. * @type {GainNode}
  36267. * @readonly
  36268. */
  36269. this.gain = this.context.createGain();
  36270. this.gain.connect( this.context.destination );
  36271. /**
  36272. * An optional filter.
  36273. *
  36274. * Defined via {@link AudioListener#setFilter}.
  36275. *
  36276. * @type {?AudioNode}
  36277. * @default null
  36278. * @readonly
  36279. */
  36280. this.filter = null;
  36281. /**
  36282. * Time delta values required for `linearRampToValueAtTime()` usage.
  36283. *
  36284. * @type {number}
  36285. * @default 0
  36286. * @readonly
  36287. */
  36288. this.timeDelta = 0;
  36289. // private
  36290. this._clock = new Clock();
  36291. }
  36292. /**
  36293. * Returns the listener's input node.
  36294. *
  36295. * This method is used by other audio nodes to connect to this listener.
  36296. *
  36297. * @return {GainNode} The input node.
  36298. */
  36299. getInput() {
  36300. return this.gain;
  36301. }
  36302. /**
  36303. * Removes the current filter from this listener.
  36304. *
  36305. * @return {AudioListener} A reference to this listener.
  36306. */
  36307. removeFilter() {
  36308. if ( this.filter !== null ) {
  36309. this.gain.disconnect( this.filter );
  36310. this.filter.disconnect( this.context.destination );
  36311. this.gain.connect( this.context.destination );
  36312. this.filter = null;
  36313. }
  36314. return this;
  36315. }
  36316. /**
  36317. * Returns the current set filter.
  36318. *
  36319. * @return {?AudioNode} The filter.
  36320. */
  36321. getFilter() {
  36322. return this.filter;
  36323. }
  36324. /**
  36325. * Sets the given filter to this listener.
  36326. *
  36327. * @param {AudioNode} value - The filter to set.
  36328. * @return {AudioListener} A reference to this listener.
  36329. */
  36330. setFilter( value ) {
  36331. if ( this.filter !== null ) {
  36332. this.gain.disconnect( this.filter );
  36333. this.filter.disconnect( this.context.destination );
  36334. } else {
  36335. this.gain.disconnect( this.context.destination );
  36336. }
  36337. this.filter = value;
  36338. this.gain.connect( this.filter );
  36339. this.filter.connect( this.context.destination );
  36340. return this;
  36341. }
  36342. /**
  36343. * Returns the applications master volume.
  36344. *
  36345. * @return {number} The master volume.
  36346. */
  36347. getMasterVolume() {
  36348. return this.gain.gain.value;
  36349. }
  36350. /**
  36351. * Sets the applications master volume. This volume setting affects
  36352. * all audio nodes in the scene.
  36353. *
  36354. * @param {number} value - The master volume to set.
  36355. * @return {AudioListener} A reference to this listener.
  36356. */
  36357. setMasterVolume( value ) {
  36358. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36359. return this;
  36360. }
  36361. updateMatrixWorld( force ) {
  36362. super.updateMatrixWorld( force );
  36363. const listener = this.context.listener;
  36364. this.timeDelta = this._clock.getDelta();
  36365. this.matrixWorld.decompose( _position$1, _quaternion$1, _scale$1 );
  36366. // the initial forward and up directions must be orthogonal
  36367. _forward.set( 0, 0, -1 ).applyQuaternion( _quaternion$1 );
  36368. _up.set( 0, 1, 0 ).applyQuaternion( _quaternion$1 );
  36369. if ( listener.positionX ) {
  36370. // code path for Chrome (see #14393)
  36371. const endTime = this.context.currentTime + this.timeDelta;
  36372. listener.positionX.linearRampToValueAtTime( _position$1.x, endTime );
  36373. listener.positionY.linearRampToValueAtTime( _position$1.y, endTime );
  36374. listener.positionZ.linearRampToValueAtTime( _position$1.z, endTime );
  36375. listener.forwardX.linearRampToValueAtTime( _forward.x, endTime );
  36376. listener.forwardY.linearRampToValueAtTime( _forward.y, endTime );
  36377. listener.forwardZ.linearRampToValueAtTime( _forward.z, endTime );
  36378. listener.upX.linearRampToValueAtTime( _up.x, endTime );
  36379. listener.upY.linearRampToValueAtTime( _up.y, endTime );
  36380. listener.upZ.linearRampToValueAtTime( _up.z, endTime );
  36381. } else {
  36382. listener.setPosition( _position$1.x, _position$1.y, _position$1.z );
  36383. listener.setOrientation( _forward.x, _forward.y, _forward.z, _up.x, _up.y, _up.z );
  36384. }
  36385. }
  36386. }
  36387. /**
  36388. * Represents a non-positional ( global ) audio object.
  36389. *
  36390. * This and related audio modules make use of the [Web Audio API](https://www.w3.org/TR/webaudio-1.1/).
  36391. *
  36392. * ```js
  36393. * // create an AudioListener and add it to the camera
  36394. * const listener = new THREE.AudioListener();
  36395. * camera.add( listener );
  36396. *
  36397. * // create a global audio source
  36398. * const sound = new THREE.Audio( listener );
  36399. *
  36400. * // load a sound and set it as the Audio object's buffer
  36401. * const audioLoader = new THREE.AudioLoader();
  36402. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  36403. * sound.setBuffer( buffer );
  36404. * sound.setLoop( true );
  36405. * sound.setVolume( 0.5 );
  36406. * sound.play();
  36407. * });
  36408. * ```
  36409. *
  36410. * @augments Object3D
  36411. */
  36412. class Audio extends Object3D {
  36413. /**
  36414. * Constructs a new audio.
  36415. *
  36416. * @param {AudioListener} listener - The global audio listener.
  36417. */
  36418. constructor( listener ) {
  36419. super();
  36420. this.type = 'Audio';
  36421. /**
  36422. * The global audio listener.
  36423. *
  36424. * @type {AudioListener}
  36425. * @readonly
  36426. */
  36427. this.listener = listener;
  36428. /**
  36429. * The audio context.
  36430. *
  36431. * @type {AudioContext}
  36432. * @readonly
  36433. */
  36434. this.context = listener.context;
  36435. /**
  36436. * The gain node used for volume control.
  36437. *
  36438. * @type {GainNode}
  36439. * @readonly
  36440. */
  36441. this.gain = this.context.createGain();
  36442. this.gain.connect( listener.getInput() );
  36443. /**
  36444. * Whether to start playback automatically or not.
  36445. *
  36446. * @type {boolean}
  36447. * @default false
  36448. */
  36449. this.autoplay = false;
  36450. /**
  36451. * A reference to an audio buffer.
  36452. *
  36453. * Defined via {@link Audio#setBuffer}.
  36454. *
  36455. * @type {?AudioBuffer}
  36456. * @default null
  36457. * @readonly
  36458. */
  36459. this.buffer = null;
  36460. /**
  36461. * Modify pitch, measured in cents. +/- 100 is a semitone.
  36462. * +/- 1200 is an octave.
  36463. *
  36464. * Defined via {@link Audio#setDetune}.
  36465. *
  36466. * @type {number}
  36467. * @default 0
  36468. * @readonly
  36469. */
  36470. this.detune = 0;
  36471. /**
  36472. * Whether the audio should loop or not.
  36473. *
  36474. * Defined via {@link Audio#setLoop}.
  36475. *
  36476. * @type {boolean}
  36477. * @default false
  36478. * @readonly
  36479. */
  36480. this.loop = false;
  36481. /**
  36482. * Defines where in the audio buffer the replay should
  36483. * start, in seconds.
  36484. *
  36485. * @type {number}
  36486. * @default 0
  36487. */
  36488. this.loopStart = 0;
  36489. /**
  36490. * Defines where in the audio buffer the replay should
  36491. * stop, in seconds.
  36492. *
  36493. * @type {number}
  36494. * @default 0
  36495. */
  36496. this.loopEnd = 0;
  36497. /**
  36498. * An offset to the time within the audio buffer the playback
  36499. * should begin, in seconds.
  36500. *
  36501. * @type {number}
  36502. * @default 0
  36503. */
  36504. this.offset = 0;
  36505. /**
  36506. * Overrides the default duration of the audio.
  36507. *
  36508. * @type {undefined|number}
  36509. * @default undefined
  36510. */
  36511. this.duration = undefined;
  36512. /**
  36513. * The playback speed.
  36514. *
  36515. * Defined via {@link Audio#setPlaybackRate}.
  36516. *
  36517. * @type {number}
  36518. * @readonly
  36519. * @default 1
  36520. */
  36521. this.playbackRate = 1;
  36522. /**
  36523. * Indicates whether the audio is playing or not.
  36524. *
  36525. * This flag will be automatically set when using {@link Audio#play},
  36526. * {@link Audio#pause}, {@link Audio#stop}.
  36527. *
  36528. * @type {boolean}
  36529. * @readonly
  36530. * @default false
  36531. */
  36532. this.isPlaying = false;
  36533. /**
  36534. * Indicates whether the audio playback can be controlled
  36535. * with method like {@link Audio#play} or {@link Audio#pause}.
  36536. *
  36537. * This flag will be automatically set when audio sources are
  36538. * defined.
  36539. *
  36540. * @type {boolean}
  36541. * @readonly
  36542. * @default true
  36543. */
  36544. this.hasPlaybackControl = true;
  36545. /**
  36546. * Holds a reference to the current audio source.
  36547. *
  36548. * The property is automatically by one of the `set*()` methods.
  36549. *
  36550. * @type {?AudioNode}
  36551. * @readonly
  36552. * @default null
  36553. */
  36554. this.source = null;
  36555. /**
  36556. * Defines the source type.
  36557. *
  36558. * The property is automatically by one of the `set*()` methods.
  36559. *
  36560. * @type {('empty'|'audioNode'|'mediaNode'|'mediaStreamNode'|'buffer')}
  36561. * @readonly
  36562. * @default 'empty'
  36563. */
  36564. this.sourceType = 'empty';
  36565. this._startedAt = 0;
  36566. this._progress = 0;
  36567. this._connected = false;
  36568. /**
  36569. * Can be used to apply a variety of low-order filters to create
  36570. * more complex sound effects e.g. via `BiquadFilterNode`.
  36571. *
  36572. * The property is automatically set by {@link Audio#setFilters}.
  36573. *
  36574. * @type {Array<AudioNode>}
  36575. * @readonly
  36576. */
  36577. this.filters = [];
  36578. }
  36579. /**
  36580. * Returns the output audio node.
  36581. *
  36582. * @return {GainNode} The output node.
  36583. */
  36584. getOutput() {
  36585. return this.gain;
  36586. }
  36587. /**
  36588. * Sets the given audio node as the source of this instance.
  36589. *
  36590. * {@link Audio#sourceType} is set to `audioNode` and {@link Audio#hasPlaybackControl} to `false`.
  36591. *
  36592. * @param {AudioNode} audioNode - The audio node like an instance of `OscillatorNode`.
  36593. * @return {Audio} A reference to this instance.
  36594. */
  36595. setNodeSource( audioNode ) {
  36596. this.hasPlaybackControl = false;
  36597. this.sourceType = 'audioNode';
  36598. this.source = audioNode;
  36599. this.connect();
  36600. return this;
  36601. }
  36602. /**
  36603. * Sets the given media element as the source of this instance.
  36604. *
  36605. * {@link Audio#sourceType} is set to `mediaNode` and {@link Audio#hasPlaybackControl} to `false`.
  36606. *
  36607. * @param {HTMLMediaElement} mediaElement - The media element.
  36608. * @return {Audio} A reference to this instance.
  36609. */
  36610. setMediaElementSource( mediaElement ) {
  36611. this.hasPlaybackControl = false;
  36612. this.sourceType = 'mediaNode';
  36613. this.source = this.context.createMediaElementSource( mediaElement );
  36614. this.connect();
  36615. return this;
  36616. }
  36617. /**
  36618. * Sets the given media stream as the source of this instance.
  36619. *
  36620. * {@link Audio#sourceType} is set to `mediaStreamNode` and {@link Audio#hasPlaybackControl} to `false`.
  36621. *
  36622. * @param {MediaStream} mediaStream - The media stream.
  36623. * @return {Audio} A reference to this instance.
  36624. */
  36625. setMediaStreamSource( mediaStream ) {
  36626. this.hasPlaybackControl = false;
  36627. this.sourceType = 'mediaStreamNode';
  36628. this.source = this.context.createMediaStreamSource( mediaStream );
  36629. this.connect();
  36630. return this;
  36631. }
  36632. /**
  36633. * Sets the given audio buffer as the source of this instance.
  36634. *
  36635. * {@link Audio#sourceType} is set to `buffer` and {@link Audio#hasPlaybackControl} to `true`.
  36636. *
  36637. * @param {AudioBuffer} audioBuffer - The audio buffer.
  36638. * @return {Audio} A reference to this instance.
  36639. */
  36640. setBuffer( audioBuffer ) {
  36641. this.buffer = audioBuffer;
  36642. this.sourceType = 'buffer';
  36643. if ( this.autoplay ) this.play();
  36644. return this;
  36645. }
  36646. /**
  36647. * Starts the playback of the audio.
  36648. *
  36649. * Can only be used with compatible audio sources that allow playback control.
  36650. *
  36651. * @param {number} [delay=0] - The delay, in seconds, at which the audio should start playing.
  36652. * @return {Audio|undefined} A reference to this instance.
  36653. */
  36654. play( delay = 0 ) {
  36655. if ( this.isPlaying === true ) {
  36656. warn( 'Audio: Audio is already playing.' );
  36657. return;
  36658. }
  36659. if ( this.hasPlaybackControl === false ) {
  36660. warn( 'Audio: this Audio has no playback control.' );
  36661. return;
  36662. }
  36663. this._startedAt = this.context.currentTime + delay;
  36664. const source = this.context.createBufferSource();
  36665. source.buffer = this.buffer;
  36666. source.loop = this.loop;
  36667. source.loopStart = this.loopStart;
  36668. source.loopEnd = this.loopEnd;
  36669. source.onended = this.onEnded.bind( this );
  36670. source.start( this._startedAt, this._progress + this.offset, this.duration );
  36671. this.isPlaying = true;
  36672. this.source = source;
  36673. this.setDetune( this.detune );
  36674. this.setPlaybackRate( this.playbackRate );
  36675. return this.connect();
  36676. }
  36677. /**
  36678. * Pauses the playback of the audio.
  36679. *
  36680. * Can only be used with compatible audio sources that allow playback control.
  36681. *
  36682. * @return {Audio|undefined} A reference to this instance.
  36683. */
  36684. pause() {
  36685. if ( this.hasPlaybackControl === false ) {
  36686. warn( 'Audio: this Audio has no playback control.' );
  36687. return;
  36688. }
  36689. if ( this.isPlaying === true ) {
  36690. // update current progress
  36691. this._progress += Math.max( this.context.currentTime - this._startedAt, 0 ) * this.playbackRate;
  36692. if ( this.loop === true ) {
  36693. // ensure _progress does not exceed duration with looped audios
  36694. this._progress = this._progress % ( this.duration || this.buffer.duration );
  36695. }
  36696. this.source.stop();
  36697. this.source.onended = null;
  36698. this.isPlaying = false;
  36699. }
  36700. return this;
  36701. }
  36702. /**
  36703. * Stops the playback of the audio.
  36704. *
  36705. * Can only be used with compatible audio sources that allow playback control.
  36706. *
  36707. * @param {number} [delay=0] - The delay, in seconds, at which the audio should stop playing.
  36708. * @return {Audio|undefined} A reference to this instance.
  36709. */
  36710. stop( delay = 0 ) {
  36711. if ( this.hasPlaybackControl === false ) {
  36712. warn( 'Audio: this Audio has no playback control.' );
  36713. return;
  36714. }
  36715. this._progress = 0;
  36716. if ( this.source !== null ) {
  36717. this.source.stop( this.context.currentTime + delay );
  36718. this.source.onended = null;
  36719. }
  36720. this.isPlaying = false;
  36721. return this;
  36722. }
  36723. /**
  36724. * Connects to the audio source. This is used internally on
  36725. * initialisation and when setting / removing filters.
  36726. *
  36727. * @return {Audio} A reference to this instance.
  36728. */
  36729. connect() {
  36730. if ( this.filters.length > 0 ) {
  36731. this.source.connect( this.filters[ 0 ] );
  36732. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36733. this.filters[ i - 1 ].connect( this.filters[ i ] );
  36734. }
  36735. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  36736. } else {
  36737. this.source.connect( this.getOutput() );
  36738. }
  36739. this._connected = true;
  36740. return this;
  36741. }
  36742. /**
  36743. * Disconnects to the audio source. This is used internally on
  36744. * initialisation and when setting / removing filters.
  36745. *
  36746. * @return {Audio|undefined} A reference to this instance.
  36747. */
  36748. disconnect() {
  36749. if ( this._connected === false ) {
  36750. return;
  36751. }
  36752. if ( this.filters.length > 0 ) {
  36753. this.source.disconnect( this.filters[ 0 ] );
  36754. for ( let i = 1, l = this.filters.length; i < l; i ++ ) {
  36755. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  36756. }
  36757. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  36758. } else {
  36759. this.source.disconnect( this.getOutput() );
  36760. }
  36761. this._connected = false;
  36762. return this;
  36763. }
  36764. /**
  36765. * Returns the current set filters.
  36766. *
  36767. * @return {Array<AudioNode>} The list of filters.
  36768. */
  36769. getFilters() {
  36770. return this.filters;
  36771. }
  36772. /**
  36773. * Sets an array of filters and connects them with the audio source.
  36774. *
  36775. * @param {Array<AudioNode>} [value] - A list of filters.
  36776. * @return {Audio} A reference to this instance.
  36777. */
  36778. setFilters( value ) {
  36779. if ( ! value ) value = [];
  36780. if ( this._connected === true ) {
  36781. this.disconnect();
  36782. this.filters = value.slice();
  36783. this.connect();
  36784. } else {
  36785. this.filters = value.slice();
  36786. }
  36787. return this;
  36788. }
  36789. /**
  36790. * Defines the detuning of oscillation in cents.
  36791. *
  36792. * @param {number} value - The detuning of oscillation in cents.
  36793. * @return {Audio} A reference to this instance.
  36794. */
  36795. setDetune( value ) {
  36796. this.detune = value;
  36797. if ( this.isPlaying === true && this.source.detune !== undefined ) {
  36798. this.source.detune.setTargetAtTime( this.detune, this.context.currentTime, 0.01 );
  36799. }
  36800. return this;
  36801. }
  36802. /**
  36803. * Returns the detuning of oscillation in cents.
  36804. *
  36805. * @return {number} The detuning of oscillation in cents.
  36806. */
  36807. getDetune() {
  36808. return this.detune;
  36809. }
  36810. /**
  36811. * Returns the first filter in the list of filters.
  36812. *
  36813. * @return {AudioNode|undefined} The first filter in the list of filters.
  36814. */
  36815. getFilter() {
  36816. return this.getFilters()[ 0 ];
  36817. }
  36818. /**
  36819. * Applies a single filter node to the audio.
  36820. *
  36821. * @param {AudioNode} [filter] - The filter to set.
  36822. * @return {Audio} A reference to this instance.
  36823. */
  36824. setFilter( filter ) {
  36825. return this.setFilters( filter ? [ filter ] : [] );
  36826. }
  36827. /**
  36828. * Sets the playback rate.
  36829. *
  36830. * Can only be used with compatible audio sources that allow playback control.
  36831. *
  36832. * @param {number} [value] - The playback rate to set.
  36833. * @return {Audio|undefined} A reference to this instance.
  36834. */
  36835. setPlaybackRate( value ) {
  36836. if ( this.hasPlaybackControl === false ) {
  36837. warn( 'Audio: this Audio has no playback control.' );
  36838. return;
  36839. }
  36840. this.playbackRate = value;
  36841. if ( this.isPlaying === true ) {
  36842. this.source.playbackRate.setTargetAtTime( this.playbackRate, this.context.currentTime, 0.01 );
  36843. }
  36844. return this;
  36845. }
  36846. /**
  36847. * Returns the current playback rate.
  36848. * @return {number} The playback rate.
  36849. */
  36850. getPlaybackRate() {
  36851. return this.playbackRate;
  36852. }
  36853. /**
  36854. * Automatically called when playback finished.
  36855. */
  36856. onEnded() {
  36857. this.isPlaying = false;
  36858. this._progress = 0;
  36859. }
  36860. /**
  36861. * Returns the loop flag.
  36862. *
  36863. * Can only be used with compatible audio sources that allow playback control.
  36864. *
  36865. * @return {boolean} Whether the audio should loop or not.
  36866. */
  36867. getLoop() {
  36868. if ( this.hasPlaybackControl === false ) {
  36869. warn( 'Audio: this Audio has no playback control.' );
  36870. return false;
  36871. }
  36872. return this.loop;
  36873. }
  36874. /**
  36875. * Sets the loop flag.
  36876. *
  36877. * Can only be used with compatible audio sources that allow playback control.
  36878. *
  36879. * @param {boolean} value - Whether the audio should loop or not.
  36880. * @return {Audio|undefined} A reference to this instance.
  36881. */
  36882. setLoop( value ) {
  36883. if ( this.hasPlaybackControl === false ) {
  36884. warn( 'Audio: this Audio has no playback control.' );
  36885. return;
  36886. }
  36887. this.loop = value;
  36888. if ( this.isPlaying === true ) {
  36889. this.source.loop = this.loop;
  36890. }
  36891. return this;
  36892. }
  36893. /**
  36894. * Sets the loop start value which defines where in the audio buffer the replay should
  36895. * start, in seconds.
  36896. *
  36897. * @param {number} value - The loop start value.
  36898. * @return {Audio} A reference to this instance.
  36899. */
  36900. setLoopStart( value ) {
  36901. this.loopStart = value;
  36902. return this;
  36903. }
  36904. /**
  36905. * Sets the loop end value which defines where in the audio buffer the replay should
  36906. * stop, in seconds.
  36907. *
  36908. * @param {number} value - The loop end value.
  36909. * @return {Audio} A reference to this instance.
  36910. */
  36911. setLoopEnd( value ) {
  36912. this.loopEnd = value;
  36913. return this;
  36914. }
  36915. /**
  36916. * Returns the volume.
  36917. *
  36918. * @return {number} The volume.
  36919. */
  36920. getVolume() {
  36921. return this.gain.gain.value;
  36922. }
  36923. /**
  36924. * Sets the volume.
  36925. *
  36926. * @param {number} value - The volume to set.
  36927. * @return {Audio} A reference to this instance.
  36928. */
  36929. setVolume( value ) {
  36930. this.gain.gain.setTargetAtTime( value, this.context.currentTime, 0.01 );
  36931. return this;
  36932. }
  36933. copy( source, recursive ) {
  36934. super.copy( source, recursive );
  36935. if ( source.sourceType !== 'buffer' ) {
  36936. warn( 'Audio: Audio source type cannot be copied.' );
  36937. return this;
  36938. }
  36939. this.autoplay = source.autoplay;
  36940. this.buffer = source.buffer;
  36941. this.detune = source.detune;
  36942. this.loop = source.loop;
  36943. this.loopStart = source.loopStart;
  36944. this.loopEnd = source.loopEnd;
  36945. this.offset = source.offset;
  36946. this.duration = source.duration;
  36947. this.playbackRate = source.playbackRate;
  36948. this.hasPlaybackControl = source.hasPlaybackControl;
  36949. this.sourceType = source.sourceType;
  36950. this.filters = source.filters.slice();
  36951. return this;
  36952. }
  36953. clone( recursive ) {
  36954. return new this.constructor( this.listener ).copy( this, recursive );
  36955. }
  36956. }
  36957. const _position = /*@__PURE__*/ new Vector3();
  36958. const _quaternion = /*@__PURE__*/ new Quaternion();
  36959. const _scale = /*@__PURE__*/ new Vector3();
  36960. const _orientation = /*@__PURE__*/ new Vector3();
  36961. /**
  36962. * Represents a positional audio object.
  36963. *
  36964. * ```js
  36965. * // create an AudioListener and add it to the camera
  36966. * const listener = new THREE.AudioListener();
  36967. * camera.add( listener );
  36968. *
  36969. * // create the PositionalAudio object (passing in the listener)
  36970. * const sound = new THREE.PositionalAudio( listener );
  36971. *
  36972. * // load a sound and set it as the PositionalAudio object's buffer
  36973. * const audioLoader = new THREE.AudioLoader();
  36974. * audioLoader.load( 'sounds/song.ogg', function( buffer ) {
  36975. * sound.setBuffer( buffer );
  36976. * sound.setRefDistance( 20 );
  36977. * sound.play();
  36978. * });
  36979. *
  36980. * // create an object for the sound to play from
  36981. * const sphere = new THREE.SphereGeometry( 20, 32, 16 );
  36982. * const material = new THREE.MeshPhongMaterial( { color: 0xff2200 } );
  36983. * const mesh = new THREE.Mesh( sphere, material );
  36984. * scene.add( mesh );
  36985. *
  36986. * // finally add the sound to the mesh
  36987. * mesh.add( sound );
  36988. *
  36989. * @augments Audio
  36990. */
  36991. class PositionalAudio extends Audio {
  36992. /**
  36993. * Constructs a positional audio.
  36994. *
  36995. * @param {AudioListener} listener - The global audio listener.
  36996. */
  36997. constructor( listener ) {
  36998. super( listener );
  36999. /**
  37000. * The panner node represents the location, direction, and behavior of an audio
  37001. * source in 3D space.
  37002. *
  37003. * @type {PannerNode}
  37004. * @readonly
  37005. */
  37006. this.panner = this.context.createPanner();
  37007. this.panner.panningModel = 'HRTF';
  37008. this.panner.connect( this.gain );
  37009. }
  37010. connect() {
  37011. super.connect();
  37012. this.panner.connect( this.gain );
  37013. return this;
  37014. }
  37015. disconnect() {
  37016. super.disconnect();
  37017. this.panner.disconnect( this.gain );
  37018. return this;
  37019. }
  37020. getOutput() {
  37021. return this.panner;
  37022. }
  37023. /**
  37024. * Returns the current reference distance.
  37025. *
  37026. * @return {number} The reference distance.
  37027. */
  37028. getRefDistance() {
  37029. return this.panner.refDistance;
  37030. }
  37031. /**
  37032. * Defines the reference distance for reducing volume as the audio source moves
  37033. * further from the listener – i.e. the distance at which the volume reduction
  37034. * starts taking effect.
  37035. *
  37036. * @param {number} value - The reference distance to set.
  37037. * @return {PositionalAudio} A reference to this instance.
  37038. */
  37039. setRefDistance( value ) {
  37040. this.panner.refDistance = value;
  37041. return this;
  37042. }
  37043. /**
  37044. * Returns the current rolloff factor.
  37045. *
  37046. * @return {number} The rolloff factor.
  37047. */
  37048. getRolloffFactor() {
  37049. return this.panner.rolloffFactor;
  37050. }
  37051. /**
  37052. * Defines how quickly the volume is reduced as the source moves away from the listener.
  37053. *
  37054. * @param {number} value - The rolloff factor.
  37055. * @return {PositionalAudio} A reference to this instance.
  37056. */
  37057. setRolloffFactor( value ) {
  37058. this.panner.rolloffFactor = value;
  37059. return this;
  37060. }
  37061. /**
  37062. * Returns the current distance model.
  37063. *
  37064. * @return {('linear'|'inverse'|'exponential')} The distance model.
  37065. */
  37066. getDistanceModel() {
  37067. return this.panner.distanceModel;
  37068. }
  37069. /**
  37070. * Defines which algorithm to use to reduce the volume of the audio source
  37071. * as it moves away from the listener.
  37072. *
  37073. * Read [the spec](https://www.w3.org/TR/webaudio-1.1/#enumdef-distancemodeltype)
  37074. * for more details.
  37075. *
  37076. * @param {('linear'|'inverse'|'exponential')} value - The distance model to set.
  37077. * @return {PositionalAudio} A reference to this instance.
  37078. */
  37079. setDistanceModel( value ) {
  37080. this.panner.distanceModel = value;
  37081. return this;
  37082. }
  37083. /**
  37084. * Returns the current max distance.
  37085. *
  37086. * @return {number} The max distance.
  37087. */
  37088. getMaxDistance() {
  37089. return this.panner.maxDistance;
  37090. }
  37091. /**
  37092. * Defines the maximum distance between the audio source and the listener,
  37093. * after which the volume is not reduced any further.
  37094. *
  37095. * This value is used only by the `linear` distance model.
  37096. *
  37097. * @param {number} value - The max distance.
  37098. * @return {PositionalAudio} A reference to this instance.
  37099. */
  37100. setMaxDistance( value ) {
  37101. this.panner.maxDistance = value;
  37102. return this;
  37103. }
  37104. /**
  37105. * Sets the directional cone in which the audio can be listened.
  37106. *
  37107. * @param {number} coneInnerAngle - An angle, in degrees, of a cone inside of which there will be no volume reduction.
  37108. * @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.
  37109. * @param {number} coneOuterGain - The amount of volume reduction outside the cone defined by the `coneOuterAngle`. When set to `0`, no sound can be heard.
  37110. * @return {PositionalAudio} A reference to this instance.
  37111. */
  37112. setDirectionalCone( coneInnerAngle, coneOuterAngle, coneOuterGain ) {
  37113. this.panner.coneInnerAngle = coneInnerAngle;
  37114. this.panner.coneOuterAngle = coneOuterAngle;
  37115. this.panner.coneOuterGain = coneOuterGain;
  37116. return this;
  37117. }
  37118. updateMatrixWorld( force ) {
  37119. super.updateMatrixWorld( force );
  37120. if ( this.hasPlaybackControl === true && this.isPlaying === false ) return;
  37121. this.matrixWorld.decompose( _position, _quaternion, _scale );
  37122. _orientation.set( 0, 0, 1 ).applyQuaternion( _quaternion );
  37123. const panner = this.panner;
  37124. if ( panner.positionX ) {
  37125. // code path for Chrome and Firefox (see #14393)
  37126. const endTime = this.context.currentTime + this.listener.timeDelta;
  37127. panner.positionX.linearRampToValueAtTime( _position.x, endTime );
  37128. panner.positionY.linearRampToValueAtTime( _position.y, endTime );
  37129. panner.positionZ.linearRampToValueAtTime( _position.z, endTime );
  37130. panner.orientationX.linearRampToValueAtTime( _orientation.x, endTime );
  37131. panner.orientationY.linearRampToValueAtTime( _orientation.y, endTime );
  37132. panner.orientationZ.linearRampToValueAtTime( _orientation.z, endTime );
  37133. } else {
  37134. panner.setPosition( _position.x, _position.y, _position.z );
  37135. panner.setOrientation( _orientation.x, _orientation.y, _orientation.z );
  37136. }
  37137. }
  37138. }
  37139. /**
  37140. * This class can be used to analyse audio data.
  37141. *
  37142. * ```js
  37143. * // create an AudioListener and add it to the camera
  37144. * const listener = new THREE.AudioListener();
  37145. * camera.add( listener );
  37146. *
  37147. * // create an Audio source
  37148. * const sound = new THREE.Audio( listener );
  37149. *
  37150. * // load a sound and set it as the Audio object's buffer
  37151. * const audioLoader = new THREE.AudioLoader();
  37152. * audioLoader.load( 'sounds/ambient.ogg', function( buffer ) {
  37153. * sound.setBuffer( buffer );
  37154. * sound.setLoop(true);
  37155. * sound.setVolume(0.5);
  37156. * sound.play();
  37157. * });
  37158. *
  37159. * // create an AudioAnalyser, passing in the sound and desired fftSize
  37160. * const analyser = new THREE.AudioAnalyser( sound, 32 );
  37161. *
  37162. * // get the average frequency of the sound
  37163. * const data = analyser.getAverageFrequency();
  37164. * ```
  37165. */
  37166. class AudioAnalyser {
  37167. /**
  37168. * Constructs a new audio analyzer.
  37169. *
  37170. * @param {Audio} audio - The audio to analyze.
  37171. * @param {number} [fftSize=2048] - The window size in samples that is used when performing a Fast Fourier Transform (FFT) to get frequency domain data.
  37172. */
  37173. constructor( audio, fftSize = 2048 ) {
  37174. /**
  37175. * The global audio listener.
  37176. *
  37177. * @type {AnalyserNode}
  37178. */
  37179. this.analyser = audio.context.createAnalyser();
  37180. this.analyser.fftSize = fftSize;
  37181. /**
  37182. * Holds the analyzed data.
  37183. *
  37184. * @type {Uint8Array}
  37185. */
  37186. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  37187. audio.getOutput().connect( this.analyser );
  37188. }
  37189. /**
  37190. * Returns an array with frequency data of the audio.
  37191. *
  37192. * Each item in the array represents the decibel value for a specific frequency.
  37193. * The frequencies are spread linearly from 0 to 1/2 of the sample rate.
  37194. * For example, for 48000 sample rate, the last item of the array will represent
  37195. * the decibel value for 24000 Hz.
  37196. *
  37197. * @return {Uint8Array} The frequency data.
  37198. */
  37199. getFrequencyData() {
  37200. this.analyser.getByteFrequencyData( this.data );
  37201. return this.data;
  37202. }
  37203. /**
  37204. * Returns the average of the frequencies returned by {@link AudioAnalyser#getFrequencyData}.
  37205. *
  37206. * @return {number} The average frequency.
  37207. */
  37208. getAverageFrequency() {
  37209. let value = 0;
  37210. const data = this.getFrequencyData();
  37211. for ( let i = 0; i < data.length; i ++ ) {
  37212. value += data[ i ];
  37213. }
  37214. return value / data.length;
  37215. }
  37216. }
  37217. /**
  37218. * Buffered scene graph property that allows weighted accumulation; used internally.
  37219. */
  37220. class PropertyMixer {
  37221. /**
  37222. * Constructs a new property mixer.
  37223. *
  37224. * @param {PropertyBinding} binding - The property binding.
  37225. * @param {string} typeName - The keyframe track type name.
  37226. * @param {number} valueSize - The keyframe track value size.
  37227. */
  37228. constructor( binding, typeName, valueSize ) {
  37229. /**
  37230. * The property binding.
  37231. *
  37232. * @type {PropertyBinding}
  37233. */
  37234. this.binding = binding;
  37235. /**
  37236. * The keyframe track value size.
  37237. *
  37238. * @type {number}
  37239. */
  37240. this.valueSize = valueSize;
  37241. let mixFunction,
  37242. mixFunctionAdditive,
  37243. setIdentity;
  37244. // buffer layout: [ incoming | accu0 | accu1 | orig | addAccu | (optional work) ]
  37245. //
  37246. // interpolators can use .buffer as their .result
  37247. // the data then goes to 'incoming'
  37248. //
  37249. // 'accu0' and 'accu1' are used frame-interleaved for
  37250. // the cumulative result and are compared to detect
  37251. // changes
  37252. //
  37253. // 'orig' stores the original state of the property
  37254. //
  37255. // 'add' is used for additive cumulative results
  37256. //
  37257. // 'work' is optional and is only present for quaternion types. It is used
  37258. // to store intermediate quaternion multiplication results
  37259. switch ( typeName ) {
  37260. case 'quaternion':
  37261. mixFunction = this._slerp;
  37262. mixFunctionAdditive = this._slerpAdditive;
  37263. setIdentity = this._setAdditiveIdentityQuaternion;
  37264. this.buffer = new Float64Array( valueSize * 6 );
  37265. this._workIndex = 5;
  37266. break;
  37267. case 'string':
  37268. case 'bool':
  37269. mixFunction = this._select;
  37270. // Use the regular mix function and for additive on these types,
  37271. // additive is not relevant for non-numeric types
  37272. mixFunctionAdditive = this._select;
  37273. setIdentity = this._setAdditiveIdentityOther;
  37274. this.buffer = new Array( valueSize * 5 );
  37275. break;
  37276. default:
  37277. mixFunction = this._lerp;
  37278. mixFunctionAdditive = this._lerpAdditive;
  37279. setIdentity = this._setAdditiveIdentityNumeric;
  37280. this.buffer = new Float64Array( valueSize * 5 );
  37281. }
  37282. this._mixBufferRegion = mixFunction;
  37283. this._mixBufferRegionAdditive = mixFunctionAdditive;
  37284. this._setIdentity = setIdentity;
  37285. this._origIndex = 3;
  37286. this._addIndex = 4;
  37287. /**
  37288. * TODO
  37289. *
  37290. * @type {number}
  37291. * @default 0
  37292. */
  37293. this.cumulativeWeight = 0;
  37294. /**
  37295. * TODO
  37296. *
  37297. * @type {number}
  37298. * @default 0
  37299. */
  37300. this.cumulativeWeightAdditive = 0;
  37301. /**
  37302. * TODO
  37303. *
  37304. * @type {number}
  37305. * @default 0
  37306. */
  37307. this.useCount = 0;
  37308. /**
  37309. * TODO
  37310. *
  37311. * @type {number}
  37312. * @default 0
  37313. */
  37314. this.referenceCount = 0;
  37315. }
  37316. /**
  37317. * Accumulates data in the `incoming` region into `accu<i>`.
  37318. *
  37319. * @param {number} accuIndex - The accumulation index.
  37320. * @param {number} weight - The weight.
  37321. */
  37322. accumulate( accuIndex, weight ) {
  37323. // note: happily accumulating nothing when weight = 0, the caller knows
  37324. // the weight and shouldn't have made the call in the first place
  37325. const buffer = this.buffer,
  37326. stride = this.valueSize,
  37327. offset = accuIndex * stride + stride;
  37328. let currentWeight = this.cumulativeWeight;
  37329. if ( currentWeight === 0 ) {
  37330. // accuN := incoming * weight
  37331. for ( let i = 0; i !== stride; ++ i ) {
  37332. buffer[ offset + i ] = buffer[ i ];
  37333. }
  37334. currentWeight = weight;
  37335. } else {
  37336. // accuN := accuN + incoming * weight
  37337. currentWeight += weight;
  37338. const mix = weight / currentWeight;
  37339. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  37340. }
  37341. this.cumulativeWeight = currentWeight;
  37342. }
  37343. /**
  37344. * Accumulates data in the `incoming` region into `add`.
  37345. *
  37346. * @param {number} weight - The weight.
  37347. */
  37348. accumulateAdditive( weight ) {
  37349. const buffer = this.buffer,
  37350. stride = this.valueSize,
  37351. offset = stride * this._addIndex;
  37352. if ( this.cumulativeWeightAdditive === 0 ) {
  37353. // add = identity
  37354. this._setIdentity();
  37355. }
  37356. // add := add + incoming * weight
  37357. this._mixBufferRegionAdditive( buffer, offset, 0, weight, stride );
  37358. this.cumulativeWeightAdditive += weight;
  37359. }
  37360. /**
  37361. * Applies the state of `accu<i>` to the binding when accus differ.
  37362. *
  37363. * @param {number} accuIndex - The accumulation index.
  37364. */
  37365. apply( accuIndex ) {
  37366. const stride = this.valueSize,
  37367. buffer = this.buffer,
  37368. offset = accuIndex * stride + stride,
  37369. weight = this.cumulativeWeight,
  37370. weightAdditive = this.cumulativeWeightAdditive,
  37371. binding = this.binding;
  37372. this.cumulativeWeight = 0;
  37373. this.cumulativeWeightAdditive = 0;
  37374. if ( weight < 1 ) {
  37375. // accuN := accuN + original * ( 1 - cumulativeWeight )
  37376. const originalValueOffset = stride * this._origIndex;
  37377. this._mixBufferRegion(
  37378. buffer, offset, originalValueOffset, 1 - weight, stride );
  37379. }
  37380. if ( weightAdditive > 0 ) {
  37381. // accuN := accuN + additive accuN
  37382. this._mixBufferRegionAdditive( buffer, offset, this._addIndex * stride, 1, stride );
  37383. }
  37384. for ( let i = stride, e = stride + stride; i !== e; ++ i ) {
  37385. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  37386. // value has changed -> update scene graph
  37387. binding.setValue( buffer, offset );
  37388. break;
  37389. }
  37390. }
  37391. }
  37392. /**
  37393. * Remembers the state of the bound property and copy it to both accus.
  37394. */
  37395. saveOriginalState() {
  37396. const binding = this.binding;
  37397. const buffer = this.buffer,
  37398. stride = this.valueSize,
  37399. originalValueOffset = stride * this._origIndex;
  37400. binding.getValue( buffer, originalValueOffset );
  37401. // accu[0..1] := orig -- initially detect changes against the original
  37402. for ( let i = stride, e = originalValueOffset; i !== e; ++ i ) {
  37403. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  37404. }
  37405. // Add to identity for additive
  37406. this._setIdentity();
  37407. this.cumulativeWeight = 0;
  37408. this.cumulativeWeightAdditive = 0;
  37409. }
  37410. /**
  37411. * Applies the state previously taken via {@link PropertyMixer#saveOriginalState} to the binding.
  37412. */
  37413. restoreOriginalState() {
  37414. const originalValueOffset = this.valueSize * 3;
  37415. this.binding.setValue( this.buffer, originalValueOffset );
  37416. }
  37417. // internals
  37418. _setAdditiveIdentityNumeric() {
  37419. const startIndex = this._addIndex * this.valueSize;
  37420. const endIndex = startIndex + this.valueSize;
  37421. for ( let i = startIndex; i < endIndex; i ++ ) {
  37422. this.buffer[ i ] = 0;
  37423. }
  37424. }
  37425. _setAdditiveIdentityQuaternion() {
  37426. this._setAdditiveIdentityNumeric();
  37427. this.buffer[ this._addIndex * this.valueSize + 3 ] = 1;
  37428. }
  37429. _setAdditiveIdentityOther() {
  37430. const startIndex = this._origIndex * this.valueSize;
  37431. const targetIndex = this._addIndex * this.valueSize;
  37432. for ( let i = 0; i < this.valueSize; i ++ ) {
  37433. this.buffer[ targetIndex + i ] = this.buffer[ startIndex + i ];
  37434. }
  37435. }
  37436. // mix functions
  37437. _select( buffer, dstOffset, srcOffset, t, stride ) {
  37438. if ( t >= 0.5 ) {
  37439. for ( let i = 0; i !== stride; ++ i ) {
  37440. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  37441. }
  37442. }
  37443. }
  37444. _slerp( buffer, dstOffset, srcOffset, t ) {
  37445. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  37446. }
  37447. _slerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37448. const workOffset = this._workIndex * stride;
  37449. // Store result in intermediate buffer offset
  37450. Quaternion.multiplyQuaternionsFlat( buffer, workOffset, buffer, dstOffset, buffer, srcOffset );
  37451. // Slerp to the intermediate result
  37452. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, workOffset, t );
  37453. }
  37454. _lerp( buffer, dstOffset, srcOffset, t, stride ) {
  37455. const s = 1 - t;
  37456. for ( let i = 0; i !== stride; ++ i ) {
  37457. const j = dstOffset + i;
  37458. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  37459. }
  37460. }
  37461. _lerpAdditive( buffer, dstOffset, srcOffset, t, stride ) {
  37462. for ( let i = 0; i !== stride; ++ i ) {
  37463. const j = dstOffset + i;
  37464. buffer[ j ] = buffer[ j ] + buffer[ srcOffset + i ] * t;
  37465. }
  37466. }
  37467. }
  37468. // Characters [].:/ are reserved for track binding syntax.
  37469. const _RESERVED_CHARS_RE = '\\[\\]\\.:\\/';
  37470. const _reservedRe = new RegExp( '[' + _RESERVED_CHARS_RE + ']', 'g' );
  37471. // Attempts to allow node names from any language. ES5's `\w` regexp matches
  37472. // only latin characters, and the unicode \p{L} is not yet supported. So
  37473. // instead, we exclude reserved characters and match everything else.
  37474. const _wordChar = '[^' + _RESERVED_CHARS_RE + ']';
  37475. const _wordCharOrDot = '[^' + _RESERVED_CHARS_RE.replace( '\\.', '' ) + ']';
  37476. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  37477. // be matched to parse the rest of the track name.
  37478. const _directoryRe = /*@__PURE__*/ /((?:WC+[\/:])*)/.source.replace( 'WC', _wordChar );
  37479. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  37480. const _nodeRe = /*@__PURE__*/ /(WCOD+)?/.source.replace( 'WCOD', _wordCharOrDot );
  37481. // Object on target node, and accessor. May not contain reserved
  37482. // characters. Accessor may contain any character except closing bracket.
  37483. const _objectRe = /*@__PURE__*/ /(?:\.(WC+)(?:\[(.+)\])?)?/.source.replace( 'WC', _wordChar );
  37484. // Property and accessor. May not contain reserved characters. Accessor may
  37485. // contain any non-bracket characters.
  37486. const _propertyRe = /*@__PURE__*/ /\.(WC+)(?:\[(.+)\])?/.source.replace( 'WC', _wordChar );
  37487. const _trackRe = new RegExp( ''
  37488. + '^'
  37489. + _directoryRe
  37490. + _nodeRe
  37491. + _objectRe
  37492. + _propertyRe
  37493. + '$'
  37494. );
  37495. const _supportedObjectNames = [ 'material', 'materials', 'bones', 'map' ];
  37496. class Composite {
  37497. constructor( targetGroup, path, optionalParsedPath ) {
  37498. const parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  37499. this._targetGroup = targetGroup;
  37500. this._bindings = targetGroup.subscribe_( path, parsedPath );
  37501. }
  37502. getValue( array, offset ) {
  37503. this.bind(); // bind all binding
  37504. const firstValidIndex = this._targetGroup.nCachedObjects_,
  37505. binding = this._bindings[ firstValidIndex ];
  37506. // and only call .getValue on the first
  37507. if ( binding !== undefined ) binding.getValue( array, offset );
  37508. }
  37509. setValue( array, offset ) {
  37510. const bindings = this._bindings;
  37511. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37512. bindings[ i ].setValue( array, offset );
  37513. }
  37514. }
  37515. bind() {
  37516. const bindings = this._bindings;
  37517. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37518. bindings[ i ].bind();
  37519. }
  37520. }
  37521. unbind() {
  37522. const bindings = this._bindings;
  37523. for ( let i = this._targetGroup.nCachedObjects_, n = bindings.length; i !== n; ++ i ) {
  37524. bindings[ i ].unbind();
  37525. }
  37526. }
  37527. }
  37528. // Note: This class uses a State pattern on a per-method basis:
  37529. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  37530. // prototype version of these methods with one that represents
  37531. // the bound state. When the property is not found, the methods
  37532. // become no-ops.
  37533. /**
  37534. * This holds a reference to a real property in the scene graph; used internally.
  37535. */
  37536. class PropertyBinding {
  37537. /**
  37538. * Constructs a new property binding.
  37539. *
  37540. * @param {Object} rootNode - The root node.
  37541. * @param {string} path - The path.
  37542. * @param {?Object} [parsedPath] - The parsed path.
  37543. */
  37544. constructor( rootNode, path, parsedPath ) {
  37545. /**
  37546. * The object path to the animated property.
  37547. *
  37548. * @type {string}
  37549. */
  37550. this.path = path;
  37551. /**
  37552. * An object holding information about the path.
  37553. *
  37554. * @type {Object}
  37555. */
  37556. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  37557. /**
  37558. * The object owns the animated property.
  37559. *
  37560. * @type {?Object}
  37561. */
  37562. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName );
  37563. /**
  37564. * The root node.
  37565. *
  37566. * @type {Object3D|Skeleton}
  37567. */
  37568. this.rootNode = rootNode;
  37569. // initial state of these methods that calls 'bind'
  37570. this.getValue = this._getValue_unbound;
  37571. this.setValue = this._setValue_unbound;
  37572. }
  37573. /**
  37574. * Factory method for creating a property binding from the given parameters.
  37575. *
  37576. * @static
  37577. * @param {Object} root - The root node.
  37578. * @param {string} path - The path.
  37579. * @param {?Object} [parsedPath] - The parsed path.
  37580. * @return {PropertyBinding|Composite} The created property binding or composite.
  37581. */
  37582. static create( root, path, parsedPath ) {
  37583. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  37584. return new PropertyBinding( root, path, parsedPath );
  37585. } else {
  37586. return new PropertyBinding.Composite( root, path, parsedPath );
  37587. }
  37588. }
  37589. /**
  37590. * Replaces spaces with underscores and removes unsupported characters from
  37591. * node names, to ensure compatibility with parseTrackName().
  37592. *
  37593. * @param {string} name - Node name to be sanitized.
  37594. * @return {string} The sanitized node name.
  37595. */
  37596. static sanitizeNodeName( name ) {
  37597. return name.replace( /\s/g, '_' ).replace( _reservedRe, '' );
  37598. }
  37599. /**
  37600. * Parses the given track name (an object path to an animated property) and
  37601. * returns an object with information about the path. Matches strings in the following forms:
  37602. *
  37603. * - nodeName.property
  37604. * - nodeName.property[accessor]
  37605. * - nodeName.material.property[accessor]
  37606. * - uuid.property[accessor]
  37607. * - uuid.objectName[objectIndex].propertyName[propertyIndex]
  37608. * - parentName/nodeName.property
  37609. * - parentName/parentName/nodeName.property[index]
  37610. * - .bone[Armature.DEF_cog].position
  37611. * - scene:helium_balloon_model:helium_balloon_model.position
  37612. *
  37613. * @static
  37614. * @param {string} trackName - The track name to parse.
  37615. * @return {Object} The parsed track name as an object.
  37616. */
  37617. static parseTrackName( trackName ) {
  37618. const matches = _trackRe.exec( trackName );
  37619. if ( matches === null ) {
  37620. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  37621. }
  37622. const results = {
  37623. // directoryName: matches[ 1 ], // (tschw) currently unused
  37624. nodeName: matches[ 2 ],
  37625. objectName: matches[ 3 ],
  37626. objectIndex: matches[ 4 ],
  37627. propertyName: matches[ 5 ], // required
  37628. propertyIndex: matches[ 6 ]
  37629. };
  37630. const lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  37631. if ( lastDot !== undefined && lastDot !== -1 ) {
  37632. const objectName = results.nodeName.substring( lastDot + 1 );
  37633. // Object names must be checked against an allowlist. Otherwise, there
  37634. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  37635. // 'bar' could be the objectName, or part of a nodeName (which can
  37636. // include '.' characters).
  37637. if ( _supportedObjectNames.indexOf( objectName ) !== -1 ) {
  37638. results.nodeName = results.nodeName.substring( 0, lastDot );
  37639. results.objectName = objectName;
  37640. }
  37641. }
  37642. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  37643. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  37644. }
  37645. return results;
  37646. }
  37647. /**
  37648. * Searches for a node in the hierarchy of the given root object by the given
  37649. * node name.
  37650. *
  37651. * @static
  37652. * @param {Object} root - The root object.
  37653. * @param {string|number} nodeName - The name of the node.
  37654. * @return {?Object} The found node. Returns `null` if no object was found.
  37655. */
  37656. static findNode( root, nodeName ) {
  37657. if ( nodeName === undefined || nodeName === '' || nodeName === '.' || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  37658. return root;
  37659. }
  37660. // search into skeleton bones.
  37661. if ( root.skeleton ) {
  37662. const bone = root.skeleton.getBoneByName( nodeName );
  37663. if ( bone !== undefined ) {
  37664. return bone;
  37665. }
  37666. }
  37667. // search into node subtree.
  37668. if ( root.children ) {
  37669. const searchNodeSubtree = function ( children ) {
  37670. for ( let i = 0; i < children.length; i ++ ) {
  37671. const childNode = children[ i ];
  37672. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  37673. return childNode;
  37674. }
  37675. const result = searchNodeSubtree( childNode.children );
  37676. if ( result ) return result;
  37677. }
  37678. return null;
  37679. };
  37680. const subTreeNode = searchNodeSubtree( root.children );
  37681. if ( subTreeNode ) {
  37682. return subTreeNode;
  37683. }
  37684. }
  37685. return null;
  37686. }
  37687. // these are used to "bind" a nonexistent property
  37688. _getValue_unavailable() {}
  37689. _setValue_unavailable() {}
  37690. // Getters
  37691. _getValue_direct( buffer, offset ) {
  37692. buffer[ offset ] = this.targetObject[ this.propertyName ];
  37693. }
  37694. _getValue_array( buffer, offset ) {
  37695. const source = this.resolvedProperty;
  37696. for ( let i = 0, n = source.length; i !== n; ++ i ) {
  37697. buffer[ offset ++ ] = source[ i ];
  37698. }
  37699. }
  37700. _getValue_arrayElement( buffer, offset ) {
  37701. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  37702. }
  37703. _getValue_toArray( buffer, offset ) {
  37704. this.resolvedProperty.toArray( buffer, offset );
  37705. }
  37706. // Direct
  37707. _setValue_direct( buffer, offset ) {
  37708. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37709. }
  37710. _setValue_direct_setNeedsUpdate( buffer, offset ) {
  37711. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37712. this.targetObject.needsUpdate = true;
  37713. }
  37714. _setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37715. this.targetObject[ this.propertyName ] = buffer[ offset ];
  37716. this.targetObject.matrixWorldNeedsUpdate = true;
  37717. }
  37718. // EntireArray
  37719. _setValue_array( buffer, offset ) {
  37720. const dest = this.resolvedProperty;
  37721. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37722. dest[ i ] = buffer[ offset ++ ];
  37723. }
  37724. }
  37725. _setValue_array_setNeedsUpdate( buffer, offset ) {
  37726. const dest = this.resolvedProperty;
  37727. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37728. dest[ i ] = buffer[ offset ++ ];
  37729. }
  37730. this.targetObject.needsUpdate = true;
  37731. }
  37732. _setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37733. const dest = this.resolvedProperty;
  37734. for ( let i = 0, n = dest.length; i !== n; ++ i ) {
  37735. dest[ i ] = buffer[ offset ++ ];
  37736. }
  37737. this.targetObject.matrixWorldNeedsUpdate = true;
  37738. }
  37739. // ArrayElement
  37740. _setValue_arrayElement( buffer, offset ) {
  37741. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37742. }
  37743. _setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  37744. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37745. this.targetObject.needsUpdate = true;
  37746. }
  37747. _setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37748. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  37749. this.targetObject.matrixWorldNeedsUpdate = true;
  37750. }
  37751. // HasToFromArray
  37752. _setValue_fromArray( buffer, offset ) {
  37753. this.resolvedProperty.fromArray( buffer, offset );
  37754. }
  37755. _setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  37756. this.resolvedProperty.fromArray( buffer, offset );
  37757. this.targetObject.needsUpdate = true;
  37758. }
  37759. _setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  37760. this.resolvedProperty.fromArray( buffer, offset );
  37761. this.targetObject.matrixWorldNeedsUpdate = true;
  37762. }
  37763. _getValue_unbound( targetArray, offset ) {
  37764. this.bind();
  37765. this.getValue( targetArray, offset );
  37766. }
  37767. _setValue_unbound( sourceArray, offset ) {
  37768. this.bind();
  37769. this.setValue( sourceArray, offset );
  37770. }
  37771. /**
  37772. * Creates a getter / setter pair for the property tracked by this binding.
  37773. */
  37774. bind() {
  37775. let targetObject = this.node;
  37776. const parsedPath = this.parsedPath;
  37777. const objectName = parsedPath.objectName;
  37778. const propertyName = parsedPath.propertyName;
  37779. let propertyIndex = parsedPath.propertyIndex;
  37780. if ( ! targetObject ) {
  37781. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName );
  37782. this.node = targetObject;
  37783. }
  37784. // set fail state so we can just 'return' on error
  37785. this.getValue = this._getValue_unavailable;
  37786. this.setValue = this._setValue_unavailable;
  37787. // ensure there is a value node
  37788. if ( ! targetObject ) {
  37789. warn( 'PropertyBinding: No target node found for track: ' + this.path + '.' );
  37790. return;
  37791. }
  37792. if ( objectName ) {
  37793. let objectIndex = parsedPath.objectIndex;
  37794. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  37795. switch ( objectName ) {
  37796. case 'materials':
  37797. if ( ! targetObject.material ) {
  37798. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37799. return;
  37800. }
  37801. if ( ! targetObject.material.materials ) {
  37802. error( 'PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  37803. return;
  37804. }
  37805. targetObject = targetObject.material.materials;
  37806. break;
  37807. case 'bones':
  37808. if ( ! targetObject.skeleton ) {
  37809. error( 'PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  37810. return;
  37811. }
  37812. // potential future optimization: skip this if propertyIndex is already an integer
  37813. // and convert the integer string to a true integer.
  37814. targetObject = targetObject.skeleton.bones;
  37815. // support resolving morphTarget names into indices.
  37816. for ( let i = 0; i < targetObject.length; i ++ ) {
  37817. if ( targetObject[ i ].name === objectIndex ) {
  37818. objectIndex = i;
  37819. break;
  37820. }
  37821. }
  37822. break;
  37823. case 'map':
  37824. if ( 'map' in targetObject ) {
  37825. targetObject = targetObject.map;
  37826. break;
  37827. }
  37828. if ( ! targetObject.material ) {
  37829. error( 'PropertyBinding: Can not bind to material as node does not have a material.', this );
  37830. return;
  37831. }
  37832. if ( ! targetObject.material.map ) {
  37833. error( 'PropertyBinding: Can not bind to material.map as node.material does not have a map.', this );
  37834. return;
  37835. }
  37836. targetObject = targetObject.material.map;
  37837. break;
  37838. default:
  37839. if ( targetObject[ objectName ] === undefined ) {
  37840. error( 'PropertyBinding: Can not bind to objectName of node undefined.', this );
  37841. return;
  37842. }
  37843. targetObject = targetObject[ objectName ];
  37844. }
  37845. if ( objectIndex !== undefined ) {
  37846. if ( targetObject[ objectIndex ] === undefined ) {
  37847. error( 'PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  37848. return;
  37849. }
  37850. targetObject = targetObject[ objectIndex ];
  37851. }
  37852. }
  37853. // resolve property
  37854. const nodeProperty = targetObject[ propertyName ];
  37855. if ( nodeProperty === undefined ) {
  37856. const nodeName = parsedPath.nodeName;
  37857. error( 'PropertyBinding: Trying to update property for track: ' + nodeName +
  37858. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  37859. return;
  37860. }
  37861. // determine versioning scheme
  37862. let versioning = this.Versioning.None;
  37863. this.targetObject = targetObject;
  37864. if ( targetObject.isMaterial === true ) {
  37865. versioning = this.Versioning.NeedsUpdate;
  37866. } else if ( targetObject.isObject3D === true ) {
  37867. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  37868. }
  37869. // determine how the property gets bound
  37870. let bindingType = this.BindingType.Direct;
  37871. if ( propertyIndex !== undefined ) {
  37872. // access a sub element of the property array (only primitives are supported right now)
  37873. if ( propertyName === 'morphTargetInfluences' ) {
  37874. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  37875. // support resolving morphTarget names into indices.
  37876. if ( ! targetObject.geometry ) {
  37877. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  37878. return;
  37879. }
  37880. if ( ! targetObject.geometry.morphAttributes ) {
  37881. error( 'PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  37882. return;
  37883. }
  37884. if ( targetObject.morphTargetDictionary[ propertyIndex ] !== undefined ) {
  37885. propertyIndex = targetObject.morphTargetDictionary[ propertyIndex ];
  37886. }
  37887. }
  37888. bindingType = this.BindingType.ArrayElement;
  37889. this.resolvedProperty = nodeProperty;
  37890. this.propertyIndex = propertyIndex;
  37891. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  37892. // must use copy for Object3D.Euler/Quaternion
  37893. bindingType = this.BindingType.HasFromToArray;
  37894. this.resolvedProperty = nodeProperty;
  37895. } else if ( Array.isArray( nodeProperty ) ) {
  37896. bindingType = this.BindingType.EntireArray;
  37897. this.resolvedProperty = nodeProperty;
  37898. } else {
  37899. this.propertyName = propertyName;
  37900. }
  37901. // select getter / setter
  37902. this.getValue = this.GetterByBindingType[ bindingType ];
  37903. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  37904. }
  37905. /**
  37906. * Unbinds the property.
  37907. */
  37908. unbind() {
  37909. this.node = null;
  37910. // back to the prototype version of getValue / setValue
  37911. // note: avoiding to mutate the shape of 'this' via 'delete'
  37912. this.getValue = this._getValue_unbound;
  37913. this.setValue = this._setValue_unbound;
  37914. }
  37915. }
  37916. PropertyBinding.Composite = Composite;
  37917. PropertyBinding.prototype.BindingType = {
  37918. Direct: 0,
  37919. EntireArray: 1,
  37920. ArrayElement: 2,
  37921. HasFromToArray: 3
  37922. };
  37923. PropertyBinding.prototype.Versioning = {
  37924. None: 0,
  37925. NeedsUpdate: 1,
  37926. MatrixWorldNeedsUpdate: 2
  37927. };
  37928. PropertyBinding.prototype.GetterByBindingType = [
  37929. PropertyBinding.prototype._getValue_direct,
  37930. PropertyBinding.prototype._getValue_array,
  37931. PropertyBinding.prototype._getValue_arrayElement,
  37932. PropertyBinding.prototype._getValue_toArray,
  37933. ];
  37934. PropertyBinding.prototype.SetterByBindingTypeAndVersioning = [
  37935. [
  37936. // Direct
  37937. PropertyBinding.prototype._setValue_direct,
  37938. PropertyBinding.prototype._setValue_direct_setNeedsUpdate,
  37939. PropertyBinding.prototype._setValue_direct_setMatrixWorldNeedsUpdate,
  37940. ], [
  37941. // EntireArray
  37942. PropertyBinding.prototype._setValue_array,
  37943. PropertyBinding.prototype._setValue_array_setNeedsUpdate,
  37944. PropertyBinding.prototype._setValue_array_setMatrixWorldNeedsUpdate,
  37945. ], [
  37946. // ArrayElement
  37947. PropertyBinding.prototype._setValue_arrayElement,
  37948. PropertyBinding.prototype._setValue_arrayElement_setNeedsUpdate,
  37949. PropertyBinding.prototype._setValue_arrayElement_setMatrixWorldNeedsUpdate,
  37950. ], [
  37951. // HasToFromArray
  37952. PropertyBinding.prototype._setValue_fromArray,
  37953. PropertyBinding.prototype._setValue_fromArray_setNeedsUpdate,
  37954. PropertyBinding.prototype._setValue_fromArray_setMatrixWorldNeedsUpdate,
  37955. ]
  37956. ];
  37957. /**
  37958. * A group of objects that receives a shared animation state.
  37959. *
  37960. * Usage:
  37961. *
  37962. * - Add objects you would otherwise pass as 'root' to the
  37963. * constructor or the .clipAction method of AnimationMixer.
  37964. * - Instead pass this object as 'root'.
  37965. * - You can also add and remove objects later when the mixer is running.
  37966. *
  37967. * Note:
  37968. *
  37969. * - Objects of this class appear as one object to the mixer,
  37970. * so cache control of the individual objects must be done on the group.
  37971. *
  37972. * Limitation:
  37973. *
  37974. * - The animated properties must be compatible among the all objects in the group.
  37975. * - A single property can either be controlled through a target group or directly, but not both.
  37976. */
  37977. class AnimationObjectGroup {
  37978. /**
  37979. * Constructs a new animation group.
  37980. *
  37981. * @param {...Object3D} arguments - An arbitrary number of 3D objects that share the same animation state.
  37982. */
  37983. constructor() {
  37984. /**
  37985. * This flag can be used for type testing.
  37986. *
  37987. * @type {boolean}
  37988. * @readonly
  37989. * @default true
  37990. */
  37991. this.isAnimationObjectGroup = true;
  37992. /**
  37993. * The UUID of the 3D object.
  37994. *
  37995. * @type {string}
  37996. * @readonly
  37997. */
  37998. this.uuid = generateUUID();
  37999. // cached objects followed by the active ones
  38000. this._objects = Array.prototype.slice.call( arguments );
  38001. this.nCachedObjects_ = 0; // threshold
  38002. // note: read by PropertyBinding.Composite
  38003. const indices = {};
  38004. this._indicesByUUID = indices; // for bookkeeping
  38005. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38006. indices[ arguments[ i ].uuid ] = i;
  38007. }
  38008. this._paths = []; // inside: string
  38009. this._parsedPaths = []; // inside: { we don't care, here }
  38010. this._bindings = []; // inside: Array< PropertyBinding >
  38011. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  38012. const scope = this;
  38013. this.stats = {
  38014. objects: {
  38015. get total() {
  38016. return scope._objects.length;
  38017. },
  38018. get inUse() {
  38019. return this.total - scope.nCachedObjects_;
  38020. }
  38021. },
  38022. get bindingsPerObject() {
  38023. return scope._bindings.length;
  38024. }
  38025. };
  38026. }
  38027. /**
  38028. * Adds an arbitrary number of objects to this animation group.
  38029. *
  38030. * @param {...Object3D} arguments - The 3D objects to add.
  38031. */
  38032. add() {
  38033. const objects = this._objects,
  38034. indicesByUUID = this._indicesByUUID,
  38035. paths = this._paths,
  38036. parsedPaths = this._parsedPaths,
  38037. bindings = this._bindings,
  38038. nBindings = bindings.length;
  38039. let knownObject = undefined,
  38040. nObjects = objects.length,
  38041. nCachedObjects = this.nCachedObjects_;
  38042. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38043. const object = arguments[ i ],
  38044. uuid = object.uuid;
  38045. let index = indicesByUUID[ uuid ];
  38046. if ( index === undefined ) {
  38047. // unknown object -> add it to the ACTIVE region
  38048. index = nObjects ++;
  38049. indicesByUUID[ uuid ] = index;
  38050. objects.push( object );
  38051. // accounting is done, now do the same for all bindings
  38052. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38053. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  38054. }
  38055. } else if ( index < nCachedObjects ) {
  38056. knownObject = objects[ index ];
  38057. // move existing object to the ACTIVE region
  38058. const firstActiveIndex = -- nCachedObjects,
  38059. lastCachedObject = objects[ firstActiveIndex ];
  38060. indicesByUUID[ lastCachedObject.uuid ] = index;
  38061. objects[ index ] = lastCachedObject;
  38062. indicesByUUID[ uuid ] = firstActiveIndex;
  38063. objects[ firstActiveIndex ] = object;
  38064. // accounting is done, now do the same for all bindings
  38065. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38066. const bindingsForPath = bindings[ j ],
  38067. lastCached = bindingsForPath[ firstActiveIndex ];
  38068. let binding = bindingsForPath[ index ];
  38069. bindingsForPath[ index ] = lastCached;
  38070. if ( binding === undefined ) {
  38071. // since we do not bother to create new bindings
  38072. // for objects that are cached, the binding may
  38073. // or may not exist
  38074. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  38075. }
  38076. bindingsForPath[ firstActiveIndex ] = binding;
  38077. }
  38078. } else if ( objects[ index ] !== knownObject ) {
  38079. error( 'AnimationObjectGroup: Different objects with the same UUID ' +
  38080. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  38081. } // else the object is already where we want it to be
  38082. } // for arguments
  38083. this.nCachedObjects_ = nCachedObjects;
  38084. }
  38085. /**
  38086. * Removes an arbitrary number of objects to this animation group
  38087. *
  38088. * @param {...Object3D} arguments - The 3D objects to remove.
  38089. */
  38090. remove() {
  38091. const objects = this._objects,
  38092. indicesByUUID = this._indicesByUUID,
  38093. bindings = this._bindings,
  38094. nBindings = bindings.length;
  38095. let nCachedObjects = this.nCachedObjects_;
  38096. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38097. const object = arguments[ i ],
  38098. uuid = object.uuid,
  38099. index = indicesByUUID[ uuid ];
  38100. if ( index !== undefined && index >= nCachedObjects ) {
  38101. // move existing object into the CACHED region
  38102. const lastCachedIndex = nCachedObjects ++,
  38103. firstActiveObject = objects[ lastCachedIndex ];
  38104. indicesByUUID[ firstActiveObject.uuid ] = index;
  38105. objects[ index ] = firstActiveObject;
  38106. indicesByUUID[ uuid ] = lastCachedIndex;
  38107. objects[ lastCachedIndex ] = object;
  38108. // accounting is done, now do the same for all bindings
  38109. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38110. const bindingsForPath = bindings[ j ],
  38111. firstActive = bindingsForPath[ lastCachedIndex ],
  38112. binding = bindingsForPath[ index ];
  38113. bindingsForPath[ index ] = firstActive;
  38114. bindingsForPath[ lastCachedIndex ] = binding;
  38115. }
  38116. }
  38117. } // for arguments
  38118. this.nCachedObjects_ = nCachedObjects;
  38119. }
  38120. /**
  38121. * Deallocates all memory resources for the passed 3D objects of this animation group.
  38122. *
  38123. * @param {...Object3D} arguments - The 3D objects to uncache.
  38124. */
  38125. uncache() {
  38126. const objects = this._objects,
  38127. indicesByUUID = this._indicesByUUID,
  38128. bindings = this._bindings,
  38129. nBindings = bindings.length;
  38130. let nCachedObjects = this.nCachedObjects_,
  38131. nObjects = objects.length;
  38132. for ( let i = 0, n = arguments.length; i !== n; ++ i ) {
  38133. const object = arguments[ i ],
  38134. uuid = object.uuid,
  38135. index = indicesByUUID[ uuid ];
  38136. if ( index !== undefined ) {
  38137. delete indicesByUUID[ uuid ];
  38138. if ( index < nCachedObjects ) {
  38139. // object is cached, shrink the CACHED region
  38140. const firstActiveIndex = -- nCachedObjects,
  38141. lastCachedObject = objects[ firstActiveIndex ],
  38142. lastIndex = -- nObjects,
  38143. lastObject = objects[ lastIndex ];
  38144. // last cached object takes this object's place
  38145. indicesByUUID[ lastCachedObject.uuid ] = index;
  38146. objects[ index ] = lastCachedObject;
  38147. // last object goes to the activated slot and pop
  38148. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  38149. objects[ firstActiveIndex ] = lastObject;
  38150. objects.pop();
  38151. // accounting is done, now do the same for all bindings
  38152. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38153. const bindingsForPath = bindings[ j ],
  38154. lastCached = bindingsForPath[ firstActiveIndex ],
  38155. last = bindingsForPath[ lastIndex ];
  38156. bindingsForPath[ index ] = lastCached;
  38157. bindingsForPath[ firstActiveIndex ] = last;
  38158. bindingsForPath.pop();
  38159. }
  38160. } else {
  38161. // object is active, just swap with the last and pop
  38162. const lastIndex = -- nObjects,
  38163. lastObject = objects[ lastIndex ];
  38164. if ( lastIndex > 0 ) {
  38165. indicesByUUID[ lastObject.uuid ] = index;
  38166. }
  38167. objects[ index ] = lastObject;
  38168. objects.pop();
  38169. // accounting is done, now do the same for all bindings
  38170. for ( let j = 0, m = nBindings; j !== m; ++ j ) {
  38171. const bindingsForPath = bindings[ j ];
  38172. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  38173. bindingsForPath.pop();
  38174. }
  38175. } // cached or active
  38176. } // if object is known
  38177. } // for arguments
  38178. this.nCachedObjects_ = nCachedObjects;
  38179. }
  38180. // Internal interface used by befriended PropertyBinding.Composite:
  38181. subscribe_( path, parsedPath ) {
  38182. // returns an array of bindings for the given path that is changed
  38183. // according to the contained objects in the group
  38184. const indicesByPath = this._bindingsIndicesByPath;
  38185. let index = indicesByPath[ path ];
  38186. const bindings = this._bindings;
  38187. if ( index !== undefined ) return bindings[ index ];
  38188. const paths = this._paths,
  38189. parsedPaths = this._parsedPaths,
  38190. objects = this._objects,
  38191. nObjects = objects.length,
  38192. nCachedObjects = this.nCachedObjects_,
  38193. bindingsForPath = new Array( nObjects );
  38194. index = bindings.length;
  38195. indicesByPath[ path ] = index;
  38196. paths.push( path );
  38197. parsedPaths.push( parsedPath );
  38198. bindings.push( bindingsForPath );
  38199. for ( let i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  38200. const object = objects[ i ];
  38201. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  38202. }
  38203. return bindingsForPath;
  38204. }
  38205. unsubscribe_( path ) {
  38206. // tells the group to forget about a property path and no longer
  38207. // update the array previously obtained with 'subscribe_'
  38208. const indicesByPath = this._bindingsIndicesByPath,
  38209. index = indicesByPath[ path ];
  38210. if ( index !== undefined ) {
  38211. const paths = this._paths,
  38212. parsedPaths = this._parsedPaths,
  38213. bindings = this._bindings,
  38214. lastBindingsIndex = bindings.length - 1,
  38215. lastBindings = bindings[ lastBindingsIndex ],
  38216. lastBindingsPath = path[ lastBindingsIndex ];
  38217. indicesByPath[ lastBindingsPath ] = index;
  38218. bindings[ index ] = lastBindings;
  38219. bindings.pop();
  38220. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  38221. parsedPaths.pop();
  38222. paths[ index ] = paths[ lastBindingsIndex ];
  38223. paths.pop();
  38224. }
  38225. }
  38226. }
  38227. /**
  38228. * An instance of `AnimationAction` schedules the playback of an animation which is
  38229. * stored in {@link AnimationClip}.
  38230. */
  38231. class AnimationAction {
  38232. /**
  38233. * Constructs a new animation action.
  38234. *
  38235. * @param {AnimationMixer} mixer - The mixer that is controlled by this action.
  38236. * @param {AnimationClip} clip - The animation clip that holds the actual keyframes.
  38237. * @param {?Object3D} [localRoot=null] - The root object on which this action is performed.
  38238. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  38239. */
  38240. constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
  38241. this._mixer = mixer;
  38242. this._clip = clip;
  38243. this._localRoot = localRoot;
  38244. /**
  38245. * Defines how the animation is blended/combined when two or more animations
  38246. * are simultaneously played.
  38247. *
  38248. * @type {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)}
  38249. */
  38250. this.blendMode = blendMode;
  38251. const tracks = clip.tracks,
  38252. nTracks = tracks.length,
  38253. interpolants = new Array( nTracks );
  38254. const interpolantSettings = {
  38255. endingStart: ZeroCurvatureEnding,
  38256. endingEnd: ZeroCurvatureEnding
  38257. };
  38258. for ( let i = 0; i !== nTracks; ++ i ) {
  38259. const interpolant = tracks[ i ].createInterpolant( null );
  38260. interpolants[ i ] = interpolant;
  38261. interpolant.settings = interpolantSettings;
  38262. }
  38263. this._interpolantSettings = interpolantSettings;
  38264. this._interpolants = interpolants; // bound by the mixer
  38265. // inside: PropertyMixer (managed by the mixer)
  38266. this._propertyBindings = new Array( nTracks );
  38267. this._cacheIndex = null; // for the memory manager
  38268. this._byClipCacheIndex = null; // for the memory manager
  38269. this._timeScaleInterpolant = null;
  38270. this._weightInterpolant = null;
  38271. /**
  38272. * The loop mode, set via {@link AnimationAction#setLoop}.
  38273. *
  38274. * @type {(LoopRepeat|LoopOnce|LoopPingPong)}
  38275. * @default LoopRepeat
  38276. */
  38277. this.loop = LoopRepeat;
  38278. this._loopCount = -1;
  38279. // global mixer time when the action is to be started
  38280. // it's set back to 'null' upon start of the action
  38281. this._startTime = null;
  38282. /**
  38283. * The local time of this action (in seconds, starting with `0`).
  38284. *
  38285. * The value gets clamped or wrapped to `[0,clip.duration]` (according to the
  38286. * loop state).
  38287. *
  38288. * @type {number}
  38289. * @default Infinity
  38290. */
  38291. this.time = 0;
  38292. /**
  38293. * Scaling factor for the {@link AnimationAction#time}. A value of `0` causes the
  38294. * animation to pause. Negative values cause the animation to play backwards.
  38295. *
  38296. * @type {number}
  38297. * @default 1
  38298. */
  38299. this.timeScale = 1;
  38300. this._effectiveTimeScale = 1;
  38301. /**
  38302. * The degree of influence of this action (in the interval `[0, 1]`). Values
  38303. * between `0` (no impact) and `1` (full impact) can be used to blend between
  38304. * several actions.
  38305. *
  38306. * @type {number}
  38307. * @default 1
  38308. */
  38309. this.weight = 1;
  38310. this._effectiveWeight = 1;
  38311. /**
  38312. * The number of repetitions of the performed clip over the course of this action.
  38313. * Can be set via {@link AnimationAction#setLoop}.
  38314. *
  38315. * Setting this number has no effect if {@link AnimationAction#loop} is set to
  38316. * `THREE:LoopOnce`.
  38317. *
  38318. * @type {number}
  38319. * @default Infinity
  38320. */
  38321. this.repetitions = Infinity;
  38322. /**
  38323. * If set to `true`, the playback of the action is paused.
  38324. *
  38325. * @type {boolean}
  38326. * @default false
  38327. */
  38328. this.paused = false;
  38329. /**
  38330. * If set to `false`, the action is disabled so it has no impact.
  38331. *
  38332. * When the action is re-enabled, the animation continues from its current
  38333. * time (setting `enabled` to `false` doesn't reset the action).
  38334. *
  38335. * @type {boolean}
  38336. * @default true
  38337. */
  38338. this.enabled = true;
  38339. /**
  38340. * If set to true the animation will automatically be paused on its last frame.
  38341. *
  38342. * If set to false, {@link AnimationAction#enabled} will automatically be switched
  38343. * to `false` when the last loop of the action has finished, so that this action has
  38344. * no further impact.
  38345. *
  38346. * Note: This member has no impact if the action is interrupted (it
  38347. * has only an effect if its last loop has really finished).
  38348. *
  38349. * @type {boolean}
  38350. * @default false
  38351. */
  38352. this.clampWhenFinished = false;
  38353. /**
  38354. * Enables smooth interpolation without separate clips for start, loop and end.
  38355. *
  38356. * @type {boolean}
  38357. * @default true
  38358. */
  38359. this.zeroSlopeAtStart = true;
  38360. /**
  38361. * Enables smooth interpolation without separate clips for start, loop and end.
  38362. *
  38363. * @type {boolean}
  38364. * @default true
  38365. */
  38366. this.zeroSlopeAtEnd = true;
  38367. }
  38368. /**
  38369. * Starts the playback of the animation.
  38370. *
  38371. * @return {AnimationAction} A reference to this animation action.
  38372. */
  38373. play() {
  38374. this._mixer._activateAction( this );
  38375. return this;
  38376. }
  38377. /**
  38378. * Stops the playback of the animation.
  38379. *
  38380. * @return {AnimationAction} A reference to this animation action.
  38381. */
  38382. stop() {
  38383. this._mixer._deactivateAction( this );
  38384. return this.reset();
  38385. }
  38386. /**
  38387. * Resets the playback of the animation.
  38388. *
  38389. * @return {AnimationAction} A reference to this animation action.
  38390. */
  38391. reset() {
  38392. this.paused = false;
  38393. this.enabled = true;
  38394. this.time = 0; // restart clip
  38395. this._loopCount = -1;// forget previous loops
  38396. this._startTime = null;// forget scheduling
  38397. return this.stopFading().stopWarping();
  38398. }
  38399. /**
  38400. * Returns `true` if the animation is running.
  38401. *
  38402. * @return {boolean} Whether the animation is running or not.
  38403. */
  38404. isRunning() {
  38405. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  38406. this._startTime === null && this._mixer._isActiveAction( this );
  38407. }
  38408. /**
  38409. * Returns `true` when {@link AnimationAction#play} has been called.
  38410. *
  38411. * @return {boolean} Whether the animation is scheduled or not.
  38412. */
  38413. isScheduled() {
  38414. return this._mixer._isActiveAction( this );
  38415. }
  38416. /**
  38417. * Defines the time when the animation should start.
  38418. *
  38419. * @param {number} time - The start time in seconds.
  38420. * @return {AnimationAction} A reference to this animation action.
  38421. */
  38422. startAt( time ) {
  38423. this._startTime = time;
  38424. return this;
  38425. }
  38426. /**
  38427. * Configures the loop settings for this action.
  38428. *
  38429. * @param {(LoopRepeat|LoopOnce|LoopPingPong)} mode - The loop mode.
  38430. * @param {number} repetitions - The number of repetitions.
  38431. * @return {AnimationAction} A reference to this animation action.
  38432. */
  38433. setLoop( mode, repetitions ) {
  38434. this.loop = mode;
  38435. this.repetitions = repetitions;
  38436. return this;
  38437. }
  38438. /**
  38439. * Sets the effective weight of this action.
  38440. *
  38441. * An action has no effect and thus an effective weight of zero when the
  38442. * action is disabled.
  38443. *
  38444. * @param {number} weight - The weight to set.
  38445. * @return {AnimationAction} A reference to this animation action.
  38446. */
  38447. setEffectiveWeight( weight ) {
  38448. this.weight = weight;
  38449. // note: same logic as when updated at runtime
  38450. this._effectiveWeight = this.enabled ? weight : 0;
  38451. return this.stopFading();
  38452. }
  38453. /**
  38454. * Returns the effective weight of this action.
  38455. *
  38456. * @return {number} The effective weight.
  38457. */
  38458. getEffectiveWeight() {
  38459. return this._effectiveWeight;
  38460. }
  38461. /**
  38462. * Fades the animation in by increasing its weight gradually from `0` to `1`,
  38463. * within the passed time interval.
  38464. *
  38465. * @param {number} duration - The duration of the fade.
  38466. * @return {AnimationAction} A reference to this animation action.
  38467. */
  38468. fadeIn( duration ) {
  38469. return this._scheduleFading( duration, 0, 1 );
  38470. }
  38471. /**
  38472. * Fades the animation out by decreasing its weight gradually from `1` to `0`,
  38473. * within the passed time interval.
  38474. *
  38475. * @param {number} duration - The duration of the fade.
  38476. * @return {AnimationAction} A reference to this animation action.
  38477. */
  38478. fadeOut( duration ) {
  38479. return this._scheduleFading( duration, 1, 0 );
  38480. }
  38481. /**
  38482. * Causes this action to fade in and the given action to fade out,
  38483. * within the passed time interval.
  38484. *
  38485. * @param {AnimationAction} fadeOutAction - The animation action to fade out.
  38486. * @param {number} duration - The duration of the fade.
  38487. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38488. * @return {AnimationAction} A reference to this animation action.
  38489. */
  38490. crossFadeFrom( fadeOutAction, duration, warp = false ) {
  38491. fadeOutAction.fadeOut( duration );
  38492. this.fadeIn( duration );
  38493. if ( warp === true ) {
  38494. const fadeInDuration = this._clip.duration,
  38495. fadeOutDuration = fadeOutAction._clip.duration,
  38496. startEndRatio = fadeOutDuration / fadeInDuration,
  38497. endStartRatio = fadeInDuration / fadeOutDuration;
  38498. fadeOutAction.warp( 1.0, startEndRatio, duration );
  38499. this.warp( endStartRatio, 1.0, duration );
  38500. }
  38501. return this;
  38502. }
  38503. /**
  38504. * Causes this action to fade out and the given action to fade in,
  38505. * within the passed time interval.
  38506. *
  38507. * @param {AnimationAction} fadeInAction - The animation action to fade in.
  38508. * @param {number} duration - The duration of the fade.
  38509. * @param {boolean} [warp=false] - Whether warping should be used or not.
  38510. * @return {AnimationAction} A reference to this animation action.
  38511. */
  38512. crossFadeTo( fadeInAction, duration, warp = false ) {
  38513. return fadeInAction.crossFadeFrom( this, duration, warp );
  38514. }
  38515. /**
  38516. * Stops any fading which is applied to this action.
  38517. *
  38518. * @return {AnimationAction} A reference to this animation action.
  38519. */
  38520. stopFading() {
  38521. const weightInterpolant = this._weightInterpolant;
  38522. if ( weightInterpolant !== null ) {
  38523. this._weightInterpolant = null;
  38524. this._mixer._takeBackControlInterpolant( weightInterpolant );
  38525. }
  38526. return this;
  38527. }
  38528. /**
  38529. * Sets the effective time scale of this action.
  38530. *
  38531. * An action has no effect and thus an effective time scale of zero when the
  38532. * action is paused.
  38533. *
  38534. * @param {number} timeScale - The time scale to set.
  38535. * @return {AnimationAction} A reference to this animation action.
  38536. */
  38537. setEffectiveTimeScale( timeScale ) {
  38538. this.timeScale = timeScale;
  38539. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  38540. return this.stopWarping();
  38541. }
  38542. /**
  38543. * Returns the effective time scale of this action.
  38544. *
  38545. * @return {number} The effective time scale.
  38546. */
  38547. getEffectiveTimeScale() {
  38548. return this._effectiveTimeScale;
  38549. }
  38550. /**
  38551. * Sets the duration for a single loop of this action.
  38552. *
  38553. * @param {number} duration - The duration to set.
  38554. * @return {AnimationAction} A reference to this animation action.
  38555. */
  38556. setDuration( duration ) {
  38557. this.timeScale = this._clip.duration / duration;
  38558. return this.stopWarping();
  38559. }
  38560. /**
  38561. * Synchronizes this action with the passed other action.
  38562. *
  38563. * @param {AnimationAction} action - The action to sync with.
  38564. * @return {AnimationAction} A reference to this animation action.
  38565. */
  38566. syncWith( action ) {
  38567. this.time = action.time;
  38568. this.timeScale = action.timeScale;
  38569. return this.stopWarping();
  38570. }
  38571. /**
  38572. * Decelerates this animation's speed to `0` within the passed time interval.
  38573. *
  38574. * @param {number} duration - The duration.
  38575. * @return {AnimationAction} A reference to this animation action.
  38576. */
  38577. halt( duration ) {
  38578. return this.warp( this._effectiveTimeScale, 0, duration );
  38579. }
  38580. /**
  38581. * Changes the playback speed, within the passed time interval, by modifying
  38582. * {@link AnimationAction#timeScale} gradually from `startTimeScale` to
  38583. * `endTimeScale`.
  38584. *
  38585. * @param {number} startTimeScale - The start time scale.
  38586. * @param {number} endTimeScale - The end time scale.
  38587. * @param {number} duration - The duration.
  38588. * @return {AnimationAction} A reference to this animation action.
  38589. */
  38590. warp( startTimeScale, endTimeScale, duration ) {
  38591. const mixer = this._mixer,
  38592. now = mixer.time,
  38593. timeScale = this.timeScale;
  38594. let interpolant = this._timeScaleInterpolant;
  38595. if ( interpolant === null ) {
  38596. interpolant = mixer._lendControlInterpolant();
  38597. this._timeScaleInterpolant = interpolant;
  38598. }
  38599. const times = interpolant.parameterPositions,
  38600. values = interpolant.sampleValues;
  38601. times[ 0 ] = now;
  38602. times[ 1 ] = now + duration;
  38603. values[ 0 ] = startTimeScale / timeScale;
  38604. values[ 1 ] = endTimeScale / timeScale;
  38605. return this;
  38606. }
  38607. /**
  38608. * Stops any scheduled warping which is applied to this action.
  38609. *
  38610. * @return {AnimationAction} A reference to this animation action.
  38611. */
  38612. stopWarping() {
  38613. const timeScaleInterpolant = this._timeScaleInterpolant;
  38614. if ( timeScaleInterpolant !== null ) {
  38615. this._timeScaleInterpolant = null;
  38616. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  38617. }
  38618. return this;
  38619. }
  38620. /**
  38621. * Returns the animation mixer of this animation action.
  38622. *
  38623. * @return {AnimationMixer} The animation mixer.
  38624. */
  38625. getMixer() {
  38626. return this._mixer;
  38627. }
  38628. /**
  38629. * Returns the animation clip of this animation action.
  38630. *
  38631. * @return {AnimationClip} The animation clip.
  38632. */
  38633. getClip() {
  38634. return this._clip;
  38635. }
  38636. /**
  38637. * Returns the root object of this animation action.
  38638. *
  38639. * @return {Object3D} The root object.
  38640. */
  38641. getRoot() {
  38642. return this._localRoot || this._mixer._root;
  38643. }
  38644. // Interna
  38645. _update( time, deltaTime, timeDirection, accuIndex ) {
  38646. // called by the mixer
  38647. if ( ! this.enabled ) {
  38648. // call ._updateWeight() to update ._effectiveWeight
  38649. this._updateWeight( time );
  38650. return;
  38651. }
  38652. const startTime = this._startTime;
  38653. if ( startTime !== null ) {
  38654. // check for scheduled start of action
  38655. const timeRunning = ( time - startTime ) * timeDirection;
  38656. if ( timeRunning < 0 || timeDirection === 0 ) {
  38657. deltaTime = 0;
  38658. } else {
  38659. this._startTime = null; // unschedule
  38660. deltaTime = timeDirection * timeRunning;
  38661. }
  38662. }
  38663. // apply time scale and advance time
  38664. deltaTime *= this._updateTimeScale( time );
  38665. const clipTime = this._updateTime( deltaTime );
  38666. // note: _updateTime may disable the action resulting in
  38667. // an effective weight of 0
  38668. const weight = this._updateWeight( time );
  38669. if ( weight > 0 ) {
  38670. const interpolants = this._interpolants;
  38671. const propertyMixers = this._propertyBindings;
  38672. switch ( this.blendMode ) {
  38673. case AdditiveAnimationBlendMode:
  38674. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38675. interpolants[ j ].evaluate( clipTime );
  38676. propertyMixers[ j ].accumulateAdditive( weight );
  38677. }
  38678. break;
  38679. case NormalAnimationBlendMode:
  38680. default:
  38681. for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
  38682. interpolants[ j ].evaluate( clipTime );
  38683. propertyMixers[ j ].accumulate( accuIndex, weight );
  38684. }
  38685. }
  38686. }
  38687. }
  38688. _updateWeight( time ) {
  38689. let weight = 0;
  38690. if ( this.enabled ) {
  38691. weight = this.weight;
  38692. const interpolant = this._weightInterpolant;
  38693. if ( interpolant !== null ) {
  38694. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38695. weight *= interpolantValue;
  38696. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38697. this.stopFading();
  38698. if ( interpolantValue === 0 ) {
  38699. // faded out, disable
  38700. this.enabled = false;
  38701. }
  38702. }
  38703. }
  38704. }
  38705. this._effectiveWeight = weight;
  38706. return weight;
  38707. }
  38708. _updateTimeScale( time ) {
  38709. let timeScale = 0;
  38710. if ( ! this.paused ) {
  38711. timeScale = this.timeScale;
  38712. const interpolant = this._timeScaleInterpolant;
  38713. if ( interpolant !== null ) {
  38714. const interpolantValue = interpolant.evaluate( time )[ 0 ];
  38715. timeScale *= interpolantValue;
  38716. if ( time > interpolant.parameterPositions[ 1 ] ) {
  38717. this.stopWarping();
  38718. if ( timeScale === 0 ) {
  38719. // motion has halted, pause
  38720. this.paused = true;
  38721. } else {
  38722. // warp done - apply final time scale
  38723. this.timeScale = timeScale;
  38724. }
  38725. }
  38726. }
  38727. }
  38728. this._effectiveTimeScale = timeScale;
  38729. return timeScale;
  38730. }
  38731. _updateTime( deltaTime ) {
  38732. const duration = this._clip.duration;
  38733. const loop = this.loop;
  38734. let time = this.time + deltaTime;
  38735. let loopCount = this._loopCount;
  38736. const pingPong = ( loop === LoopPingPong );
  38737. if ( deltaTime === 0 ) {
  38738. if ( loopCount === -1 ) return time;
  38739. return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
  38740. }
  38741. if ( loop === LoopOnce ) {
  38742. if ( loopCount === -1 ) {
  38743. // just started
  38744. this._loopCount = 0;
  38745. this._setEndings( true, true, false );
  38746. }
  38747. handle_stop: {
  38748. if ( time >= duration ) {
  38749. time = duration;
  38750. } else if ( time < 0 ) {
  38751. time = 0;
  38752. } else {
  38753. this.time = time;
  38754. break handle_stop;
  38755. }
  38756. if ( this.clampWhenFinished ) this.paused = true;
  38757. else this.enabled = false;
  38758. this.time = time;
  38759. this._mixer.dispatchEvent( {
  38760. type: 'finished', action: this,
  38761. direction: deltaTime < 0 ? -1 : 1
  38762. } );
  38763. }
  38764. } else { // repetitive Repeat or PingPong
  38765. if ( loopCount === -1 ) {
  38766. // just started
  38767. if ( deltaTime >= 0 ) {
  38768. loopCount = 0;
  38769. this._setEndings( true, this.repetitions === 0, pingPong );
  38770. } else {
  38771. // when looping in reverse direction, the initial
  38772. // transition through zero counts as a repetition,
  38773. // so leave loopCount at -1
  38774. this._setEndings( this.repetitions === 0, true, pingPong );
  38775. }
  38776. }
  38777. if ( time >= duration || time < 0 ) {
  38778. // wrap around
  38779. const loopDelta = Math.floor( time / duration ); // signed
  38780. time -= duration * loopDelta;
  38781. loopCount += Math.abs( loopDelta );
  38782. const pending = this.repetitions - loopCount;
  38783. if ( pending <= 0 ) {
  38784. // have to stop (switch state, clamp time, fire event)
  38785. if ( this.clampWhenFinished ) this.paused = true;
  38786. else this.enabled = false;
  38787. time = deltaTime > 0 ? duration : 0;
  38788. this.time = time;
  38789. this._mixer.dispatchEvent( {
  38790. type: 'finished', action: this,
  38791. direction: deltaTime > 0 ? 1 : -1
  38792. } );
  38793. } else {
  38794. // keep running
  38795. if ( pending === 1 ) {
  38796. // entering the last round
  38797. const atStart = deltaTime < 0;
  38798. this._setEndings( atStart, ! atStart, pingPong );
  38799. } else {
  38800. this._setEndings( false, false, pingPong );
  38801. }
  38802. this._loopCount = loopCount;
  38803. this.time = time;
  38804. this._mixer.dispatchEvent( {
  38805. type: 'loop', action: this, loopDelta: loopDelta
  38806. } );
  38807. }
  38808. } else {
  38809. this.time = time;
  38810. }
  38811. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  38812. // invert time for the "pong round"
  38813. return duration - time;
  38814. }
  38815. }
  38816. return time;
  38817. }
  38818. _setEndings( atStart, atEnd, pingPong ) {
  38819. const settings = this._interpolantSettings;
  38820. if ( pingPong ) {
  38821. settings.endingStart = ZeroSlopeEnding;
  38822. settings.endingEnd = ZeroSlopeEnding;
  38823. } else {
  38824. // assuming for LoopOnce atStart == atEnd == true
  38825. if ( atStart ) {
  38826. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38827. } else {
  38828. settings.endingStart = WrapAroundEnding;
  38829. }
  38830. if ( atEnd ) {
  38831. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  38832. } else {
  38833. settings.endingEnd = WrapAroundEnding;
  38834. }
  38835. }
  38836. }
  38837. _scheduleFading( duration, weightNow, weightThen ) {
  38838. const mixer = this._mixer, now = mixer.time;
  38839. let interpolant = this._weightInterpolant;
  38840. if ( interpolant === null ) {
  38841. interpolant = mixer._lendControlInterpolant();
  38842. this._weightInterpolant = interpolant;
  38843. }
  38844. const times = interpolant.parameterPositions,
  38845. values = interpolant.sampleValues;
  38846. times[ 0 ] = now;
  38847. values[ 0 ] = weightNow;
  38848. times[ 1 ] = now + duration;
  38849. values[ 1 ] = weightThen;
  38850. return this;
  38851. }
  38852. }
  38853. const _controlInterpolantsResultBuffer = new Float32Array( 1 );
  38854. /**
  38855. * `AnimationMixer` is a player for animations on a particular object in
  38856. * the scene. When multiple objects in the scene are animated independently,
  38857. * one `AnimationMixer` may be used for each object.
  38858. */
  38859. class AnimationMixer extends EventDispatcher {
  38860. /**
  38861. * Constructs a new animation mixer.
  38862. *
  38863. * @param {Object3D} root - The object whose animations shall be played by this mixer.
  38864. */
  38865. constructor( root ) {
  38866. super();
  38867. this._root = root;
  38868. this._initMemoryManager();
  38869. this._accuIndex = 0;
  38870. /**
  38871. * The global mixer time (in seconds; starting with `0` on the mixer's creation).
  38872. *
  38873. * @type {number}
  38874. * @default 0
  38875. */
  38876. this.time = 0;
  38877. /**
  38878. * A scaling factor for the global time.
  38879. *
  38880. * Note: Setting this member to `0` and later back to `1` is a
  38881. * possibility to pause/unpause all actions that are controlled by this
  38882. * mixer.
  38883. *
  38884. * @type {number}
  38885. * @default 1
  38886. */
  38887. this.timeScale = 1.0;
  38888. }
  38889. _bindAction( action, prototypeAction ) {
  38890. const root = action._localRoot || this._root,
  38891. tracks = action._clip.tracks,
  38892. nTracks = tracks.length,
  38893. bindings = action._propertyBindings,
  38894. interpolants = action._interpolants,
  38895. rootUuid = root.uuid,
  38896. bindingsByRoot = this._bindingsByRootAndName;
  38897. let bindingsByName = bindingsByRoot[ rootUuid ];
  38898. if ( bindingsByName === undefined ) {
  38899. bindingsByName = {};
  38900. bindingsByRoot[ rootUuid ] = bindingsByName;
  38901. }
  38902. for ( let i = 0; i !== nTracks; ++ i ) {
  38903. const track = tracks[ i ],
  38904. trackName = track.name;
  38905. let binding = bindingsByName[ trackName ];
  38906. if ( binding !== undefined ) {
  38907. ++ binding.referenceCount;
  38908. bindings[ i ] = binding;
  38909. } else {
  38910. binding = bindings[ i ];
  38911. if ( binding !== undefined ) {
  38912. // existing binding, make sure the cache knows
  38913. if ( binding._cacheIndex === null ) {
  38914. ++ binding.referenceCount;
  38915. this._addInactiveBinding( binding, rootUuid, trackName );
  38916. }
  38917. continue;
  38918. }
  38919. const path = prototypeAction && prototypeAction.
  38920. _propertyBindings[ i ].binding.parsedPath;
  38921. binding = new PropertyMixer(
  38922. PropertyBinding.create( root, trackName, path ),
  38923. track.ValueTypeName, track.getValueSize() );
  38924. ++ binding.referenceCount;
  38925. this._addInactiveBinding( binding, rootUuid, trackName );
  38926. bindings[ i ] = binding;
  38927. }
  38928. interpolants[ i ].resultBuffer = binding.buffer;
  38929. }
  38930. }
  38931. _activateAction( action ) {
  38932. if ( ! this._isActiveAction( action ) ) {
  38933. if ( action._cacheIndex === null ) {
  38934. // this action has been forgotten by the cache, but the user
  38935. // appears to be still using it -> rebind
  38936. const rootUuid = ( action._localRoot || this._root ).uuid,
  38937. clipUuid = action._clip.uuid,
  38938. actionsForClip = this._actionsByClip[ clipUuid ];
  38939. this._bindAction( action,
  38940. actionsForClip && actionsForClip.knownActions[ 0 ] );
  38941. this._addInactiveAction( action, clipUuid, rootUuid );
  38942. }
  38943. const bindings = action._propertyBindings;
  38944. // increment reference counts / sort out state
  38945. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38946. const binding = bindings[ i ];
  38947. if ( binding.useCount ++ === 0 ) {
  38948. this._lendBinding( binding );
  38949. binding.saveOriginalState();
  38950. }
  38951. }
  38952. this._lendAction( action );
  38953. }
  38954. }
  38955. _deactivateAction( action ) {
  38956. if ( this._isActiveAction( action ) ) {
  38957. const bindings = action._propertyBindings;
  38958. // decrement reference counts / sort out state
  38959. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  38960. const binding = bindings[ i ];
  38961. if ( -- binding.useCount === 0 ) {
  38962. binding.restoreOriginalState();
  38963. this._takeBackBinding( binding );
  38964. }
  38965. }
  38966. this._takeBackAction( action );
  38967. }
  38968. }
  38969. // Memory manager
  38970. _initMemoryManager() {
  38971. this._actions = []; // 'nActiveActions' followed by inactive ones
  38972. this._nActiveActions = 0;
  38973. this._actionsByClip = {};
  38974. // inside:
  38975. // {
  38976. // knownActions: Array< AnimationAction > - used as prototypes
  38977. // actionByRoot: AnimationAction - lookup
  38978. // }
  38979. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  38980. this._nActiveBindings = 0;
  38981. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  38982. this._controlInterpolants = []; // same game as above
  38983. this._nActiveControlInterpolants = 0;
  38984. const scope = this;
  38985. this.stats = {
  38986. actions: {
  38987. get total() {
  38988. return scope._actions.length;
  38989. },
  38990. get inUse() {
  38991. return scope._nActiveActions;
  38992. }
  38993. },
  38994. bindings: {
  38995. get total() {
  38996. return scope._bindings.length;
  38997. },
  38998. get inUse() {
  38999. return scope._nActiveBindings;
  39000. }
  39001. },
  39002. controlInterpolants: {
  39003. get total() {
  39004. return scope._controlInterpolants.length;
  39005. },
  39006. get inUse() {
  39007. return scope._nActiveControlInterpolants;
  39008. }
  39009. }
  39010. };
  39011. }
  39012. // Memory management for AnimationAction objects
  39013. _isActiveAction( action ) {
  39014. const index = action._cacheIndex;
  39015. return index !== null && index < this._nActiveActions;
  39016. }
  39017. _addInactiveAction( action, clipUuid, rootUuid ) {
  39018. const actions = this._actions,
  39019. actionsByClip = this._actionsByClip;
  39020. let actionsForClip = actionsByClip[ clipUuid ];
  39021. if ( actionsForClip === undefined ) {
  39022. actionsForClip = {
  39023. knownActions: [ action ],
  39024. actionByRoot: {}
  39025. };
  39026. action._byClipCacheIndex = 0;
  39027. actionsByClip[ clipUuid ] = actionsForClip;
  39028. } else {
  39029. const knownActions = actionsForClip.knownActions;
  39030. action._byClipCacheIndex = knownActions.length;
  39031. knownActions.push( action );
  39032. }
  39033. action._cacheIndex = actions.length;
  39034. actions.push( action );
  39035. actionsForClip.actionByRoot[ rootUuid ] = action;
  39036. }
  39037. _removeInactiveAction( action ) {
  39038. const actions = this._actions,
  39039. lastInactiveAction = actions[ actions.length - 1 ],
  39040. cacheIndex = action._cacheIndex;
  39041. lastInactiveAction._cacheIndex = cacheIndex;
  39042. actions[ cacheIndex ] = lastInactiveAction;
  39043. actions.pop();
  39044. action._cacheIndex = null;
  39045. const clipUuid = action._clip.uuid,
  39046. actionsByClip = this._actionsByClip,
  39047. actionsForClip = actionsByClip[ clipUuid ],
  39048. knownActionsForClip = actionsForClip.knownActions,
  39049. lastKnownAction =
  39050. knownActionsForClip[ knownActionsForClip.length - 1 ],
  39051. byClipCacheIndex = action._byClipCacheIndex;
  39052. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  39053. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  39054. knownActionsForClip.pop();
  39055. action._byClipCacheIndex = null;
  39056. const actionByRoot = actionsForClip.actionByRoot,
  39057. rootUuid = ( action._localRoot || this._root ).uuid;
  39058. delete actionByRoot[ rootUuid ];
  39059. if ( knownActionsForClip.length === 0 ) {
  39060. delete actionsByClip[ clipUuid ];
  39061. }
  39062. this._removeInactiveBindingsForAction( action );
  39063. }
  39064. _removeInactiveBindingsForAction( action ) {
  39065. const bindings = action._propertyBindings;
  39066. for ( let i = 0, n = bindings.length; i !== n; ++ i ) {
  39067. const binding = bindings[ i ];
  39068. if ( -- binding.referenceCount === 0 ) {
  39069. this._removeInactiveBinding( binding );
  39070. }
  39071. }
  39072. }
  39073. _lendAction( action ) {
  39074. // [ active actions | inactive actions ]
  39075. // [ active actions >| inactive actions ]
  39076. // s a
  39077. // <-swap->
  39078. // a s
  39079. const actions = this._actions,
  39080. prevIndex = action._cacheIndex,
  39081. lastActiveIndex = this._nActiveActions ++,
  39082. firstInactiveAction = actions[ lastActiveIndex ];
  39083. action._cacheIndex = lastActiveIndex;
  39084. actions[ lastActiveIndex ] = action;
  39085. firstInactiveAction._cacheIndex = prevIndex;
  39086. actions[ prevIndex ] = firstInactiveAction;
  39087. }
  39088. _takeBackAction( action ) {
  39089. // [ active actions | inactive actions ]
  39090. // [ active actions |< inactive actions ]
  39091. // a s
  39092. // <-swap->
  39093. // s a
  39094. const actions = this._actions,
  39095. prevIndex = action._cacheIndex,
  39096. firstInactiveIndex = -- this._nActiveActions,
  39097. lastActiveAction = actions[ firstInactiveIndex ];
  39098. action._cacheIndex = firstInactiveIndex;
  39099. actions[ firstInactiveIndex ] = action;
  39100. lastActiveAction._cacheIndex = prevIndex;
  39101. actions[ prevIndex ] = lastActiveAction;
  39102. }
  39103. // Memory management for PropertyMixer objects
  39104. _addInactiveBinding( binding, rootUuid, trackName ) {
  39105. const bindingsByRoot = this._bindingsByRootAndName,
  39106. bindings = this._bindings;
  39107. let bindingByName = bindingsByRoot[ rootUuid ];
  39108. if ( bindingByName === undefined ) {
  39109. bindingByName = {};
  39110. bindingsByRoot[ rootUuid ] = bindingByName;
  39111. }
  39112. bindingByName[ trackName ] = binding;
  39113. binding._cacheIndex = bindings.length;
  39114. bindings.push( binding );
  39115. }
  39116. _removeInactiveBinding( binding ) {
  39117. const bindings = this._bindings,
  39118. propBinding = binding.binding,
  39119. rootUuid = propBinding.rootNode.uuid,
  39120. trackName = propBinding.path,
  39121. bindingsByRoot = this._bindingsByRootAndName,
  39122. bindingByName = bindingsByRoot[ rootUuid ],
  39123. lastInactiveBinding = bindings[ bindings.length - 1 ],
  39124. cacheIndex = binding._cacheIndex;
  39125. lastInactiveBinding._cacheIndex = cacheIndex;
  39126. bindings[ cacheIndex ] = lastInactiveBinding;
  39127. bindings.pop();
  39128. delete bindingByName[ trackName ];
  39129. if ( Object.keys( bindingByName ).length === 0 ) {
  39130. delete bindingsByRoot[ rootUuid ];
  39131. }
  39132. }
  39133. _lendBinding( binding ) {
  39134. const bindings = this._bindings,
  39135. prevIndex = binding._cacheIndex,
  39136. lastActiveIndex = this._nActiveBindings ++,
  39137. firstInactiveBinding = bindings[ lastActiveIndex ];
  39138. binding._cacheIndex = lastActiveIndex;
  39139. bindings[ lastActiveIndex ] = binding;
  39140. firstInactiveBinding._cacheIndex = prevIndex;
  39141. bindings[ prevIndex ] = firstInactiveBinding;
  39142. }
  39143. _takeBackBinding( binding ) {
  39144. const bindings = this._bindings,
  39145. prevIndex = binding._cacheIndex,
  39146. firstInactiveIndex = -- this._nActiveBindings,
  39147. lastActiveBinding = bindings[ firstInactiveIndex ];
  39148. binding._cacheIndex = firstInactiveIndex;
  39149. bindings[ firstInactiveIndex ] = binding;
  39150. lastActiveBinding._cacheIndex = prevIndex;
  39151. bindings[ prevIndex ] = lastActiveBinding;
  39152. }
  39153. // Memory management of Interpolants for weight and time scale
  39154. _lendControlInterpolant() {
  39155. const interpolants = this._controlInterpolants,
  39156. lastActiveIndex = this._nActiveControlInterpolants ++;
  39157. let interpolant = interpolants[ lastActiveIndex ];
  39158. if ( interpolant === undefined ) {
  39159. interpolant = new LinearInterpolant(
  39160. new Float32Array( 2 ), new Float32Array( 2 ),
  39161. 1, _controlInterpolantsResultBuffer );
  39162. interpolant.__cacheIndex = lastActiveIndex;
  39163. interpolants[ lastActiveIndex ] = interpolant;
  39164. }
  39165. return interpolant;
  39166. }
  39167. _takeBackControlInterpolant( interpolant ) {
  39168. const interpolants = this._controlInterpolants,
  39169. prevIndex = interpolant.__cacheIndex,
  39170. firstInactiveIndex = -- this._nActiveControlInterpolants,
  39171. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  39172. interpolant.__cacheIndex = firstInactiveIndex;
  39173. interpolants[ firstInactiveIndex ] = interpolant;
  39174. lastActiveInterpolant.__cacheIndex = prevIndex;
  39175. interpolants[ prevIndex ] = lastActiveInterpolant;
  39176. }
  39177. /**
  39178. * Returns an instance of {@link AnimationAction} for the passed clip.
  39179. *
  39180. * If an action fitting the clip and root parameters doesn't yet exist, it
  39181. * will be created by this method. Calling this method several times with the
  39182. * same clip and root parameters always returns the same action.
  39183. *
  39184. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39185. * @param {Object3D} [optionalRoot] - An alternative root object.
  39186. * @param {(NormalAnimationBlendMode|AdditiveAnimationBlendMode)} [blendMode] - The blend mode.
  39187. * @return {?AnimationAction} The animation action.
  39188. */
  39189. clipAction( clip, optionalRoot, blendMode ) {
  39190. const root = optionalRoot || this._root,
  39191. rootUuid = root.uuid;
  39192. let clipObject = typeof clip === 'string' ? AnimationClip.findByName( root, clip ) : clip;
  39193. const clipUuid = clipObject !== null ? clipObject.uuid : clip;
  39194. const actionsForClip = this._actionsByClip[ clipUuid ];
  39195. let prototypeAction = null;
  39196. if ( blendMode === undefined ) {
  39197. if ( clipObject !== null ) {
  39198. blendMode = clipObject.blendMode;
  39199. } else {
  39200. blendMode = NormalAnimationBlendMode;
  39201. }
  39202. }
  39203. if ( actionsForClip !== undefined ) {
  39204. const existingAction = actionsForClip.actionByRoot[ rootUuid ];
  39205. if ( existingAction !== undefined && existingAction.blendMode === blendMode ) {
  39206. return existingAction;
  39207. }
  39208. // we know the clip, so we don't have to parse all
  39209. // the bindings again but can just copy
  39210. prototypeAction = actionsForClip.knownActions[ 0 ];
  39211. // also, take the clip from the prototype action
  39212. if ( clipObject === null )
  39213. clipObject = prototypeAction._clip;
  39214. }
  39215. // clip must be known when specified via string
  39216. if ( clipObject === null ) return null;
  39217. // allocate all resources required to run it
  39218. const newAction = new AnimationAction( this, clipObject, optionalRoot, blendMode );
  39219. this._bindAction( newAction, prototypeAction );
  39220. // and make the action known to the memory manager
  39221. this._addInactiveAction( newAction, clipUuid, rootUuid );
  39222. return newAction;
  39223. }
  39224. /**
  39225. * Returns an existing animation action for the passed clip.
  39226. *
  39227. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39228. * @param {Object3D} [optionalRoot] - An alternative root object.
  39229. * @return {?AnimationAction} The animation action. Returns `null` if no action was found.
  39230. */
  39231. existingAction( clip, optionalRoot ) {
  39232. const root = optionalRoot || this._root,
  39233. rootUuid = root.uuid,
  39234. clipObject = typeof clip === 'string' ?
  39235. AnimationClip.findByName( root, clip ) : clip,
  39236. clipUuid = clipObject ? clipObject.uuid : clip,
  39237. actionsForClip = this._actionsByClip[ clipUuid ];
  39238. if ( actionsForClip !== undefined ) {
  39239. return actionsForClip.actionByRoot[ rootUuid ] || null;
  39240. }
  39241. return null;
  39242. }
  39243. /**
  39244. * Deactivates all previously scheduled actions on this mixer.
  39245. *
  39246. * @return {AnimationMixer} A reference to this animation mixer.
  39247. */
  39248. stopAllAction() {
  39249. const actions = this._actions,
  39250. nActions = this._nActiveActions;
  39251. for ( let i = nActions - 1; i >= 0; -- i ) {
  39252. actions[ i ].stop();
  39253. }
  39254. return this;
  39255. }
  39256. /**
  39257. * Advances the global mixer time and updates the animation.
  39258. *
  39259. * This is usually done in the render loop by passing the delta
  39260. * time from {@link Clock} or {@link Timer}.
  39261. *
  39262. * @param {number} deltaTime - The delta time in seconds.
  39263. * @return {AnimationMixer} A reference to this animation mixer.
  39264. */
  39265. update( deltaTime ) {
  39266. deltaTime *= this.timeScale;
  39267. const actions = this._actions,
  39268. nActions = this._nActiveActions,
  39269. time = this.time += deltaTime,
  39270. timeDirection = Math.sign( deltaTime ),
  39271. accuIndex = this._accuIndex ^= 1;
  39272. // run active actions
  39273. for ( let i = 0; i !== nActions; ++ i ) {
  39274. const action = actions[ i ];
  39275. action._update( time, deltaTime, timeDirection, accuIndex );
  39276. }
  39277. // update scene graph
  39278. const bindings = this._bindings,
  39279. nBindings = this._nActiveBindings;
  39280. for ( let i = 0; i !== nBindings; ++ i ) {
  39281. bindings[ i ].apply( accuIndex );
  39282. }
  39283. return this;
  39284. }
  39285. /**
  39286. * Sets the global mixer to a specific time and updates the animation accordingly.
  39287. *
  39288. * This is useful when you need to jump to an exact time in an animation. The
  39289. * input parameter will be scaled by {@link AnimationMixer#timeScale}
  39290. *
  39291. * @param {number} time - The time to set in seconds.
  39292. * @return {AnimationMixer} A reference to this animation mixer.
  39293. */
  39294. setTime( time ) {
  39295. this.time = 0; // Zero out time attribute for AnimationMixer object;
  39296. for ( let i = 0; i < this._actions.length; i ++ ) {
  39297. this._actions[ i ].time = 0; // Zero out time attribute for all associated AnimationAction objects.
  39298. }
  39299. return this.update( time ); // Update used to set exact time. Returns "this" AnimationMixer object.
  39300. }
  39301. /**
  39302. * Returns this mixer's root object.
  39303. *
  39304. * @return {Object3D} The mixer's root object.
  39305. */
  39306. getRoot() {
  39307. return this._root;
  39308. }
  39309. /**
  39310. * Deallocates all memory resources for a clip. Before using this method make
  39311. * sure to call {@link AnimationAction#stop} for all related actions.
  39312. *
  39313. * @param {AnimationClip} clip - The clip to uncache.
  39314. */
  39315. uncacheClip( clip ) {
  39316. const actions = this._actions,
  39317. clipUuid = clip.uuid,
  39318. actionsByClip = this._actionsByClip,
  39319. actionsForClip = actionsByClip[ clipUuid ];
  39320. if ( actionsForClip !== undefined ) {
  39321. // note: just calling _removeInactiveAction would mess up the
  39322. // iteration state and also require updating the state we can
  39323. // just throw away
  39324. const actionsToRemove = actionsForClip.knownActions;
  39325. for ( let i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  39326. const action = actionsToRemove[ i ];
  39327. this._deactivateAction( action );
  39328. const cacheIndex = action._cacheIndex,
  39329. lastInactiveAction = actions[ actions.length - 1 ];
  39330. action._cacheIndex = null;
  39331. action._byClipCacheIndex = null;
  39332. lastInactiveAction._cacheIndex = cacheIndex;
  39333. actions[ cacheIndex ] = lastInactiveAction;
  39334. actions.pop();
  39335. this._removeInactiveBindingsForAction( action );
  39336. }
  39337. delete actionsByClip[ clipUuid ];
  39338. }
  39339. }
  39340. /**
  39341. * Deallocates all memory resources for a root object. Before using this
  39342. * method make sure to call {@link AnimationAction#stop} for all related
  39343. * actions or alternatively {@link AnimationMixer#stopAllAction} when the
  39344. * mixer operates on a single root.
  39345. *
  39346. * @param {Object3D} root - The root object to uncache.
  39347. */
  39348. uncacheRoot( root ) {
  39349. const rootUuid = root.uuid,
  39350. actionsByClip = this._actionsByClip;
  39351. for ( const clipUuid in actionsByClip ) {
  39352. const actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  39353. action = actionByRoot[ rootUuid ];
  39354. if ( action !== undefined ) {
  39355. this._deactivateAction( action );
  39356. this._removeInactiveAction( action );
  39357. }
  39358. }
  39359. const bindingsByRoot = this._bindingsByRootAndName,
  39360. bindingByName = bindingsByRoot[ rootUuid ];
  39361. if ( bindingByName !== undefined ) {
  39362. for ( const trackName in bindingByName ) {
  39363. const binding = bindingByName[ trackName ];
  39364. binding.restoreOriginalState();
  39365. this._removeInactiveBinding( binding );
  39366. }
  39367. }
  39368. }
  39369. /**
  39370. * Deallocates all memory resources for an action. The action is identified by the
  39371. * given clip and an optional root object. Before using this method make
  39372. * sure to call {@link AnimationAction#stop} to deactivate the action.
  39373. *
  39374. * @param {AnimationClip|string} clip - An animation clip or alternatively the name of the animation clip.
  39375. * @param {Object3D} [optionalRoot] - An alternative root object.
  39376. */
  39377. uncacheAction( clip, optionalRoot ) {
  39378. const action = this.existingAction( clip, optionalRoot );
  39379. if ( action !== null ) {
  39380. this._deactivateAction( action );
  39381. this._removeInactiveAction( action );
  39382. }
  39383. }
  39384. }
  39385. /**
  39386. * Represents a 3D render target.
  39387. *
  39388. * @augments RenderTarget
  39389. */
  39390. class RenderTarget3D extends RenderTarget {
  39391. /**
  39392. * Constructs a new 3D render target.
  39393. *
  39394. * @param {number} [width=1] - The width of the render target.
  39395. * @param {number} [height=1] - The height of the render target.
  39396. * @param {number} [depth=1] - The height of the render target.
  39397. * @param {RenderTarget~Options} [options] - The configuration object.
  39398. */
  39399. constructor( width = 1, height = 1, depth = 1, options = {} ) {
  39400. super( width, height, options );
  39401. /**
  39402. * This flag can be used for type testing.
  39403. *
  39404. * @type {boolean}
  39405. * @readonly
  39406. * @default true
  39407. */
  39408. this.isRenderTarget3D = true;
  39409. this.depth = depth;
  39410. /**
  39411. * Overwritten with a different texture type.
  39412. *
  39413. * @type {Data3DTexture}
  39414. */
  39415. this.texture = new Data3DTexture( null, width, height, depth );
  39416. this._setTextureOptions( options );
  39417. this.texture.isRenderTargetTexture = true;
  39418. }
  39419. }
  39420. /**
  39421. * Represents a uniform which is a global shader variable. They are passed to shader programs.
  39422. *
  39423. * When declaring a uniform of a {@link ShaderMaterial}, it is declared by value or by object.
  39424. * ```js
  39425. * uniforms: {
  39426. * time: { value: 1.0 },
  39427. * resolution: new Uniform( new Vector2() )
  39428. * };
  39429. * ```
  39430. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39431. * in {@link WebGLRenderer}.
  39432. */
  39433. class Uniform {
  39434. /**
  39435. * Constructs a new uniform.
  39436. *
  39437. * @param {any} value - The uniform value.
  39438. */
  39439. constructor( value ) {
  39440. /**
  39441. * The uniform value.
  39442. *
  39443. * @type {any}
  39444. */
  39445. this.value = value;
  39446. }
  39447. /**
  39448. * Returns a new uniform with copied values from this instance.
  39449. * If the value has a `clone()` method, the value is cloned as well.
  39450. *
  39451. * @return {Uniform} A clone of this instance.
  39452. */
  39453. clone() {
  39454. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  39455. }
  39456. }
  39457. let _id$1 = 0;
  39458. /**
  39459. * A class for managing multiple uniforms in a single group. The renderer will process
  39460. * such a definition as a single UBO.
  39461. *
  39462. * Since this class can only be used in context of {@link ShaderMaterial}, it is only supported
  39463. * in {@link WebGLRenderer}.
  39464. *
  39465. * @augments EventDispatcher
  39466. */
  39467. class UniformsGroup extends EventDispatcher {
  39468. /**
  39469. * Constructs a new uniforms group.
  39470. */
  39471. constructor() {
  39472. super();
  39473. /**
  39474. * This flag can be used for type testing.
  39475. *
  39476. * @type {boolean}
  39477. * @readonly
  39478. * @default true
  39479. */
  39480. this.isUniformsGroup = true;
  39481. /**
  39482. * The ID of the 3D object.
  39483. *
  39484. * @name UniformsGroup#id
  39485. * @type {number}
  39486. * @readonly
  39487. */
  39488. Object.defineProperty( this, 'id', { value: _id$1 ++ } );
  39489. /**
  39490. * The name of the uniforms group.
  39491. *
  39492. * @type {string}
  39493. */
  39494. this.name = '';
  39495. /**
  39496. * The buffer usage.
  39497. *
  39498. * @type {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)}
  39499. * @default StaticDrawUsage
  39500. */
  39501. this.usage = StaticDrawUsage;
  39502. /**
  39503. * An array holding the uniforms.
  39504. *
  39505. * @type {Array<Uniform>}
  39506. */
  39507. this.uniforms = [];
  39508. }
  39509. /**
  39510. * Adds the given uniform to this uniforms group.
  39511. *
  39512. * @param {Uniform} uniform - The uniform to add.
  39513. * @return {UniformsGroup} A reference to this uniforms group.
  39514. */
  39515. add( uniform ) {
  39516. this.uniforms.push( uniform );
  39517. return this;
  39518. }
  39519. /**
  39520. * Removes the given uniform from this uniforms group.
  39521. *
  39522. * @param {Uniform} uniform - The uniform to remove.
  39523. * @return {UniformsGroup} A reference to this uniforms group.
  39524. */
  39525. remove( uniform ) {
  39526. const index = this.uniforms.indexOf( uniform );
  39527. if ( index !== -1 ) this.uniforms.splice( index, 1 );
  39528. return this;
  39529. }
  39530. /**
  39531. * Sets the name of this uniforms group.
  39532. *
  39533. * @param {string} name - The name to set.
  39534. * @return {UniformsGroup} A reference to this uniforms group.
  39535. */
  39536. setName( name ) {
  39537. this.name = name;
  39538. return this;
  39539. }
  39540. /**
  39541. * Sets the usage of this uniforms group.
  39542. *
  39543. * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set.
  39544. * @return {UniformsGroup} A reference to this uniforms group.
  39545. */
  39546. setUsage( value ) {
  39547. this.usage = value;
  39548. return this;
  39549. }
  39550. /**
  39551. * Frees the GPU-related resources allocated by this instance. Call this
  39552. * method whenever this instance is no longer used in your app.
  39553. *
  39554. * @fires Texture#dispose
  39555. */
  39556. dispose() {
  39557. this.dispatchEvent( { type: 'dispose' } );
  39558. }
  39559. /**
  39560. * Copies the values of the given uniforms group to this instance.
  39561. *
  39562. * @param {UniformsGroup} source - The uniforms group to copy.
  39563. * @return {UniformsGroup} A reference to this uniforms group.
  39564. */
  39565. copy( source ) {
  39566. this.name = source.name;
  39567. this.usage = source.usage;
  39568. const uniformsSource = source.uniforms;
  39569. this.uniforms.length = 0;
  39570. for ( let i = 0, l = uniformsSource.length; i < l; i ++ ) {
  39571. const uniforms = Array.isArray( uniformsSource[ i ] ) ? uniformsSource[ i ] : [ uniformsSource[ i ] ];
  39572. for ( let j = 0; j < uniforms.length; j ++ ) {
  39573. this.uniforms.push( uniforms[ j ].clone() );
  39574. }
  39575. }
  39576. return this;
  39577. }
  39578. /**
  39579. * Returns a new uniforms group with copied values from this instance.
  39580. *
  39581. * @return {UniformsGroup} A clone of this instance.
  39582. */
  39583. clone() {
  39584. return new this.constructor().copy( this );
  39585. }
  39586. }
  39587. /**
  39588. * An instanced version of an interleaved buffer.
  39589. *
  39590. * @augments InterleavedBuffer
  39591. */
  39592. class InstancedInterleavedBuffer extends InterleavedBuffer {
  39593. /**
  39594. * Constructs a new instanced interleaved buffer.
  39595. *
  39596. * @param {TypedArray} array - A typed array with a shared buffer storing attribute data.
  39597. * @param {number} stride - The number of typed-array elements per vertex.
  39598. * @param {number} [meshPerAttribute=1] - Defines how often a value of this interleaved buffer should be repeated.
  39599. */
  39600. constructor( array, stride, meshPerAttribute = 1 ) {
  39601. super( array, stride );
  39602. /**
  39603. * This flag can be used for type testing.
  39604. *
  39605. * @type {boolean}
  39606. * @readonly
  39607. * @default true
  39608. */
  39609. this.isInstancedInterleavedBuffer = true;
  39610. /**
  39611. * Defines how often a value of this buffer attribute should be repeated,
  39612. * see {@link InstancedBufferAttribute#meshPerAttribute}.
  39613. *
  39614. * @type {number}
  39615. * @default 1
  39616. */
  39617. this.meshPerAttribute = meshPerAttribute;
  39618. }
  39619. copy( source ) {
  39620. super.copy( source );
  39621. this.meshPerAttribute = source.meshPerAttribute;
  39622. return this;
  39623. }
  39624. clone( data ) {
  39625. const ib = super.clone( data );
  39626. ib.meshPerAttribute = this.meshPerAttribute;
  39627. return ib;
  39628. }
  39629. toJSON( data ) {
  39630. const json = super.toJSON( data );
  39631. json.isInstancedInterleavedBuffer = true;
  39632. json.meshPerAttribute = this.meshPerAttribute;
  39633. return json;
  39634. }
  39635. }
  39636. /**
  39637. * An alternative version of a buffer attribute with more control over the VBO.
  39638. *
  39639. * The renderer does not construct a VBO for this kind of attribute. Instead, it uses
  39640. * whatever VBO is passed in constructor and can later be altered via the `buffer` property.
  39641. *
  39642. * The most common use case for this class is when some kind of GPGPU calculation interferes
  39643. * or even produces the VBOs in question.
  39644. *
  39645. * Notice that this class can only be used with {@link WebGLRenderer}.
  39646. */
  39647. class GLBufferAttribute {
  39648. /**
  39649. * Constructs a new GL buffer attribute.
  39650. *
  39651. * @param {WebGLBuffer} buffer - The native WebGL buffer.
  39652. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39653. * @param {number} itemSize - The item size.
  39654. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39655. * @param {number} count - The expected number of vertices in VBO.
  39656. * @param {boolean} [normalized=false] - Whether the data are normalized or not.
  39657. */
  39658. constructor( buffer, type, itemSize, elementSize, count, normalized = false ) {
  39659. /**
  39660. * This flag can be used for type testing.
  39661. *
  39662. * @type {boolean}
  39663. * @readonly
  39664. * @default true
  39665. */
  39666. this.isGLBufferAttribute = true;
  39667. /**
  39668. * The name of the buffer attribute.
  39669. *
  39670. * @type {string}
  39671. */
  39672. this.name = '';
  39673. /**
  39674. * The native WebGL buffer.
  39675. *
  39676. * @type {WebGLBuffer}
  39677. */
  39678. this.buffer = buffer;
  39679. /**
  39680. * The native data type.
  39681. *
  39682. * @type {number}
  39683. */
  39684. this.type = type;
  39685. /**
  39686. * The item size, see {@link BufferAttribute#itemSize}.
  39687. *
  39688. * @type {number}
  39689. */
  39690. this.itemSize = itemSize;
  39691. /**
  39692. * The corresponding size (in bytes) for the given `type` parameter.
  39693. *
  39694. * @type {number}
  39695. */
  39696. this.elementSize = elementSize;
  39697. /**
  39698. * The expected number of vertices in VBO.
  39699. *
  39700. * @type {number}
  39701. */
  39702. this.count = count;
  39703. /**
  39704. * Applies to integer data only. Indicates how the underlying data in the buffer maps to
  39705. * the values in the GLSL code. For instance, if `buffer` contains data of `gl.UNSIGNED_SHORT`,
  39706. * and `normalized` is `true`, the values `0 - +65535` in the buffer data will be mapped to
  39707. * `0.0f - +1.0f` in the GLSL attribute. If `normalized` is `false`, the values will be converted
  39708. * to floats unmodified, i.e. `65535` becomes `65535.0f`.
  39709. *
  39710. * @type {boolean}
  39711. */
  39712. this.normalized = normalized;
  39713. /**
  39714. * A version number, incremented every time the `needsUpdate` is set to `true`.
  39715. *
  39716. * @type {number}
  39717. */
  39718. this.version = 0;
  39719. }
  39720. /**
  39721. * Flag to indicate that this attribute has changed and should be re-sent to
  39722. * the GPU. Set this to `true` when you modify the value of the array.
  39723. *
  39724. * @type {number}
  39725. * @default false
  39726. * @param {boolean} value
  39727. */
  39728. set needsUpdate( value ) {
  39729. if ( value === true ) this.version ++;
  39730. }
  39731. /**
  39732. * Sets the given native WebGL buffer.
  39733. *
  39734. * @param {WebGLBuffer} buffer - The buffer to set.
  39735. * @return {BufferAttribute} A reference to this instance.
  39736. */
  39737. setBuffer( buffer ) {
  39738. this.buffer = buffer;
  39739. return this;
  39740. }
  39741. /**
  39742. * Sets the given native data type and element size.
  39743. *
  39744. * @param {number} type - The native data type (e.g. `gl.FLOAT`).
  39745. * @param {number} elementSize - The corresponding size (in bytes) for the given `type` parameter.
  39746. * @return {BufferAttribute} A reference to this instance.
  39747. */
  39748. setType( type, elementSize ) {
  39749. this.type = type;
  39750. this.elementSize = elementSize;
  39751. return this;
  39752. }
  39753. /**
  39754. * Sets the item size.
  39755. *
  39756. * @param {number} itemSize - The item size.
  39757. * @return {BufferAttribute} A reference to this instance.
  39758. */
  39759. setItemSize( itemSize ) {
  39760. this.itemSize = itemSize;
  39761. return this;
  39762. }
  39763. /**
  39764. * Sets the count (the expected number of vertices in VBO).
  39765. *
  39766. * @param {number} count - The count.
  39767. * @return {BufferAttribute} A reference to this instance.
  39768. */
  39769. setCount( count ) {
  39770. this.count = count;
  39771. return this;
  39772. }
  39773. }
  39774. const _matrix = /*@__PURE__*/ new Matrix4();
  39775. /**
  39776. * This class is designed to assist with raycasting. Raycasting is used for
  39777. * mouse picking (working out what objects in the 3d space the mouse is over)
  39778. * amongst other things.
  39779. */
  39780. class Raycaster {
  39781. /**
  39782. * Constructs a new raycaster.
  39783. *
  39784. * @param {Vector3} origin - The origin vector where the ray casts from.
  39785. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39786. * @param {number} [near=0] - All results returned are further away than near. Near can't be negative.
  39787. * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near.
  39788. */
  39789. constructor( origin, direction, near = 0, far = Infinity ) {
  39790. /**
  39791. * The ray used for raycasting.
  39792. *
  39793. * @type {Ray}
  39794. */
  39795. this.ray = new Ray( origin, direction );
  39796. /**
  39797. * All results returned are further away than near. Near can't be negative.
  39798. *
  39799. * @type {number}
  39800. * @default 0
  39801. */
  39802. this.near = near;
  39803. /**
  39804. * All results returned are further away than near. Near can't be negative.
  39805. *
  39806. * @type {number}
  39807. * @default Infinity
  39808. */
  39809. this.far = far;
  39810. /**
  39811. * The camera to use when raycasting against view-dependent objects such as
  39812. * billboarded objects like sprites. This field can be set manually or
  39813. * is set when calling `setFromCamera()`.
  39814. *
  39815. * @type {?Camera}
  39816. * @default null
  39817. */
  39818. this.camera = null;
  39819. /**
  39820. * Allows to selectively ignore 3D objects when performing intersection tests.
  39821. * The following code example ensures that only 3D objects on layer `1` will be
  39822. * honored by raycaster.
  39823. * ```js
  39824. * raycaster.layers.set( 1 );
  39825. * object.layers.enable( 1 );
  39826. * ```
  39827. *
  39828. * @type {Layers}
  39829. */
  39830. this.layers = new Layers();
  39831. /**
  39832. * A parameter object that configures the raycasting. It has the structure:
  39833. *
  39834. * ```
  39835. * {
  39836. * Mesh: {},
  39837. * Line: { threshold: 1 },
  39838. * LOD: {},
  39839. * Points: { threshold: 1 },
  39840. * Sprite: {}
  39841. * }
  39842. * ```
  39843. * Where `threshold` is the precision of the raycaster when intersecting objects, in world units.
  39844. *
  39845. * @type {Object}
  39846. */
  39847. this.params = {
  39848. Mesh: {},
  39849. Line: { threshold: 1 },
  39850. LOD: {},
  39851. Points: { threshold: 1 },
  39852. Sprite: {}
  39853. };
  39854. }
  39855. /**
  39856. * Updates the ray with a new origin and direction by copying the values from the arguments.
  39857. *
  39858. * @param {Vector3} origin - The origin vector where the ray casts from.
  39859. * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray.
  39860. */
  39861. set( origin, direction ) {
  39862. // direction is assumed to be normalized (for accurate distance calculations)
  39863. this.ray.set( origin, direction );
  39864. }
  39865. /**
  39866. * Uses the given coordinates and camera to compute a new origin and direction for the internal ray.
  39867. *
  39868. * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC).
  39869. * X and Y components should be between `-1` and `1`.
  39870. * @param {Camera} camera - The camera from which the ray should originate.
  39871. */
  39872. setFromCamera( coords, camera ) {
  39873. if ( camera.isPerspectiveCamera ) {
  39874. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  39875. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  39876. this.camera = camera;
  39877. } else if ( camera.isOrthographicCamera ) {
  39878. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  39879. this.ray.direction.set( 0, 0, -1 ).transformDirection( camera.matrixWorld );
  39880. this.camera = camera;
  39881. } else {
  39882. error( 'Raycaster: Unsupported camera type: ' + camera.type );
  39883. }
  39884. }
  39885. /**
  39886. * Uses the given WebXR controller to compute a new origin and direction for the internal ray.
  39887. *
  39888. * @param {WebXRController} controller - The controller to copy the position and direction from.
  39889. * @return {Raycaster} A reference to this raycaster.
  39890. */
  39891. setFromXRController( controller ) {
  39892. _matrix.identity().extractRotation( controller.matrixWorld );
  39893. this.ray.origin.setFromMatrixPosition( controller.matrixWorld );
  39894. this.ray.direction.set( 0, 0, -1 ).applyMatrix4( _matrix );
  39895. return this;
  39896. }
  39897. /**
  39898. * The intersection point of a raycaster intersection test.
  39899. * @typedef {Object} Raycaster~Intersection
  39900. * @property {number} distance - The distance from the ray's origin to the intersection point.
  39901. * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the
  39902. * intersection to the nearest point on the ray. For other objects it will be `undefined`.
  39903. * @property {Vector3} point - The intersection point, in world coordinates.
  39904. * @property {Object} face - The face that has been intersected.
  39905. * @property {number} faceIndex - The face index.
  39906. * @property {Object3D} object - The 3D object that has been intersected.
  39907. * @property {Vector2} uv - U,V coordinates at point of intersection.
  39908. * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection.
  39909. * @property {Vector3} normal - Interpolated normal vector at point of intersection.
  39910. * @property {number} instanceId - The index number of the instance where the ray
  39911. * intersects the {@link InstancedMesh}.
  39912. */
  39913. /**
  39914. * Checks all intersection between the ray and the object with or without the
  39915. * descendants. Intersections are returned sorted by distance, closest first.
  39916. *
  39917. * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when
  39918. * evaluating whether the ray intersects the object or not. This allows meshes to respond
  39919. * differently to ray casting than lines or points.
  39920. *
  39921. * Note that for meshes, faces must be pointed towards the origin of the ray in order
  39922. * to be detected; intersections of the ray passing through the back of a face will not
  39923. * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side}
  39924. * to `THREE.DoubleSide`.
  39925. *
  39926. * @param {Object3D} object - The 3D object to check for intersection with the ray.
  39927. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39928. * Otherwise it only checks intersection with the object.
  39929. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39930. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39931. */
  39932. intersectObject( object, recursive = true, intersects = [] ) {
  39933. intersect( object, this, intersects, recursive );
  39934. intersects.sort( ascSort );
  39935. return intersects;
  39936. }
  39937. /**
  39938. * Checks all intersection between the ray and the objects with or without
  39939. * the descendants. Intersections are returned sorted by distance, closest first.
  39940. *
  39941. * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray.
  39942. * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants.
  39943. * Otherwise it only checks intersection with the object.
  39944. * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method.
  39945. * @return {Array<Raycaster~Intersection>} An array holding the intersection points.
  39946. */
  39947. intersectObjects( objects, recursive = true, intersects = [] ) {
  39948. for ( let i = 0, l = objects.length; i < l; i ++ ) {
  39949. intersect( objects[ i ], this, intersects, recursive );
  39950. }
  39951. intersects.sort( ascSort );
  39952. return intersects;
  39953. }
  39954. }
  39955. function ascSort( a, b ) {
  39956. return a.distance - b.distance;
  39957. }
  39958. function intersect( object, raycaster, intersects, recursive ) {
  39959. let propagate = true;
  39960. if ( object.layers.test( raycaster.layers ) ) {
  39961. const result = object.raycast( raycaster, intersects );
  39962. if ( result === false ) propagate = false;
  39963. }
  39964. if ( propagate === true && recursive === true ) {
  39965. const children = object.children;
  39966. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39967. intersect( children[ i ], raycaster, intersects, true );
  39968. }
  39969. }
  39970. }
  39971. /**
  39972. * This class is an alternative to {@link Clock} with a different API design and behavior.
  39973. * The goal is to avoid the conceptual flaws that became apparent in `Clock` over time.
  39974. *
  39975. * - `Timer` has an `update()` method that updates its internal state. That makes it possible to
  39976. * call `getDelta()` and `getElapsed()` multiple times per simulation step without getting different values.
  39977. * - The class can make use of the Page Visibility API to avoid large time delta values when the app
  39978. * is inactive (e.g. tab switched or browser hidden).
  39979. *
  39980. * ```js
  39981. * const timer = new Timer();
  39982. * timer.connect( document ); // use Page Visibility API
  39983. * ```
  39984. */
  39985. class Timer {
  39986. /**
  39987. * Constructs a new timer.
  39988. */
  39989. constructor() {
  39990. this._previousTime = 0;
  39991. this._currentTime = 0;
  39992. this._startTime = performance.now();
  39993. this._delta = 0;
  39994. this._elapsed = 0;
  39995. this._timescale = 1;
  39996. this._document = null;
  39997. this._pageVisibilityHandler = null;
  39998. }
  39999. /**
  40000. * Connect the timer to the given document.Calling this method is not mandatory to
  40001. * use the timer but enables the usage of the Page Visibility API to avoid large time
  40002. * delta values.
  40003. *
  40004. * @param {Document} document - The document.
  40005. */
  40006. connect( document ) {
  40007. this._document = document;
  40008. // use Page Visibility API to avoid large time delta values
  40009. if ( document.hidden !== undefined ) {
  40010. this._pageVisibilityHandler = handleVisibilityChange.bind( this );
  40011. document.addEventListener( 'visibilitychange', this._pageVisibilityHandler, false );
  40012. }
  40013. }
  40014. /**
  40015. * Disconnects the timer from the DOM and also disables the usage of the Page Visibility API.
  40016. */
  40017. disconnect() {
  40018. if ( this._pageVisibilityHandler !== null ) {
  40019. this._document.removeEventListener( 'visibilitychange', this._pageVisibilityHandler );
  40020. this._pageVisibilityHandler = null;
  40021. }
  40022. this._document = null;
  40023. }
  40024. /**
  40025. * Returns the time delta in seconds.
  40026. *
  40027. * @return {number} The time delta in second.
  40028. */
  40029. getDelta() {
  40030. return this._delta / 1000;
  40031. }
  40032. /**
  40033. * Returns the elapsed time in seconds.
  40034. *
  40035. * @return {number} The elapsed time in second.
  40036. */
  40037. getElapsed() {
  40038. return this._elapsed / 1000;
  40039. }
  40040. /**
  40041. * Returns the timescale.
  40042. *
  40043. * @return {number} The timescale.
  40044. */
  40045. getTimescale() {
  40046. return this._timescale;
  40047. }
  40048. /**
  40049. * Sets the given timescale which scale the time delta computation
  40050. * in `update()`.
  40051. *
  40052. * @param {number} timescale - The timescale to set.
  40053. * @return {Timer} A reference to this timer.
  40054. */
  40055. setTimescale( timescale ) {
  40056. this._timescale = timescale;
  40057. return this;
  40058. }
  40059. /**
  40060. * Resets the time computation for the current simulation step.
  40061. *
  40062. * @return {Timer} A reference to this timer.
  40063. */
  40064. reset() {
  40065. this._currentTime = performance.now() - this._startTime;
  40066. return this;
  40067. }
  40068. /**
  40069. * Can be used to free all internal resources. Usually called when
  40070. * the timer instance isn't required anymore.
  40071. */
  40072. dispose() {
  40073. this.disconnect();
  40074. }
  40075. /**
  40076. * Updates the internal state of the timer. This method should be called
  40077. * once per simulation step and before you perform queries against the timer
  40078. * (e.g. via `getDelta()`).
  40079. *
  40080. * @param {number} timestamp - The current time in milliseconds. Can be obtained
  40081. * from the `requestAnimationFrame` callback argument. If not provided, the current
  40082. * time will be determined with `performance.now`.
  40083. * @return {Timer} A reference to this timer.
  40084. */
  40085. update( timestamp ) {
  40086. if ( this._pageVisibilityHandler !== null && this._document.hidden === true ) {
  40087. this._delta = 0;
  40088. } else {
  40089. this._previousTime = this._currentTime;
  40090. this._currentTime = ( timestamp !== undefined ? timestamp : performance.now() ) - this._startTime;
  40091. this._delta = ( this._currentTime - this._previousTime ) * this._timescale;
  40092. this._elapsed += this._delta; // _elapsed is the accumulation of all previous deltas
  40093. }
  40094. return this;
  40095. }
  40096. }
  40097. function handleVisibilityChange() {
  40098. if ( this._document.hidden === false ) this.reset();
  40099. }
  40100. /**
  40101. * This class can be used to represent points in 3D space as
  40102. * [Spherical coordinates](https://en.wikipedia.org/wiki/Spherical_coordinate_system).
  40103. */
  40104. class Spherical {
  40105. /**
  40106. * Constructs a new spherical.
  40107. *
  40108. * @param {number} [radius=1] - The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40109. * @param {number} [phi=0] - The polar angle in radians from the y (up) axis.
  40110. * @param {number} [theta=0] - The equator/azimuthal angle in radians around the y (up) axis.
  40111. */
  40112. constructor( radius = 1, phi = 0, theta = 0 ) {
  40113. /**
  40114. * The radius, or the Euclidean distance (straight-line distance) from the point to the origin.
  40115. *
  40116. * @type {number}
  40117. * @default 1
  40118. */
  40119. this.radius = radius;
  40120. /**
  40121. * The polar angle in radians from the y (up) axis.
  40122. *
  40123. * @type {number}
  40124. * @default 0
  40125. */
  40126. this.phi = phi;
  40127. /**
  40128. * The equator/azimuthal angle in radians around the y (up) axis.
  40129. *
  40130. * @type {number}
  40131. * @default 0
  40132. */
  40133. this.theta = theta;
  40134. }
  40135. /**
  40136. * Sets the spherical components by copying the given values.
  40137. *
  40138. * @param {number} radius - The radius.
  40139. * @param {number} phi - The polar angle.
  40140. * @param {number} theta - The azimuthal angle.
  40141. * @return {Spherical} A reference to this spherical.
  40142. */
  40143. set( radius, phi, theta ) {
  40144. this.radius = radius;
  40145. this.phi = phi;
  40146. this.theta = theta;
  40147. return this;
  40148. }
  40149. /**
  40150. * Copies the values of the given spherical to this instance.
  40151. *
  40152. * @param {Spherical} other - The spherical to copy.
  40153. * @return {Spherical} A reference to this spherical.
  40154. */
  40155. copy( other ) {
  40156. this.radius = other.radius;
  40157. this.phi = other.phi;
  40158. this.theta = other.theta;
  40159. return this;
  40160. }
  40161. /**
  40162. * Restricts the polar angle [page:.phi phi] to be between `0.000001` and pi -
  40163. * `0.000001`.
  40164. *
  40165. * @return {Spherical} A reference to this spherical.
  40166. */
  40167. makeSafe() {
  40168. const EPS = 0.000001;
  40169. this.phi = clamp( this.phi, EPS, Math.PI - EPS );
  40170. return this;
  40171. }
  40172. /**
  40173. * Sets the spherical components from the given vector which is assumed to hold
  40174. * Cartesian coordinates.
  40175. *
  40176. * @param {Vector3} v - The vector to set.
  40177. * @return {Spherical} A reference to this spherical.
  40178. */
  40179. setFromVector3( v ) {
  40180. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40181. }
  40182. /**
  40183. * Sets the spherical components from the given Cartesian coordinates.
  40184. *
  40185. * @param {number} x - The x value.
  40186. * @param {number} y - The y value.
  40187. * @param {number} z - The z value.
  40188. * @return {Spherical} A reference to this spherical.
  40189. */
  40190. setFromCartesianCoords( x, y, z ) {
  40191. this.radius = Math.sqrt( x * x + y * y + z * z );
  40192. if ( this.radius === 0 ) {
  40193. this.theta = 0;
  40194. this.phi = 0;
  40195. } else {
  40196. this.theta = Math.atan2( x, z );
  40197. this.phi = Math.acos( clamp( y / this.radius, -1, 1 ) );
  40198. }
  40199. return this;
  40200. }
  40201. /**
  40202. * Returns a new spherical with copied values from this instance.
  40203. *
  40204. * @return {Spherical} A clone of this instance.
  40205. */
  40206. clone() {
  40207. return new this.constructor().copy( this );
  40208. }
  40209. }
  40210. /**
  40211. * This class can be used to represent points in 3D space as
  40212. * [Cylindrical coordinates](https://en.wikipedia.org/wiki/Cylindrical_coordinate_system).
  40213. */
  40214. class Cylindrical {
  40215. /**
  40216. * Constructs a new cylindrical.
  40217. *
  40218. * @param {number} [radius=1] - The distance from the origin to a point in the x-z plane.
  40219. * @param {number} [theta=0] - A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40220. * @param {number} [y=0] - The height above the x-z plane.
  40221. */
  40222. constructor( radius = 1, theta = 0, y = 0 ) {
  40223. /**
  40224. * The distance from the origin to a point in the x-z plane.
  40225. *
  40226. * @type {number}
  40227. * @default 1
  40228. */
  40229. this.radius = radius;
  40230. /**
  40231. * A counterclockwise angle in the x-z plane measured in radians from the positive z-axis.
  40232. *
  40233. * @type {number}
  40234. * @default 0
  40235. */
  40236. this.theta = theta;
  40237. /**
  40238. * The height above the x-z plane.
  40239. *
  40240. * @type {number}
  40241. * @default 0
  40242. */
  40243. this.y = y;
  40244. }
  40245. /**
  40246. * Sets the cylindrical components by copying the given values.
  40247. *
  40248. * @param {number} radius - The radius.
  40249. * @param {number} theta - The theta angle.
  40250. * @param {number} y - The height value.
  40251. * @return {Cylindrical} A reference to this cylindrical.
  40252. */
  40253. set( radius, theta, y ) {
  40254. this.radius = radius;
  40255. this.theta = theta;
  40256. this.y = y;
  40257. return this;
  40258. }
  40259. /**
  40260. * Copies the values of the given cylindrical to this instance.
  40261. *
  40262. * @param {Cylindrical} other - The cylindrical to copy.
  40263. * @return {Cylindrical} A reference to this cylindrical.
  40264. */
  40265. copy( other ) {
  40266. this.radius = other.radius;
  40267. this.theta = other.theta;
  40268. this.y = other.y;
  40269. return this;
  40270. }
  40271. /**
  40272. * Sets the cylindrical components from the given vector which is assumed to hold
  40273. * Cartesian coordinates.
  40274. *
  40275. * @param {Vector3} v - The vector to set.
  40276. * @return {Cylindrical} A reference to this cylindrical.
  40277. */
  40278. setFromVector3( v ) {
  40279. return this.setFromCartesianCoords( v.x, v.y, v.z );
  40280. }
  40281. /**
  40282. * Sets the cylindrical components from the given Cartesian coordinates.
  40283. *
  40284. * @param {number} x - The x value.
  40285. * @param {number} y - The x value.
  40286. * @param {number} z - The x value.
  40287. * @return {Cylindrical} A reference to this cylindrical.
  40288. */
  40289. setFromCartesianCoords( x, y, z ) {
  40290. this.radius = Math.sqrt( x * x + z * z );
  40291. this.theta = Math.atan2( x, z );
  40292. this.y = y;
  40293. return this;
  40294. }
  40295. /**
  40296. * Returns a new cylindrical with copied values from this instance.
  40297. *
  40298. * @return {Cylindrical} A clone of this instance.
  40299. */
  40300. clone() {
  40301. return new this.constructor().copy( this );
  40302. }
  40303. }
  40304. /**
  40305. * Represents a 2x2 matrix.
  40306. *
  40307. * A Note on Row-Major and Column-Major Ordering:
  40308. *
  40309. * The constructor and {@link Matrix2#set} method take arguments in
  40310. * [row-major](https://en.wikipedia.org/wiki/Row-_and_column-major_order#Column-major_order)
  40311. * order, while internally they are stored in the {@link Matrix2#elements} array in column-major order.
  40312. * This means that calling:
  40313. * ```js
  40314. * const m = new THREE.Matrix2();
  40315. * m.set( 11, 12,
  40316. * 21, 22 );
  40317. * ```
  40318. * will result in the elements array containing:
  40319. * ```js
  40320. * m.elements = [ 11, 21,
  40321. * 12, 22 ];
  40322. * ```
  40323. * and internally all calculations are performed using column-major ordering.
  40324. * However, as the actual ordering makes no difference mathematically and
  40325. * most people are used to thinking about matrices in row-major order, the
  40326. * three.js documentation shows matrices in row-major order. Just bear in
  40327. * mind that if you are reading the source code, you'll have to take the
  40328. * transpose of any matrices outlined here to make sense of the calculations.
  40329. */
  40330. class Matrix2 {
  40331. /**
  40332. * Constructs a new 2x2 matrix. The arguments are supposed to be
  40333. * in row-major order. If no arguments are provided, the constructor
  40334. * initializes the matrix as an identity matrix.
  40335. *
  40336. * @param {number} [n11] - 1-1 matrix element.
  40337. * @param {number} [n12] - 1-2 matrix element.
  40338. * @param {number} [n21] - 2-1 matrix element.
  40339. * @param {number} [n22] - 2-2 matrix element.
  40340. */
  40341. constructor( n11, n12, n21, n22 ) {
  40342. /**
  40343. * This flag can be used for type testing.
  40344. *
  40345. * @type {boolean}
  40346. * @readonly
  40347. * @default true
  40348. */
  40349. Matrix2.prototype.isMatrix2 = true;
  40350. /**
  40351. * A column-major list of matrix values.
  40352. *
  40353. * @type {Array<number>}
  40354. */
  40355. this.elements = [
  40356. 1, 0,
  40357. 0, 1,
  40358. ];
  40359. if ( n11 !== undefined ) {
  40360. this.set( n11, n12, n21, n22 );
  40361. }
  40362. }
  40363. /**
  40364. * Sets this matrix to the 2x2 identity matrix.
  40365. *
  40366. * @return {Matrix2} A reference to this matrix.
  40367. */
  40368. identity() {
  40369. this.set(
  40370. 1, 0,
  40371. 0, 1,
  40372. );
  40373. return this;
  40374. }
  40375. /**
  40376. * Sets the elements of the matrix from the given array.
  40377. *
  40378. * @param {Array<number>} array - The matrix elements in column-major order.
  40379. * @param {number} [offset=0] - Index of the first element in the array.
  40380. * @return {Matrix2} A reference to this matrix.
  40381. */
  40382. fromArray( array, offset = 0 ) {
  40383. for ( let i = 0; i < 4; i ++ ) {
  40384. this.elements[ i ] = array[ i + offset ];
  40385. }
  40386. return this;
  40387. }
  40388. /**
  40389. * Sets the elements of the matrix.The arguments are supposed to be
  40390. * in row-major order.
  40391. *
  40392. * @param {number} n11 - 1-1 matrix element.
  40393. * @param {number} n12 - 1-2 matrix element.
  40394. * @param {number} n21 - 2-1 matrix element.
  40395. * @param {number} n22 - 2-2 matrix element.
  40396. * @return {Matrix2} A reference to this matrix.
  40397. */
  40398. set( n11, n12, n21, n22 ) {
  40399. const te = this.elements;
  40400. te[ 0 ] = n11; te[ 2 ] = n12;
  40401. te[ 1 ] = n21; te[ 3 ] = n22;
  40402. return this;
  40403. }
  40404. }
  40405. const _vector$4 = /*@__PURE__*/ new Vector2();
  40406. /**
  40407. * Represents an axis-aligned bounding box (AABB) in 2D space.
  40408. */
  40409. class Box2 {
  40410. /**
  40411. * Constructs a new bounding box.
  40412. *
  40413. * @param {Vector2} [min=(Infinity,Infinity)] - A vector representing the lower boundary of the box.
  40414. * @param {Vector2} [max=(-Infinity,-Infinity)] - A vector representing the upper boundary of the box.
  40415. */
  40416. constructor( min = new Vector2( + Infinity, + Infinity ), max = new Vector2( - Infinity, - Infinity ) ) {
  40417. /**
  40418. * This flag can be used for type testing.
  40419. *
  40420. * @type {boolean}
  40421. * @readonly
  40422. * @default true
  40423. */
  40424. this.isBox2 = true;
  40425. /**
  40426. * The lower boundary of the box.
  40427. *
  40428. * @type {Vector2}
  40429. */
  40430. this.min = min;
  40431. /**
  40432. * The upper boundary of the box.
  40433. *
  40434. * @type {Vector2}
  40435. */
  40436. this.max = max;
  40437. }
  40438. /**
  40439. * Sets the lower and upper boundaries of this box.
  40440. * Please note that this method only copies the values from the given objects.
  40441. *
  40442. * @param {Vector2} min - The lower boundary of the box.
  40443. * @param {Vector2} max - The upper boundary of the box.
  40444. * @return {Box2} A reference to this bounding box.
  40445. */
  40446. set( min, max ) {
  40447. this.min.copy( min );
  40448. this.max.copy( max );
  40449. return this;
  40450. }
  40451. /**
  40452. * Sets the upper and lower bounds of this box so it encloses the position data
  40453. * in the given array.
  40454. *
  40455. * @param {Array<Vector2>} points - An array holding 2D position data as instances of {@link Vector2}.
  40456. * @return {Box2} A reference to this bounding box.
  40457. */
  40458. setFromPoints( points ) {
  40459. this.makeEmpty();
  40460. for ( let i = 0, il = points.length; i < il; i ++ ) {
  40461. this.expandByPoint( points[ i ] );
  40462. }
  40463. return this;
  40464. }
  40465. /**
  40466. * Centers this box on the given center vector and sets this box's width, height and
  40467. * depth to the given size values.
  40468. *
  40469. * @param {Vector2} center - The center of the box.
  40470. * @param {Vector2} size - The x and y dimensions of the box.
  40471. * @return {Box2} A reference to this bounding box.
  40472. */
  40473. setFromCenterAndSize( center, size ) {
  40474. const halfSize = _vector$4.copy( size ).multiplyScalar( 0.5 );
  40475. this.min.copy( center ).sub( halfSize );
  40476. this.max.copy( center ).add( halfSize );
  40477. return this;
  40478. }
  40479. /**
  40480. * Returns a new box with copied values from this instance.
  40481. *
  40482. * @return {Box2} A clone of this instance.
  40483. */
  40484. clone() {
  40485. return new this.constructor().copy( this );
  40486. }
  40487. /**
  40488. * Copies the values of the given box to this instance.
  40489. *
  40490. * @param {Box2} box - The box to copy.
  40491. * @return {Box2} A reference to this bounding box.
  40492. */
  40493. copy( box ) {
  40494. this.min.copy( box.min );
  40495. this.max.copy( box.max );
  40496. return this;
  40497. }
  40498. /**
  40499. * Makes this box empty which means in encloses a zero space in 2D.
  40500. *
  40501. * @return {Box2} A reference to this bounding box.
  40502. */
  40503. makeEmpty() {
  40504. this.min.x = this.min.y = + Infinity;
  40505. this.max.x = this.max.y = - Infinity;
  40506. return this;
  40507. }
  40508. /**
  40509. * Returns true if this box includes zero points within its bounds.
  40510. * Note that a box with equal lower and upper bounds still includes one
  40511. * point, the one both bounds share.
  40512. *
  40513. * @return {boolean} Whether this box is empty or not.
  40514. */
  40515. isEmpty() {
  40516. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  40517. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  40518. }
  40519. /**
  40520. * Returns the center point of this box.
  40521. *
  40522. * @param {Vector2} target - The target vector that is used to store the method's result.
  40523. * @return {Vector2} The center point.
  40524. */
  40525. getCenter( target ) {
  40526. return this.isEmpty() ? target.set( 0, 0 ) : target.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  40527. }
  40528. /**
  40529. * Returns the dimensions of this box.
  40530. *
  40531. * @param {Vector2} target - The target vector that is used to store the method's result.
  40532. * @return {Vector2} The size.
  40533. */
  40534. getSize( target ) {
  40535. return this.isEmpty() ? target.set( 0, 0 ) : target.subVectors( this.max, this.min );
  40536. }
  40537. /**
  40538. * Expands the boundaries of this box to include the given point.
  40539. *
  40540. * @param {Vector2} point - The point that should be included by the bounding box.
  40541. * @return {Box2} A reference to this bounding box.
  40542. */
  40543. expandByPoint( point ) {
  40544. this.min.min( point );
  40545. this.max.max( point );
  40546. return this;
  40547. }
  40548. /**
  40549. * Expands this box equilaterally by the given vector. The width of this
  40550. * box will be expanded by the x component of the vector in both
  40551. * directions. The height of this box will be expanded by the y component of
  40552. * the vector in both directions.
  40553. *
  40554. * @param {Vector2} vector - The vector that should expand the bounding box.
  40555. * @return {Box2} A reference to this bounding box.
  40556. */
  40557. expandByVector( vector ) {
  40558. this.min.sub( vector );
  40559. this.max.add( vector );
  40560. return this;
  40561. }
  40562. /**
  40563. * Expands each dimension of the box by the given scalar. If negative, the
  40564. * dimensions of the box will be contracted.
  40565. *
  40566. * @param {number} scalar - The scalar value that should expand the bounding box.
  40567. * @return {Box2} A reference to this bounding box.
  40568. */
  40569. expandByScalar( scalar ) {
  40570. this.min.addScalar( - scalar );
  40571. this.max.addScalar( scalar );
  40572. return this;
  40573. }
  40574. /**
  40575. * Returns `true` if the given point lies within or on the boundaries of this box.
  40576. *
  40577. * @param {Vector2} point - The point to test.
  40578. * @return {boolean} Whether the bounding box contains the given point or not.
  40579. */
  40580. containsPoint( point ) {
  40581. return point.x >= this.min.x && point.x <= this.max.x &&
  40582. point.y >= this.min.y && point.y <= this.max.y;
  40583. }
  40584. /**
  40585. * Returns `true` if this bounding box includes the entirety of the given bounding box.
  40586. * If this box and the given one are identical, this function also returns `true`.
  40587. *
  40588. * @param {Box2} box - The bounding box to test.
  40589. * @return {boolean} Whether the bounding box contains the given bounding box or not.
  40590. */
  40591. containsBox( box ) {
  40592. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  40593. this.min.y <= box.min.y && box.max.y <= this.max.y;
  40594. }
  40595. /**
  40596. * Returns a point as a proportion of this box's width and height.
  40597. *
  40598. * @param {Vector2} point - A point in 2D space.
  40599. * @param {Vector2} target - The target vector that is used to store the method's result.
  40600. * @return {Vector2} A point as a proportion of this box's width and height.
  40601. */
  40602. getParameter( point, target ) {
  40603. // This can potentially have a divide by zero if the box
  40604. // has a size dimension of 0.
  40605. return target.set(
  40606. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  40607. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  40608. );
  40609. }
  40610. /**
  40611. * Returns `true` if the given bounding box intersects with this bounding box.
  40612. *
  40613. * @param {Box2} box - The bounding box to test.
  40614. * @return {boolean} Whether the given bounding box intersects with this bounding box.
  40615. */
  40616. intersectsBox( box ) {
  40617. // using 4 splitting planes to rule out intersections
  40618. return box.max.x >= this.min.x && box.min.x <= this.max.x &&
  40619. box.max.y >= this.min.y && box.min.y <= this.max.y;
  40620. }
  40621. /**
  40622. * Clamps the given point within the bounds of this box.
  40623. *
  40624. * @param {Vector2} point - The point to clamp.
  40625. * @param {Vector2} target - The target vector that is used to store the method's result.
  40626. * @return {Vector2} The clamped point.
  40627. */
  40628. clampPoint( point, target ) {
  40629. return target.copy( point ).clamp( this.min, this.max );
  40630. }
  40631. /**
  40632. * Returns the euclidean distance from any edge of this box to the specified point. If
  40633. * the given point lies inside of this box, the distance will be `0`.
  40634. *
  40635. * @param {Vector2} point - The point to compute the distance to.
  40636. * @return {number} The euclidean distance.
  40637. */
  40638. distanceToPoint( point ) {
  40639. return this.clampPoint( point, _vector$4 ).distanceTo( point );
  40640. }
  40641. /**
  40642. * Computes the intersection of this bounding box and the given one, setting the upper
  40643. * bound of this box to the lesser of the two boxes' upper bounds and the
  40644. * lower bound of this box to the greater of the two boxes' lower bounds. If
  40645. * there's no overlap, makes this box empty.
  40646. *
  40647. * @param {Box2} box - The bounding box to intersect with.
  40648. * @return {Box2} A reference to this bounding box.
  40649. */
  40650. intersect( box ) {
  40651. this.min.max( box.min );
  40652. this.max.min( box.max );
  40653. if ( this.isEmpty() ) this.makeEmpty();
  40654. return this;
  40655. }
  40656. /**
  40657. * Computes the union of this box and another and the given one, setting the upper
  40658. * bound of this box to the greater of the two boxes' upper bounds and the
  40659. * lower bound of this box to the lesser of the two boxes' lower bounds.
  40660. *
  40661. * @param {Box2} box - The bounding box that will be unioned with this instance.
  40662. * @return {Box2} A reference to this bounding box.
  40663. */
  40664. union( box ) {
  40665. this.min.min( box.min );
  40666. this.max.max( box.max );
  40667. return this;
  40668. }
  40669. /**
  40670. * Adds the given offset to both the upper and lower bounds of this bounding box,
  40671. * effectively moving it in 2D space.
  40672. *
  40673. * @param {Vector2} offset - The offset that should be used to translate the bounding box.
  40674. * @return {Box2} A reference to this bounding box.
  40675. */
  40676. translate( offset ) {
  40677. this.min.add( offset );
  40678. this.max.add( offset );
  40679. return this;
  40680. }
  40681. /**
  40682. * Returns `true` if this bounding box is equal with the given one.
  40683. *
  40684. * @param {Box2} box - The box to test for equality.
  40685. * @return {boolean} Whether this bounding box is equal with the given one.
  40686. */
  40687. equals( box ) {
  40688. return box.min.equals( this.min ) && box.max.equals( this.max );
  40689. }
  40690. }
  40691. const _startP = /*@__PURE__*/ new Vector3();
  40692. const _startEnd = /*@__PURE__*/ new Vector3();
  40693. const _d1 = /*@__PURE__*/ new Vector3();
  40694. const _d2 = /*@__PURE__*/ new Vector3();
  40695. const _r = /*@__PURE__*/ new Vector3();
  40696. const _c1 = /*@__PURE__*/ new Vector3();
  40697. const _c2 = /*@__PURE__*/ new Vector3();
  40698. /**
  40699. * An analytical line segment in 3D space represented by a start and end point.
  40700. */
  40701. class Line3 {
  40702. /**
  40703. * Constructs a new line segment.
  40704. *
  40705. * @param {Vector3} [start=(0,0,0)] - Start of the line segment.
  40706. * @param {Vector3} [end=(0,0,0)] - End of the line segment.
  40707. */
  40708. constructor( start = new Vector3(), end = new Vector3() ) {
  40709. /**
  40710. * Start of the line segment.
  40711. *
  40712. * @type {Vector3}
  40713. */
  40714. this.start = start;
  40715. /**
  40716. * End of the line segment.
  40717. *
  40718. * @type {Vector3}
  40719. */
  40720. this.end = end;
  40721. }
  40722. /**
  40723. * Sets the start and end values by copying the given vectors.
  40724. *
  40725. * @param {Vector3} start - The start point.
  40726. * @param {Vector3} end - The end point.
  40727. * @return {Line3} A reference to this line segment.
  40728. */
  40729. set( start, end ) {
  40730. this.start.copy( start );
  40731. this.end.copy( end );
  40732. return this;
  40733. }
  40734. /**
  40735. * Copies the values of the given line segment to this instance.
  40736. *
  40737. * @param {Line3} line - The line segment to copy.
  40738. * @return {Line3} A reference to this line segment.
  40739. */
  40740. copy( line ) {
  40741. this.start.copy( line.start );
  40742. this.end.copy( line.end );
  40743. return this;
  40744. }
  40745. /**
  40746. * Returns the center of the line segment.
  40747. *
  40748. * @param {Vector3} target - The target vector that is used to store the method's result.
  40749. * @return {Vector3} The center point.
  40750. */
  40751. getCenter( target ) {
  40752. return target.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  40753. }
  40754. /**
  40755. * Returns the delta vector of the line segment's start and end point.
  40756. *
  40757. * @param {Vector3} target - The target vector that is used to store the method's result.
  40758. * @return {Vector3} The delta vector.
  40759. */
  40760. delta( target ) {
  40761. return target.subVectors( this.end, this.start );
  40762. }
  40763. /**
  40764. * Returns the squared Euclidean distance between the line' start and end point.
  40765. *
  40766. * @return {number} The squared Euclidean distance.
  40767. */
  40768. distanceSq() {
  40769. return this.start.distanceToSquared( this.end );
  40770. }
  40771. /**
  40772. * Returns the Euclidean distance between the line' start and end point.
  40773. *
  40774. * @return {number} The Euclidean distance.
  40775. */
  40776. distance() {
  40777. return this.start.distanceTo( this.end );
  40778. }
  40779. /**
  40780. * Returns a vector at a certain position along the line segment.
  40781. *
  40782. * @param {number} t - A value between `[0,1]` to represent a position along the line segment.
  40783. * @param {Vector3} target - The target vector that is used to store the method's result.
  40784. * @return {Vector3} The delta vector.
  40785. */
  40786. at( t, target ) {
  40787. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40788. }
  40789. /**
  40790. * Returns a point parameter based on the closest point as projected on the line segment.
  40791. *
  40792. * @param {Vector3} point - The point for which to return a point parameter.
  40793. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40794. * @return {number} The point parameter.
  40795. */
  40796. closestPointToPointParameter( point, clampToLine ) {
  40797. _startP.subVectors( point, this.start );
  40798. _startEnd.subVectors( this.end, this.start );
  40799. const startEnd2 = _startEnd.dot( _startEnd );
  40800. const startEnd_startP = _startEnd.dot( _startP );
  40801. let t = startEnd_startP / startEnd2;
  40802. if ( clampToLine ) {
  40803. t = clamp( t, 0, 1 );
  40804. }
  40805. return t;
  40806. }
  40807. /**
  40808. * Returns the closest point on the line for a given point.
  40809. *
  40810. * @param {Vector3} point - The point to compute the closest point on the line for.
  40811. * @param {boolean} clampToLine - Whether to clamp the result to the range `[0,1]` or not.
  40812. * @param {Vector3} target - The target vector that is used to store the method's result.
  40813. * @return {Vector3} The closest point on the line.
  40814. */
  40815. closestPointToPoint( point, clampToLine, target ) {
  40816. const t = this.closestPointToPointParameter( point, clampToLine );
  40817. return this.delta( target ).multiplyScalar( t ).add( this.start );
  40818. }
  40819. /**
  40820. * Returns the closest squared distance between this line segment and the given one.
  40821. *
  40822. * @param {Line3} line - The line segment to compute the closest squared distance to.
  40823. * @param {Vector3} [c1] - The closest point on this line segment.
  40824. * @param {Vector3} [c2] - The closest point on the given line segment.
  40825. * @return {number} The squared distance between this line segment and the given one.
  40826. */
  40827. distanceSqToLine3( line, c1 = _c1, c2 = _c2 ) {
  40828. // from Real-Time Collision Detection by Christer Ericson, chapter 5.1.9
  40829. // Computes closest points C1 and C2 of S1(s)=P1+s*(Q1-P1) and
  40830. // S2(t)=P2+t*(Q2-P2), returning s and t. Function result is squared
  40831. // distance between between S1(s) and S2(t)
  40832. const EPSILON = 1e-8 * 1e-8; // must be squared since we compare squared length
  40833. let s, t;
  40834. const p1 = this.start;
  40835. const p2 = line.start;
  40836. const q1 = this.end;
  40837. const q2 = line.end;
  40838. _d1.subVectors( q1, p1 ); // Direction vector of segment S1
  40839. _d2.subVectors( q2, p2 ); // Direction vector of segment S2
  40840. _r.subVectors( p1, p2 );
  40841. const a = _d1.dot( _d1 ); // Squared length of segment S1, always nonnegative
  40842. const e = _d2.dot( _d2 ); // Squared length of segment S2, always nonnegative
  40843. const f = _d2.dot( _r );
  40844. // Check if either or both segments degenerate into points
  40845. if ( a <= EPSILON && e <= EPSILON ) {
  40846. // Both segments degenerate into points
  40847. c1.copy( p1 );
  40848. c2.copy( p2 );
  40849. c1.sub( c2 );
  40850. return c1.dot( c1 );
  40851. }
  40852. if ( a <= EPSILON ) {
  40853. // First segment degenerates into a point
  40854. s = 0;
  40855. t = f / e; // s = 0 => t = (b*s + f) / e = f / e
  40856. t = clamp( t, 0, 1 );
  40857. } else {
  40858. const c = _d1.dot( _r );
  40859. if ( e <= EPSILON ) {
  40860. // Second segment degenerates into a point
  40861. t = 0;
  40862. s = clamp( - c / a, 0, 1 ); // t = 0 => s = (b*t - c) / a = -c / a
  40863. } else {
  40864. // The general nondegenerate case starts here
  40865. const b = _d1.dot( _d2 );
  40866. const denom = a * e - b * b; // Always nonnegative
  40867. // If segments not parallel, compute closest point on L1 to L2 and
  40868. // clamp to segment S1. Else pick arbitrary s (here 0)
  40869. if ( denom !== 0 ) {
  40870. s = clamp( ( b * f - c * e ) / denom, 0, 1 );
  40871. } else {
  40872. s = 0;
  40873. }
  40874. // Compute point on L2 closest to S1(s) using
  40875. // t = Dot((P1 + D1*s) - P2,D2) / Dot(D2,D2) = (b*s + f) / e
  40876. t = ( b * s + f ) / e;
  40877. // If t in [0,1] done. Else clamp t, recompute s for the new value
  40878. // of t using s = Dot((P2 + D2*t) - P1,D1) / Dot(D1,D1)= (t*b - c) / a
  40879. // and clamp s to [0, 1]
  40880. if ( t < 0 ) {
  40881. t = 0.;
  40882. s = clamp( - c / a, 0, 1 );
  40883. } else if ( t > 1 ) {
  40884. t = 1;
  40885. s = clamp( ( b - c ) / a, 0, 1 );
  40886. }
  40887. }
  40888. }
  40889. c1.copy( p1 ).add( _d1.multiplyScalar( s ) );
  40890. c2.copy( p2 ).add( _d2.multiplyScalar( t ) );
  40891. c1.sub( c2 );
  40892. return c1.dot( c1 );
  40893. }
  40894. /**
  40895. * Applies a 4x4 transformation matrix to this line segment.
  40896. *
  40897. * @param {Matrix4} matrix - The transformation matrix.
  40898. * @return {Line3} A reference to this line segment.
  40899. */
  40900. applyMatrix4( matrix ) {
  40901. this.start.applyMatrix4( matrix );
  40902. this.end.applyMatrix4( matrix );
  40903. return this;
  40904. }
  40905. /**
  40906. * Returns `true` if this line segment is equal with the given one.
  40907. *
  40908. * @param {Line3} line - The line segment to test for equality.
  40909. * @return {boolean} Whether this line segment is equal with the given one.
  40910. */
  40911. equals( line ) {
  40912. return line.start.equals( this.start ) && line.end.equals( this.end );
  40913. }
  40914. /**
  40915. * Returns a new line segment with copied values from this instance.
  40916. *
  40917. * @return {Line3} A clone of this instance.
  40918. */
  40919. clone() {
  40920. return new this.constructor().copy( this );
  40921. }
  40922. }
  40923. const _vector$3 = /*@__PURE__*/ new Vector3();
  40924. /**
  40925. * This displays a cone shaped helper object for a {@link SpotLight}.
  40926. *
  40927. * ```js
  40928. * const spotLight = new THREE.SpotLight( 0xffffff );
  40929. * spotLight.position.set( 10, 10, 10 );
  40930. * scene.add( spotLight );
  40931. *
  40932. * const spotLightHelper = new THREE.SpotLightHelper( spotLight );
  40933. * scene.add( spotLightHelper );
  40934. * ```
  40935. *
  40936. * @augments Object3D
  40937. */
  40938. class SpotLightHelper extends Object3D {
  40939. /**
  40940. * Constructs a new spot light helper.
  40941. *
  40942. * @param {HemisphereLight} light - The light to be visualized.
  40943. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  40944. * the color of the light.
  40945. */
  40946. constructor( light, color ) {
  40947. super();
  40948. /**
  40949. * The light being visualized.
  40950. *
  40951. * @type {SpotLight}
  40952. */
  40953. this.light = light;
  40954. this.matrixAutoUpdate = false;
  40955. /**
  40956. * The color parameter passed in the constructor.
  40957. * If not set, the helper will take the color of the light.
  40958. *
  40959. * @type {number|Color|string}
  40960. */
  40961. this.color = color;
  40962. this.type = 'SpotLightHelper';
  40963. const geometry = new BufferGeometry();
  40964. const positions = [
  40965. 0, 0, 0, 0, 0, 1,
  40966. 0, 0, 0, 1, 0, 1,
  40967. 0, 0, 0, -1, 0, 1,
  40968. 0, 0, 0, 0, 1, 1,
  40969. 0, 0, 0, 0, -1, 1
  40970. ];
  40971. for ( let i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  40972. const p1 = ( i / l ) * Math.PI * 2;
  40973. const p2 = ( j / l ) * Math.PI * 2;
  40974. positions.push(
  40975. Math.cos( p1 ), Math.sin( p1 ), 1,
  40976. Math.cos( p2 ), Math.sin( p2 ), 1
  40977. );
  40978. }
  40979. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  40980. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  40981. this.cone = new LineSegments( geometry, material );
  40982. this.add( this.cone );
  40983. this.update();
  40984. }
  40985. /**
  40986. * Frees the GPU-related resources allocated by this instance. Call this
  40987. * method whenever this instance is no longer used in your app.
  40988. */
  40989. dispose() {
  40990. this.cone.geometry.dispose();
  40991. this.cone.material.dispose();
  40992. }
  40993. /**
  40994. * Updates the helper to match the position and direction of the
  40995. * light being visualized.
  40996. */
  40997. update() {
  40998. this.light.updateWorldMatrix( true, false );
  40999. this.light.target.updateWorldMatrix( true, false );
  41000. // update the local matrix based on the parent and light target transforms
  41001. if ( this.parent ) {
  41002. this.parent.updateWorldMatrix( true );
  41003. this.matrix
  41004. .copy( this.parent.matrixWorld )
  41005. .invert()
  41006. .multiply( this.light.matrixWorld );
  41007. } else {
  41008. this.matrix.copy( this.light.matrixWorld );
  41009. }
  41010. this.matrixWorld.copy( this.light.matrixWorld );
  41011. const coneLength = this.light.distance ? this.light.distance : 1000;
  41012. const coneWidth = coneLength * Math.tan( this.light.angle );
  41013. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  41014. _vector$3.setFromMatrixPosition( this.light.target.matrixWorld );
  41015. this.cone.lookAt( _vector$3 );
  41016. if ( this.color !== undefined ) {
  41017. this.cone.material.color.set( this.color );
  41018. } else {
  41019. this.cone.material.color.copy( this.light.color );
  41020. }
  41021. }
  41022. }
  41023. const _vector$2 = /*@__PURE__*/ new Vector3();
  41024. const _boneMatrix = /*@__PURE__*/ new Matrix4();
  41025. const _matrixWorldInv = /*@__PURE__*/ new Matrix4();
  41026. /**
  41027. * A helper object to assist with visualizing a {@link Skeleton}.
  41028. *
  41029. * ```js
  41030. * const helper = new THREE.SkeletonHelper( skinnedMesh );
  41031. * scene.add( helper );
  41032. * ```
  41033. *
  41034. * @augments LineSegments
  41035. */
  41036. class SkeletonHelper extends LineSegments {
  41037. /**
  41038. * Constructs a new skeleton helper.
  41039. *
  41040. * @param {Object3D} object - Usually an instance of {@link SkinnedMesh}. However, any 3D object
  41041. * can be used if it represents a hierarchy of bones (see {@link Bone}).
  41042. */
  41043. constructor( object ) {
  41044. const bones = getBoneList( object );
  41045. const geometry = new BufferGeometry();
  41046. const vertices = [];
  41047. const colors = [];
  41048. for ( let i = 0; i < bones.length; i ++ ) {
  41049. const bone = bones[ i ];
  41050. if ( bone.parent && bone.parent.isBone ) {
  41051. vertices.push( 0, 0, 0 );
  41052. vertices.push( 0, 0, 0 );
  41053. colors.push( 0, 0, 0 );
  41054. colors.push( 0, 0, 0 );
  41055. }
  41056. }
  41057. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41058. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41059. const material = new LineBasicMaterial( { vertexColors: true, depthTest: false, depthWrite: false, toneMapped: false, transparent: true } );
  41060. super( geometry, material );
  41061. /**
  41062. * This flag can be used for type testing.
  41063. *
  41064. * @type {boolean}
  41065. * @readonly
  41066. * @default true
  41067. */
  41068. this.isSkeletonHelper = true;
  41069. this.type = 'SkeletonHelper';
  41070. /**
  41071. * The object being visualized.
  41072. *
  41073. * @type {Object3D}
  41074. */
  41075. this.root = object;
  41076. /**
  41077. * The list of bones that the helper visualizes.
  41078. *
  41079. * @type {Array<Bone>}
  41080. */
  41081. this.bones = bones;
  41082. this.matrix = object.matrixWorld;
  41083. this.matrixAutoUpdate = false;
  41084. // colors
  41085. const color1 = new Color( 0x0000ff );
  41086. const color2 = new Color( 0x00ff00 );
  41087. this.setColors( color1, color2 );
  41088. }
  41089. updateMatrixWorld( force ) {
  41090. const bones = this.bones;
  41091. const geometry = this.geometry;
  41092. const position = geometry.getAttribute( 'position' );
  41093. _matrixWorldInv.copy( this.root.matrixWorld ).invert();
  41094. for ( let i = 0, j = 0; i < bones.length; i ++ ) {
  41095. const bone = bones[ i ];
  41096. if ( bone.parent && bone.parent.isBone ) {
  41097. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.matrixWorld );
  41098. _vector$2.setFromMatrixPosition( _boneMatrix );
  41099. position.setXYZ( j, _vector$2.x, _vector$2.y, _vector$2.z );
  41100. _boneMatrix.multiplyMatrices( _matrixWorldInv, bone.parent.matrixWorld );
  41101. _vector$2.setFromMatrixPosition( _boneMatrix );
  41102. position.setXYZ( j + 1, _vector$2.x, _vector$2.y, _vector$2.z );
  41103. j += 2;
  41104. }
  41105. }
  41106. geometry.getAttribute( 'position' ).needsUpdate = true;
  41107. super.updateMatrixWorld( force );
  41108. }
  41109. /**
  41110. * Defines the colors of the helper.
  41111. *
  41112. * @param {Color} color1 - The first line color for each bone.
  41113. * @param {Color} color2 - The second line color for each bone.
  41114. * @return {SkeletonHelper} A reference to this helper.
  41115. */
  41116. setColors( color1, color2 ) {
  41117. const geometry = this.geometry;
  41118. const colorAttribute = geometry.getAttribute( 'color' );
  41119. for ( let i = 0; i < colorAttribute.count; i += 2 ) {
  41120. colorAttribute.setXYZ( i, color1.r, color1.g, color1.b );
  41121. colorAttribute.setXYZ( i + 1, color2.r, color2.g, color2.b );
  41122. }
  41123. colorAttribute.needsUpdate = true;
  41124. return this;
  41125. }
  41126. /**
  41127. * Frees the GPU-related resources allocated by this instance. Call this
  41128. * method whenever this instance is no longer used in your app.
  41129. */
  41130. dispose() {
  41131. this.geometry.dispose();
  41132. this.material.dispose();
  41133. }
  41134. }
  41135. function getBoneList( object ) {
  41136. const boneList = [];
  41137. if ( object.isBone === true ) {
  41138. boneList.push( object );
  41139. }
  41140. for ( let i = 0; i < object.children.length; i ++ ) {
  41141. boneList.push( ...getBoneList( object.children[ i ] ) );
  41142. }
  41143. return boneList;
  41144. }
  41145. /**
  41146. * This displays a helper object consisting of a spherical mesh for
  41147. * visualizing an instance of {@link PointLight}.
  41148. *
  41149. * ```js
  41150. * const pointLight = new THREE.PointLight( 0xff0000, 1, 100 );
  41151. * pointLight.position.set( 10, 10, 10 );
  41152. * scene.add( pointLight );
  41153. *
  41154. * const sphereSize = 1;
  41155. * const pointLightHelper = new THREE.PointLightHelper( pointLight, sphereSize );
  41156. * scene.add( pointLightHelper );
  41157. * ```
  41158. *
  41159. * @augments Mesh
  41160. */
  41161. class PointLightHelper extends Mesh {
  41162. /**
  41163. * Constructs a new point light helper.
  41164. *
  41165. * @param {PointLight} light - The light to be visualized.
  41166. * @param {number} [sphereSize=1] - The size of the sphere helper.
  41167. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41168. * the color of the light.
  41169. */
  41170. constructor( light, sphereSize, color ) {
  41171. const geometry = new SphereGeometry( sphereSize, 4, 2 );
  41172. const material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41173. super( geometry, material );
  41174. /**
  41175. * The light being visualized.
  41176. *
  41177. * @type {HemisphereLight}
  41178. */
  41179. this.light = light;
  41180. /**
  41181. * The color parameter passed in the constructor.
  41182. * If not set, the helper will take the color of the light.
  41183. *
  41184. * @type {number|Color|string}
  41185. */
  41186. this.color = color;
  41187. this.type = 'PointLightHelper';
  41188. this.matrix = this.light.matrixWorld;
  41189. this.matrixAutoUpdate = false;
  41190. this.update();
  41191. /*
  41192. // TODO: delete this comment?
  41193. const distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  41194. const distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  41195. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  41196. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  41197. const d = light.distance;
  41198. if ( d === 0.0 ) {
  41199. this.lightDistance.visible = false;
  41200. } else {
  41201. this.lightDistance.scale.set( d, d, d );
  41202. }
  41203. this.add( this.lightDistance );
  41204. */
  41205. }
  41206. /**
  41207. * Frees the GPU-related resources allocated by this instance. Call this
  41208. * method whenever this instance is no longer used in your app.
  41209. */
  41210. dispose() {
  41211. this.geometry.dispose();
  41212. this.material.dispose();
  41213. }
  41214. /**
  41215. * Updates the helper to match the position of the
  41216. * light being visualized.
  41217. */
  41218. update() {
  41219. this.light.updateWorldMatrix( true, false );
  41220. if ( this.color !== undefined ) {
  41221. this.material.color.set( this.color );
  41222. } else {
  41223. this.material.color.copy( this.light.color );
  41224. }
  41225. /*
  41226. const d = this.light.distance;
  41227. if ( d === 0.0 ) {
  41228. this.lightDistance.visible = false;
  41229. } else {
  41230. this.lightDistance.visible = true;
  41231. this.lightDistance.scale.set( d, d, d );
  41232. }
  41233. */
  41234. }
  41235. }
  41236. const _vector$1 = /*@__PURE__*/ new Vector3();
  41237. const _color1 = /*@__PURE__*/ new Color();
  41238. const _color2 = /*@__PURE__*/ new Color();
  41239. /**
  41240. * Creates a visual aid consisting of a spherical mesh for a
  41241. * given {@link HemisphereLight}.
  41242. *
  41243. * ```js
  41244. * const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 );
  41245. * const helper = new THREE.HemisphereLightHelper( light, 5 );
  41246. * scene.add( helper );
  41247. * ```
  41248. *
  41249. * @augments Object3D
  41250. */
  41251. class HemisphereLightHelper extends Object3D {
  41252. /**
  41253. * Constructs a new hemisphere light helper.
  41254. *
  41255. * @param {HemisphereLight} light - The light to be visualized.
  41256. * @param {number} [size=1] - The size of the mesh used to visualize the light.
  41257. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41258. * the color of the light.
  41259. */
  41260. constructor( light, size, color ) {
  41261. super();
  41262. /**
  41263. * The light being visualized.
  41264. *
  41265. * @type {HemisphereLight}
  41266. */
  41267. this.light = light;
  41268. this.matrix = light.matrixWorld;
  41269. this.matrixAutoUpdate = false;
  41270. /**
  41271. * The color parameter passed in the constructor.
  41272. * If not set, the helper will take the color of the light.
  41273. *
  41274. * @type {number|Color|string}
  41275. */
  41276. this.color = color;
  41277. this.type = 'HemisphereLightHelper';
  41278. const geometry = new OctahedronGeometry( size );
  41279. geometry.rotateY( Math.PI * 0.5 );
  41280. this.material = new MeshBasicMaterial( { wireframe: true, fog: false, toneMapped: false } );
  41281. if ( this.color === undefined ) this.material.vertexColors = true;
  41282. const position = geometry.getAttribute( 'position' );
  41283. const colors = new Float32Array( position.count * 3 );
  41284. geometry.setAttribute( 'color', new BufferAttribute( colors, 3 ) );
  41285. this.add( new Mesh( geometry, this.material ) );
  41286. this.update();
  41287. }
  41288. /**
  41289. * Frees the GPU-related resources allocated by this instance. Call this
  41290. * method whenever this instance is no longer used in your app.
  41291. */
  41292. dispose() {
  41293. this.children[ 0 ].geometry.dispose();
  41294. this.children[ 0 ].material.dispose();
  41295. }
  41296. /**
  41297. * Updates the helper to match the position and direction of the
  41298. * light being visualized.
  41299. */
  41300. update() {
  41301. const mesh = this.children[ 0 ];
  41302. if ( this.color !== undefined ) {
  41303. this.material.color.set( this.color );
  41304. } else {
  41305. const colors = mesh.geometry.getAttribute( 'color' );
  41306. _color1.copy( this.light.color );
  41307. _color2.copy( this.light.groundColor );
  41308. for ( let i = 0, l = colors.count; i < l; i ++ ) {
  41309. const color = ( i < ( l / 2 ) ) ? _color1 : _color2;
  41310. colors.setXYZ( i, color.r, color.g, color.b );
  41311. }
  41312. colors.needsUpdate = true;
  41313. }
  41314. this.light.updateWorldMatrix( true, false );
  41315. mesh.lookAt( _vector$1.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  41316. }
  41317. }
  41318. /**
  41319. * The helper is an object to define grids. Grids are two-dimensional
  41320. * arrays of lines.
  41321. *
  41322. * ```js
  41323. * const size = 10;
  41324. * const divisions = 10;
  41325. *
  41326. * const gridHelper = new THREE.GridHelper( size, divisions );
  41327. * scene.add( gridHelper );
  41328. * ```
  41329. *
  41330. * @augments LineSegments
  41331. */
  41332. class GridHelper extends LineSegments {
  41333. /**
  41334. * Constructs a new grid helper.
  41335. *
  41336. * @param {number} [size=10] - The size of the grid.
  41337. * @param {number} [divisions=10] - The number of divisions across the grid.
  41338. * @param {number|Color|string} [color1=0x444444] - The color of the center line.
  41339. * @param {number|Color|string} [color2=0x888888] - The color of the lines of the grid.
  41340. */
  41341. constructor( size = 10, divisions = 10, color1 = 0x444444, color2 = 0x888888 ) {
  41342. color1 = new Color( color1 );
  41343. color2 = new Color( color2 );
  41344. const center = divisions / 2;
  41345. const step = size / divisions;
  41346. const halfSize = size / 2;
  41347. const vertices = [], colors = [];
  41348. for ( let i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  41349. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  41350. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  41351. const color = i === center ? color1 : color2;
  41352. color.toArray( colors, j ); j += 3;
  41353. color.toArray( colors, j ); j += 3;
  41354. color.toArray( colors, j ); j += 3;
  41355. color.toArray( colors, j ); j += 3;
  41356. }
  41357. const geometry = new BufferGeometry();
  41358. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41359. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41360. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41361. super( geometry, material );
  41362. this.type = 'GridHelper';
  41363. }
  41364. /**
  41365. * Frees the GPU-related resources allocated by this instance. Call this
  41366. * method whenever this instance is no longer used in your app.
  41367. */
  41368. dispose() {
  41369. this.geometry.dispose();
  41370. this.material.dispose();
  41371. }
  41372. }
  41373. /**
  41374. * This helper is an object to define polar grids. Grids are
  41375. * two-dimensional arrays of lines.
  41376. *
  41377. * ```js
  41378. * const radius = 10;
  41379. * const sectors = 16;
  41380. * const rings = 8;
  41381. * const divisions = 64;
  41382. *
  41383. * const helper = new THREE.PolarGridHelper( radius, sectors, rings, divisions );
  41384. * scene.add( helper );
  41385. * ```
  41386. *
  41387. * @augments LineSegments
  41388. */
  41389. class PolarGridHelper extends LineSegments {
  41390. /**
  41391. * Constructs a new polar grid helper.
  41392. *
  41393. * @param {number} [radius=10] - The radius of the polar grid. This can be any positive number.
  41394. * @param {number} [sectors=16] - The number of sectors the grid will be divided into. This can be any positive integer.
  41395. * @param {number} [rings=16] - The number of rings. This can be any positive integer.
  41396. * @param {number} [divisions=64] - The number of line segments used for each circle. This can be any positive integer.
  41397. * @param {number|Color|string} [color1=0x444444] - The first color used for grid elements.
  41398. * @param {number|Color|string} [color2=0x888888] - The second color used for grid elements.
  41399. */
  41400. constructor( radius = 10, sectors = 16, rings = 8, divisions = 64, color1 = 0x444444, color2 = 0x888888 ) {
  41401. color1 = new Color( color1 );
  41402. color2 = new Color( color2 );
  41403. const vertices = [];
  41404. const colors = [];
  41405. // create the sectors
  41406. if ( sectors > 1 ) {
  41407. for ( let i = 0; i < sectors; i ++ ) {
  41408. const v = ( i / sectors ) * ( Math.PI * 2 );
  41409. const x = Math.sin( v ) * radius;
  41410. const z = Math.cos( v ) * radius;
  41411. vertices.push( 0, 0, 0 );
  41412. vertices.push( x, 0, z );
  41413. const color = ( i & 1 ) ? color1 : color2;
  41414. colors.push( color.r, color.g, color.b );
  41415. colors.push( color.r, color.g, color.b );
  41416. }
  41417. }
  41418. // create the rings
  41419. for ( let i = 0; i < rings; i ++ ) {
  41420. const color = ( i & 1 ) ? color1 : color2;
  41421. const r = radius - ( radius / rings * i );
  41422. for ( let j = 0; j < divisions; j ++ ) {
  41423. // first vertex
  41424. let v = ( j / divisions ) * ( Math.PI * 2 );
  41425. let x = Math.sin( v ) * r;
  41426. let z = Math.cos( v ) * r;
  41427. vertices.push( x, 0, z );
  41428. colors.push( color.r, color.g, color.b );
  41429. // second vertex
  41430. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  41431. x = Math.sin( v ) * r;
  41432. z = Math.cos( v ) * r;
  41433. vertices.push( x, 0, z );
  41434. colors.push( color.r, color.g, color.b );
  41435. }
  41436. }
  41437. const geometry = new BufferGeometry();
  41438. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41439. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41440. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  41441. super( geometry, material );
  41442. this.type = 'PolarGridHelper';
  41443. }
  41444. /**
  41445. * Frees the GPU-related resources allocated by this instance. Call this
  41446. * method whenever this instance is no longer used in your app.
  41447. */
  41448. dispose() {
  41449. this.geometry.dispose();
  41450. this.material.dispose();
  41451. }
  41452. }
  41453. const _v1 = /*@__PURE__*/ new Vector3();
  41454. const _v2 = /*@__PURE__*/ new Vector3();
  41455. const _v3 = /*@__PURE__*/ new Vector3();
  41456. /**
  41457. * Helper object to assist with visualizing a {@link DirectionalLight}'s
  41458. * effect on the scene. This consists of plane and a line representing the
  41459. * light's position and direction.
  41460. *
  41461. * ```js
  41462. * const light = new THREE.DirectionalLight( 0xFFFFFF );
  41463. * scene.add( light );
  41464. *
  41465. * const helper = new THREE.DirectionalLightHelper( light, 5 );
  41466. * scene.add( helper );
  41467. * ```
  41468. *
  41469. * @augments Object3D
  41470. */
  41471. class DirectionalLightHelper extends Object3D {
  41472. /**
  41473. * Constructs a new directional light helper.
  41474. *
  41475. * @param {DirectionalLight} light - The light to be visualized.
  41476. * @param {number} [size=1] - The dimensions of the plane.
  41477. * @param {number|Color|string} [color] - The helper's color. If not set, the helper will take
  41478. * the color of the light.
  41479. */
  41480. constructor( light, size, color ) {
  41481. super();
  41482. /**
  41483. * The light being visualized.
  41484. *
  41485. * @type {DirectionalLight}
  41486. */
  41487. this.light = light;
  41488. this.matrix = light.matrixWorld;
  41489. this.matrixAutoUpdate = false;
  41490. /**
  41491. * The color parameter passed in the constructor.
  41492. * If not set, the helper will take the color of the light.
  41493. *
  41494. * @type {number|Color|string}
  41495. */
  41496. this.color = color;
  41497. this.type = 'DirectionalLightHelper';
  41498. if ( size === undefined ) size = 1;
  41499. let geometry = new BufferGeometry();
  41500. geometry.setAttribute( 'position', new Float32BufferAttribute( [
  41501. - size, size, 0,
  41502. size, size, 0,
  41503. size, - size, 0,
  41504. - size, - size, 0,
  41505. - size, size, 0
  41506. ], 3 ) );
  41507. const material = new LineBasicMaterial( { fog: false, toneMapped: false } );
  41508. /**
  41509. * Contains the line showing the location of the directional light.
  41510. *
  41511. * @type {Line}
  41512. */
  41513. this.lightPlane = new Line( geometry, material );
  41514. this.add( this.lightPlane );
  41515. geometry = new BufferGeometry();
  41516. geometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  41517. /**
  41518. * Represents the target line of the directional light.
  41519. *
  41520. * @type {Line}
  41521. */
  41522. this.targetLine = new Line( geometry, material );
  41523. this.add( this.targetLine );
  41524. this.update();
  41525. }
  41526. /**
  41527. * Frees the GPU-related resources allocated by this instance. Call this
  41528. * method whenever this instance is no longer used in your app.
  41529. */
  41530. dispose() {
  41531. this.lightPlane.geometry.dispose();
  41532. this.lightPlane.material.dispose();
  41533. this.targetLine.geometry.dispose();
  41534. this.targetLine.material.dispose();
  41535. }
  41536. /**
  41537. * Updates the helper to match the position and direction of the
  41538. * light being visualized.
  41539. */
  41540. update() {
  41541. this.light.updateWorldMatrix( true, false );
  41542. this.light.target.updateWorldMatrix( true, false );
  41543. _v1.setFromMatrixPosition( this.light.matrixWorld );
  41544. _v2.setFromMatrixPosition( this.light.target.matrixWorld );
  41545. _v3.subVectors( _v2, _v1 );
  41546. this.lightPlane.lookAt( _v2 );
  41547. if ( this.color !== undefined ) {
  41548. this.lightPlane.material.color.set( this.color );
  41549. this.targetLine.material.color.set( this.color );
  41550. } else {
  41551. this.lightPlane.material.color.copy( this.light.color );
  41552. this.targetLine.material.color.copy( this.light.color );
  41553. }
  41554. this.targetLine.lookAt( _v2 );
  41555. this.targetLine.scale.z = _v3.length();
  41556. }
  41557. }
  41558. const _vector = /*@__PURE__*/ new Vector3();
  41559. const _camera = /*@__PURE__*/ new Camera();
  41560. /**
  41561. * This helps with visualizing what a camera contains in its frustum. It
  41562. * visualizes the frustum of a camera using a line segments.
  41563. *
  41564. * Based on frustum visualization in [lightgl.js shadowmap example](https://github.com/evanw/lightgl.js/blob/master/tests/shadowmap.html).
  41565. *
  41566. * `CameraHelper` must be a child of the scene.
  41567. *
  41568. * ```js
  41569. * const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
  41570. * const helper = new THREE.CameraHelper( camera );
  41571. * scene.add( helper );
  41572. * ```
  41573. *
  41574. * @augments LineSegments
  41575. */
  41576. class CameraHelper extends LineSegments {
  41577. /**
  41578. * Constructs a new arrow helper.
  41579. *
  41580. * @param {Camera} camera - The camera to visualize.
  41581. */
  41582. constructor( camera ) {
  41583. const geometry = new BufferGeometry();
  41584. const material = new LineBasicMaterial( { color: 0xffffff, vertexColors: true, toneMapped: false } );
  41585. const vertices = [];
  41586. const colors = [];
  41587. const pointMap = {};
  41588. // near
  41589. addLine( 'n1', 'n2' );
  41590. addLine( 'n2', 'n4' );
  41591. addLine( 'n4', 'n3' );
  41592. addLine( 'n3', 'n1' );
  41593. // far
  41594. addLine( 'f1', 'f2' );
  41595. addLine( 'f2', 'f4' );
  41596. addLine( 'f4', 'f3' );
  41597. addLine( 'f3', 'f1' );
  41598. // sides
  41599. addLine( 'n1', 'f1' );
  41600. addLine( 'n2', 'f2' );
  41601. addLine( 'n3', 'f3' );
  41602. addLine( 'n4', 'f4' );
  41603. // cone
  41604. addLine( 'p', 'n1' );
  41605. addLine( 'p', 'n2' );
  41606. addLine( 'p', 'n3' );
  41607. addLine( 'p', 'n4' );
  41608. // up
  41609. addLine( 'u1', 'u2' );
  41610. addLine( 'u2', 'u3' );
  41611. addLine( 'u3', 'u1' );
  41612. // target
  41613. addLine( 'c', 't' );
  41614. addLine( 'p', 'c' );
  41615. // cross
  41616. addLine( 'cn1', 'cn2' );
  41617. addLine( 'cn3', 'cn4' );
  41618. addLine( 'cf1', 'cf2' );
  41619. addLine( 'cf3', 'cf4' );
  41620. function addLine( a, b ) {
  41621. addPoint( a );
  41622. addPoint( b );
  41623. }
  41624. function addPoint( id ) {
  41625. vertices.push( 0, 0, 0 );
  41626. colors.push( 0, 0, 0 );
  41627. if ( pointMap[ id ] === undefined ) {
  41628. pointMap[ id ] = [];
  41629. }
  41630. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  41631. }
  41632. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  41633. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  41634. super( geometry, material );
  41635. this.type = 'CameraHelper';
  41636. /**
  41637. * The camera being visualized.
  41638. *
  41639. * @type {Camera}
  41640. */
  41641. this.camera = camera;
  41642. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  41643. this.matrix = camera.matrixWorld;
  41644. this.matrixAutoUpdate = false;
  41645. /**
  41646. * This contains the points used to visualize the camera.
  41647. *
  41648. * @type {Object<string,Array<number>>}
  41649. */
  41650. this.pointMap = pointMap;
  41651. this.update();
  41652. // colors
  41653. const colorFrustum = new Color( 0xffaa00 );
  41654. const colorCone = new Color( 0xff0000 );
  41655. const colorUp = new Color( 0x00aaff );
  41656. const colorTarget = new Color( 0xffffff );
  41657. const colorCross = new Color( 0x333333 );
  41658. this.setColors( colorFrustum, colorCone, colorUp, colorTarget, colorCross );
  41659. }
  41660. /**
  41661. * Defines the colors of the helper.
  41662. *
  41663. * @param {Color} frustum - The frustum line color.
  41664. * @param {Color} cone - The cone line color.
  41665. * @param {Color} up - The up line color.
  41666. * @param {Color} target - The target line color.
  41667. * @param {Color} cross - The cross line color.
  41668. * @return {CameraHelper} A reference to this helper.
  41669. */
  41670. setColors( frustum, cone, up, target, cross ) {
  41671. const geometry = this.geometry;
  41672. const colorAttribute = geometry.getAttribute( 'color' );
  41673. // near
  41674. colorAttribute.setXYZ( 0, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 1, frustum.r, frustum.g, frustum.b ); // n1, n2
  41675. colorAttribute.setXYZ( 2, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 3, frustum.r, frustum.g, frustum.b ); // n2, n4
  41676. colorAttribute.setXYZ( 4, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 5, frustum.r, frustum.g, frustum.b ); // n4, n3
  41677. colorAttribute.setXYZ( 6, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 7, frustum.r, frustum.g, frustum.b ); // n3, n1
  41678. // far
  41679. colorAttribute.setXYZ( 8, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 9, frustum.r, frustum.g, frustum.b ); // f1, f2
  41680. colorAttribute.setXYZ( 10, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 11, frustum.r, frustum.g, frustum.b ); // f2, f4
  41681. colorAttribute.setXYZ( 12, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 13, frustum.r, frustum.g, frustum.b ); // f4, f3
  41682. colorAttribute.setXYZ( 14, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 15, frustum.r, frustum.g, frustum.b ); // f3, f1
  41683. // sides
  41684. colorAttribute.setXYZ( 16, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 17, frustum.r, frustum.g, frustum.b ); // n1, f1
  41685. colorAttribute.setXYZ( 18, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 19, frustum.r, frustum.g, frustum.b ); // n2, f2
  41686. colorAttribute.setXYZ( 20, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 21, frustum.r, frustum.g, frustum.b ); // n3, f3
  41687. colorAttribute.setXYZ( 22, frustum.r, frustum.g, frustum.b ); colorAttribute.setXYZ( 23, frustum.r, frustum.g, frustum.b ); // n4, f4
  41688. // cone
  41689. colorAttribute.setXYZ( 24, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 25, cone.r, cone.g, cone.b ); // p, n1
  41690. colorAttribute.setXYZ( 26, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 27, cone.r, cone.g, cone.b ); // p, n2
  41691. colorAttribute.setXYZ( 28, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 29, cone.r, cone.g, cone.b ); // p, n3
  41692. colorAttribute.setXYZ( 30, cone.r, cone.g, cone.b ); colorAttribute.setXYZ( 31, cone.r, cone.g, cone.b ); // p, n4
  41693. // up
  41694. colorAttribute.setXYZ( 32, up.r, up.g, up.b ); colorAttribute.setXYZ( 33, up.r, up.g, up.b ); // u1, u2
  41695. colorAttribute.setXYZ( 34, up.r, up.g, up.b ); colorAttribute.setXYZ( 35, up.r, up.g, up.b ); // u2, u3
  41696. colorAttribute.setXYZ( 36, up.r, up.g, up.b ); colorAttribute.setXYZ( 37, up.r, up.g, up.b ); // u3, u1
  41697. // target
  41698. colorAttribute.setXYZ( 38, target.r, target.g, target.b ); colorAttribute.setXYZ( 39, target.r, target.g, target.b ); // c, t
  41699. colorAttribute.setXYZ( 40, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 41, cross.r, cross.g, cross.b ); // p, c
  41700. // cross
  41701. colorAttribute.setXYZ( 42, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 43, cross.r, cross.g, cross.b ); // cn1, cn2
  41702. colorAttribute.setXYZ( 44, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 45, cross.r, cross.g, cross.b ); // cn3, cn4
  41703. colorAttribute.setXYZ( 46, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 47, cross.r, cross.g, cross.b ); // cf1, cf2
  41704. colorAttribute.setXYZ( 48, cross.r, cross.g, cross.b ); colorAttribute.setXYZ( 49, cross.r, cross.g, cross.b ); // cf3, cf4
  41705. colorAttribute.needsUpdate = true;
  41706. return this;
  41707. }
  41708. /**
  41709. * Updates the helper based on the projection matrix of the camera.
  41710. */
  41711. update() {
  41712. const geometry = this.geometry;
  41713. const pointMap = this.pointMap;
  41714. const w = 1, h = 1;
  41715. let nearZ, farZ;
  41716. // we need just camera projection matrix inverse
  41717. // world matrix must be identity
  41718. _camera.projectionMatrixInverse.copy( this.camera.projectionMatrixInverse );
  41719. // Adjust z values based on coordinate system
  41720. if ( this.camera.reversedDepth === true ) {
  41721. nearZ = 1;
  41722. farZ = 0;
  41723. } else {
  41724. if ( this.camera.coordinateSystem === WebGLCoordinateSystem ) {
  41725. nearZ = -1;
  41726. farZ = 1;
  41727. } else if ( this.camera.coordinateSystem === WebGPUCoordinateSystem ) {
  41728. nearZ = 0;
  41729. farZ = 1;
  41730. } else {
  41731. throw new Error( 'THREE.CameraHelper.update(): Invalid coordinate system: ' + this.camera.coordinateSystem );
  41732. }
  41733. }
  41734. // center / target
  41735. setPoint( 'c', pointMap, geometry, _camera, 0, 0, nearZ );
  41736. setPoint( 't', pointMap, geometry, _camera, 0, 0, farZ );
  41737. // near
  41738. setPoint( 'n1', pointMap, geometry, _camera, - w, - h, nearZ );
  41739. setPoint( 'n2', pointMap, geometry, _camera, w, - h, nearZ );
  41740. setPoint( 'n3', pointMap, geometry, _camera, - w, h, nearZ );
  41741. setPoint( 'n4', pointMap, geometry, _camera, w, h, nearZ );
  41742. // far
  41743. setPoint( 'f1', pointMap, geometry, _camera, - w, - h, farZ );
  41744. setPoint( 'f2', pointMap, geometry, _camera, w, - h, farZ );
  41745. setPoint( 'f3', pointMap, geometry, _camera, - w, h, farZ );
  41746. setPoint( 'f4', pointMap, geometry, _camera, w, h, farZ );
  41747. // up
  41748. setPoint( 'u1', pointMap, geometry, _camera, w * 0.7, h * 1.1, nearZ );
  41749. setPoint( 'u2', pointMap, geometry, _camera, - w * 0.7, h * 1.1, nearZ );
  41750. setPoint( 'u3', pointMap, geometry, _camera, 0, h * 2, nearZ );
  41751. // cross
  41752. setPoint( 'cf1', pointMap, geometry, _camera, - w, 0, farZ );
  41753. setPoint( 'cf2', pointMap, geometry, _camera, w, 0, farZ );
  41754. setPoint( 'cf3', pointMap, geometry, _camera, 0, - h, farZ );
  41755. setPoint( 'cf4', pointMap, geometry, _camera, 0, h, farZ );
  41756. setPoint( 'cn1', pointMap, geometry, _camera, - w, 0, nearZ );
  41757. setPoint( 'cn2', pointMap, geometry, _camera, w, 0, nearZ );
  41758. setPoint( 'cn3', pointMap, geometry, _camera, 0, - h, nearZ );
  41759. setPoint( 'cn4', pointMap, geometry, _camera, 0, h, nearZ );
  41760. geometry.getAttribute( 'position' ).needsUpdate = true;
  41761. }
  41762. /**
  41763. * Frees the GPU-related resources allocated by this instance. Call this
  41764. * method whenever this instance is no longer used in your app.
  41765. */
  41766. dispose() {
  41767. this.geometry.dispose();
  41768. this.material.dispose();
  41769. }
  41770. }
  41771. function setPoint( point, pointMap, geometry, camera, x, y, z ) {
  41772. _vector.set( x, y, z ).unproject( camera );
  41773. const points = pointMap[ point ];
  41774. if ( points !== undefined ) {
  41775. const position = geometry.getAttribute( 'position' );
  41776. for ( let i = 0, l = points.length; i < l; i ++ ) {
  41777. position.setXYZ( points[ i ], _vector.x, _vector.y, _vector.z );
  41778. }
  41779. }
  41780. }
  41781. const _box = /*@__PURE__*/ new Box3();
  41782. /**
  41783. * Helper object to graphically show the world-axis-aligned bounding box
  41784. * around an object. The actual bounding box is handled with {@link Box3},
  41785. * this is just a visual helper for debugging. It can be automatically
  41786. * resized with {@link BoxHelper#update} when the object it's created from
  41787. * is transformed. Note that the object must have a geometry for this to work,
  41788. * so it won't work with sprites.
  41789. *
  41790. * ```js
  41791. * const sphere = new THREE.SphereGeometry();
  41792. * const object = new THREE.Mesh( sphere, new THREE.MeshBasicMaterial( 0xff0000 ) );
  41793. * const box = new THREE.BoxHelper( object, 0xffff00 );
  41794. * scene.add( box );
  41795. * ```
  41796. *
  41797. * @augments LineSegments
  41798. */
  41799. class BoxHelper extends LineSegments {
  41800. /**
  41801. * Constructs a new box helper.
  41802. *
  41803. * @param {Object3D} [object] - The 3D object to show the world-axis-aligned bounding box.
  41804. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41805. */
  41806. constructor( object, color = 0xffff00 ) {
  41807. 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 ] );
  41808. const positions = new Float32Array( 8 * 3 );
  41809. const geometry = new BufferGeometry();
  41810. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41811. geometry.setAttribute( 'position', new BufferAttribute( positions, 3 ) );
  41812. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41813. /**
  41814. * The 3D object being visualized.
  41815. *
  41816. * @type {Object3D}
  41817. */
  41818. this.object = object;
  41819. this.type = 'BoxHelper';
  41820. this.matrixAutoUpdate = false;
  41821. this.update();
  41822. }
  41823. /**
  41824. * Updates the helper's geometry to match the dimensions of the object,
  41825. * including any children.
  41826. */
  41827. update() {
  41828. if ( this.object !== undefined ) {
  41829. _box.setFromObject( this.object );
  41830. }
  41831. if ( _box.isEmpty() ) return;
  41832. const min = _box.min;
  41833. const max = _box.max;
  41834. /*
  41835. 5____4
  41836. 1/___0/|
  41837. | 6__|_7
  41838. 2/___3/
  41839. 0: max.x, max.y, max.z
  41840. 1: min.x, max.y, max.z
  41841. 2: min.x, min.y, max.z
  41842. 3: max.x, min.y, max.z
  41843. 4: max.x, max.y, min.z
  41844. 5: min.x, max.y, min.z
  41845. 6: min.x, min.y, min.z
  41846. 7: max.x, min.y, min.z
  41847. */
  41848. const position = this.geometry.attributes.position;
  41849. const array = position.array;
  41850. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  41851. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  41852. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  41853. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  41854. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  41855. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  41856. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  41857. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  41858. position.needsUpdate = true;
  41859. this.geometry.computeBoundingSphere();
  41860. }
  41861. /**
  41862. * Updates the wireframe box for the passed object.
  41863. *
  41864. * @param {Object3D} object - The 3D object to create the helper for.
  41865. * @return {BoxHelper} A reference to this instance.
  41866. */
  41867. setFromObject( object ) {
  41868. this.object = object;
  41869. this.update();
  41870. return this;
  41871. }
  41872. copy( source, recursive ) {
  41873. super.copy( source, recursive );
  41874. this.object = source.object;
  41875. return this;
  41876. }
  41877. /**
  41878. * Frees the GPU-related resources allocated by this instance. Call this
  41879. * method whenever this instance is no longer used in your app.
  41880. */
  41881. dispose() {
  41882. this.geometry.dispose();
  41883. this.material.dispose();
  41884. }
  41885. }
  41886. /**
  41887. * A helper object to visualize an instance of {@link Box3}.
  41888. *
  41889. * ```js
  41890. * const box = new THREE.Box3();
  41891. * box.setFromCenterAndSize( new THREE.Vector3( 1, 1, 1 ), new THREE.Vector3( 2, 1, 3 ) );
  41892. *
  41893. * const helper = new THREE.Box3Helper( box, 0xffff00 );
  41894. * scene.add( helper )
  41895. * ```
  41896. *
  41897. * @augments LineSegments
  41898. */
  41899. class Box3Helper extends LineSegments {
  41900. /**
  41901. * Constructs a new box3 helper.
  41902. *
  41903. * @param {Box3} box - The box to visualize.
  41904. * @param {number|Color|string} [color=0xffff00] - The box's color.
  41905. */
  41906. constructor( box, color = 0xffff00 ) {
  41907. 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 ] );
  41908. 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 ];
  41909. const geometry = new BufferGeometry();
  41910. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  41911. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41912. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41913. /**
  41914. * The box being visualized.
  41915. *
  41916. * @type {Box3}
  41917. */
  41918. this.box = box;
  41919. this.type = 'Box3Helper';
  41920. this.geometry.computeBoundingSphere();
  41921. }
  41922. updateMatrixWorld( force ) {
  41923. const box = this.box;
  41924. if ( box.isEmpty() ) return;
  41925. box.getCenter( this.position );
  41926. box.getSize( this.scale );
  41927. this.scale.multiplyScalar( 0.5 );
  41928. super.updateMatrixWorld( force );
  41929. }
  41930. /**
  41931. * Frees the GPU-related resources allocated by this instance. Call this
  41932. * method whenever this instance is no longer used in your app.
  41933. */
  41934. dispose() {
  41935. this.geometry.dispose();
  41936. this.material.dispose();
  41937. }
  41938. }
  41939. /**
  41940. * A helper object to visualize an instance of {@link Plane}.
  41941. *
  41942. * ```js
  41943. * const plane = new THREE.Plane( new THREE.Vector3( 1, 1, 0.2 ), 3 );
  41944. * const helper = new THREE.PlaneHelper( plane, 1, 0xffff00 );
  41945. * scene.add( helper );
  41946. * ```
  41947. *
  41948. * @augments Line
  41949. */
  41950. class PlaneHelper extends Line {
  41951. /**
  41952. * Constructs a new plane helper.
  41953. *
  41954. * @param {Plane} plane - The plane to be visualized.
  41955. * @param {number} [size=1] - The side length of plane helper.
  41956. * @param {number|Color|string} [hex=0xffff00] - The helper's color.
  41957. */
  41958. constructor( plane, size = 1, hex = 0xffff00 ) {
  41959. const color = hex;
  41960. 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 ];
  41961. const geometry = new BufferGeometry();
  41962. geometry.setAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  41963. geometry.computeBoundingSphere();
  41964. super( geometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  41965. this.type = 'PlaneHelper';
  41966. /**
  41967. * The plane being visualized.
  41968. *
  41969. * @type {Plane}
  41970. */
  41971. this.plane = plane;
  41972. /**
  41973. * The side length of plane helper.
  41974. *
  41975. * @type {number}
  41976. * @default 1
  41977. */
  41978. this.size = size;
  41979. const positions2 = [ 1, 1, 0, -1, 1, 0, -1, -1, 0, 1, 1, 0, -1, -1, 0, 1, -1, 0 ];
  41980. const geometry2 = new BufferGeometry();
  41981. geometry2.setAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  41982. geometry2.computeBoundingSphere();
  41983. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false, toneMapped: false } ) ) );
  41984. }
  41985. updateMatrixWorld( force ) {
  41986. this.position.set( 0, 0, 0 );
  41987. this.scale.set( 0.5 * this.size, 0.5 * this.size, 1 );
  41988. this.lookAt( this.plane.normal );
  41989. this.translateZ( - this.plane.constant );
  41990. super.updateMatrixWorld( force );
  41991. }
  41992. /**
  41993. * Updates the helper to match the position and direction of the
  41994. * light being visualized.
  41995. */
  41996. dispose() {
  41997. this.geometry.dispose();
  41998. this.material.dispose();
  41999. this.children[ 0 ].geometry.dispose();
  42000. this.children[ 0 ].material.dispose();
  42001. }
  42002. }
  42003. const _axis = /*@__PURE__*/ new Vector3();
  42004. let _lineGeometry, _coneGeometry;
  42005. /**
  42006. * An 3D arrow object for visualizing directions.
  42007. *
  42008. * ```js
  42009. * const dir = new THREE.Vector3( 1, 2, 0 );
  42010. *
  42011. * //normalize the direction vector (convert to vector of length 1)
  42012. * dir.normalize();
  42013. *
  42014. * const origin = new THREE.Vector3( 0, 0, 0 );
  42015. * const length = 1;
  42016. * const hex = 0xffff00;
  42017. *
  42018. * const arrowHelper = new THREE.ArrowHelper( dir, origin, length, hex );
  42019. * scene.add( arrowHelper );
  42020. * ```
  42021. *
  42022. * @augments Object3D
  42023. */
  42024. class ArrowHelper extends Object3D {
  42025. /**
  42026. * Constructs a new arrow helper.
  42027. *
  42028. * @param {Vector3} [dir=(0, 0, 1)] - The (normalized) direction vector.
  42029. * @param {Vector3} [origin=(0, 0, 0)] - Point at which the arrow starts.
  42030. * @param {number} [length=1] - Length of the arrow in world units.
  42031. * @param {(number|Color|string)} [color=0xffff00] - Color of the arrow.
  42032. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42033. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42034. */
  42035. 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 ) {
  42036. super();
  42037. this.type = 'ArrowHelper';
  42038. if ( _lineGeometry === undefined ) {
  42039. _lineGeometry = new BufferGeometry();
  42040. _lineGeometry.setAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  42041. _coneGeometry = new ConeGeometry( 0.5, 1, 5, 1 );
  42042. _coneGeometry.translate( 0, -0.5, 0 );
  42043. }
  42044. this.position.copy( origin );
  42045. /**
  42046. * The line part of the arrow helper.
  42047. *
  42048. * @type {Line}
  42049. */
  42050. this.line = new Line( _lineGeometry, new LineBasicMaterial( { color: color, toneMapped: false } ) );
  42051. this.line.matrixAutoUpdate = false;
  42052. this.add( this.line );
  42053. /**
  42054. * The cone part of the arrow helper.
  42055. *
  42056. * @type {Mesh}
  42057. */
  42058. this.cone = new Mesh( _coneGeometry, new MeshBasicMaterial( { color: color, toneMapped: false } ) );
  42059. this.cone.matrixAutoUpdate = false;
  42060. this.add( this.cone );
  42061. this.setDirection( dir );
  42062. this.setLength( length, headLength, headWidth );
  42063. }
  42064. /**
  42065. * Sets the direction of the helper.
  42066. *
  42067. * @param {Vector3} dir - The normalized direction vector.
  42068. */
  42069. setDirection( dir ) {
  42070. // dir is assumed to be normalized
  42071. if ( dir.y > 0.99999 ) {
  42072. this.quaternion.set( 0, 0, 0, 1 );
  42073. } else if ( dir.y < -0.99999 ) {
  42074. this.quaternion.set( 1, 0, 0, 0 );
  42075. } else {
  42076. _axis.set( dir.z, 0, - dir.x ).normalize();
  42077. const radians = Math.acos( dir.y );
  42078. this.quaternion.setFromAxisAngle( _axis, radians );
  42079. }
  42080. }
  42081. /**
  42082. * Sets the length of the helper.
  42083. *
  42084. * @param {number} length - Length of the arrow in world units.
  42085. * @param {number} [headLength=length*0.2] - The length of the head of the arrow.
  42086. * @param {number} [headWidth=headLength*0.2] - The width of the head of the arrow.
  42087. */
  42088. setLength( length, headLength = length * 0.2, headWidth = headLength * 0.2 ) {
  42089. this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
  42090. this.line.updateMatrix();
  42091. this.cone.scale.set( headWidth, headLength, headWidth );
  42092. this.cone.position.y = length;
  42093. this.cone.updateMatrix();
  42094. }
  42095. /**
  42096. * Sets the color of the helper.
  42097. *
  42098. * @param {number|Color|string} color - The color to set.
  42099. */
  42100. setColor( color ) {
  42101. this.line.material.color.set( color );
  42102. this.cone.material.color.set( color );
  42103. }
  42104. copy( source ) {
  42105. super.copy( source, false );
  42106. this.line.copy( source.line );
  42107. this.cone.copy( source.cone );
  42108. return this;
  42109. }
  42110. /**
  42111. * Frees the GPU-related resources allocated by this instance. Call this
  42112. * method whenever this instance is no longer used in your app.
  42113. */
  42114. dispose() {
  42115. this.line.geometry.dispose();
  42116. this.line.material.dispose();
  42117. this.cone.geometry.dispose();
  42118. this.cone.material.dispose();
  42119. }
  42120. }
  42121. /**
  42122. * An axis object to visualize the 3 axes in a simple way.
  42123. * The X axis is red. The Y axis is green. The Z axis is blue.
  42124. *
  42125. * ```js
  42126. * const axesHelper = new THREE.AxesHelper( 5 );
  42127. * scene.add( axesHelper );
  42128. * ```
  42129. *
  42130. * @augments LineSegments
  42131. */
  42132. class AxesHelper extends LineSegments {
  42133. /**
  42134. * Constructs a new axes helper.
  42135. *
  42136. * @param {number} [size=1] - Size of the lines representing the axes.
  42137. */
  42138. constructor( size = 1 ) {
  42139. const vertices = [
  42140. 0, 0, 0, size, 0, 0,
  42141. 0, 0, 0, 0, size, 0,
  42142. 0, 0, 0, 0, 0, size
  42143. ];
  42144. const colors = [
  42145. 1, 0, 0, 1, 0.6, 0,
  42146. 0, 1, 0, 0.6, 1, 0,
  42147. 0, 0, 1, 0, 0.6, 1
  42148. ];
  42149. const geometry = new BufferGeometry();
  42150. geometry.setAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  42151. geometry.setAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  42152. const material = new LineBasicMaterial( { vertexColors: true, toneMapped: false } );
  42153. super( geometry, material );
  42154. this.type = 'AxesHelper';
  42155. }
  42156. /**
  42157. * Defines the colors of the axes helper.
  42158. *
  42159. * @param {number|Color|string} xAxisColor - The color for the x axis.
  42160. * @param {number|Color|string} yAxisColor - The color for the y axis.
  42161. * @param {number|Color|string} zAxisColor - The color for the z axis.
  42162. * @return {AxesHelper} A reference to this axes helper.
  42163. */
  42164. setColors( xAxisColor, yAxisColor, zAxisColor ) {
  42165. const color = new Color();
  42166. const array = this.geometry.attributes.color.array;
  42167. color.set( xAxisColor );
  42168. color.toArray( array, 0 );
  42169. color.toArray( array, 3 );
  42170. color.set( yAxisColor );
  42171. color.toArray( array, 6 );
  42172. color.toArray( array, 9 );
  42173. color.set( zAxisColor );
  42174. color.toArray( array, 12 );
  42175. color.toArray( array, 15 );
  42176. this.geometry.attributes.color.needsUpdate = true;
  42177. return this;
  42178. }
  42179. /**
  42180. * Frees the GPU-related resources allocated by this instance. Call this
  42181. * method whenever this instance is no longer used in your app.
  42182. */
  42183. dispose() {
  42184. this.geometry.dispose();
  42185. this.material.dispose();
  42186. }
  42187. }
  42188. /**
  42189. * This class is used to convert a series of paths to an array of
  42190. * shapes. It is specifically used in context of fonts and SVG.
  42191. */
  42192. class ShapePath {
  42193. /**
  42194. * Constructs a new shape path.
  42195. */
  42196. constructor() {
  42197. this.type = 'ShapePath';
  42198. /**
  42199. * The color of the shape.
  42200. *
  42201. * @type {Color}
  42202. */
  42203. this.color = new Color();
  42204. /**
  42205. * The paths that have been generated for this shape.
  42206. *
  42207. * @type {Array<Path>}
  42208. * @default null
  42209. */
  42210. this.subPaths = [];
  42211. /**
  42212. * The current path that is being generated.
  42213. *
  42214. * @type {?Path}
  42215. * @default null
  42216. */
  42217. this.currentPath = null;
  42218. }
  42219. /**
  42220. * Creates a new path and moves it current point to the given one.
  42221. *
  42222. * @param {number} x - The x coordinate.
  42223. * @param {number} y - The y coordinate.
  42224. * @return {ShapePath} A reference to this shape path.
  42225. */
  42226. moveTo( x, y ) {
  42227. this.currentPath = new Path();
  42228. this.subPaths.push( this.currentPath );
  42229. this.currentPath.moveTo( x, y );
  42230. return this;
  42231. }
  42232. /**
  42233. * Adds an instance of {@link LineCurve} to the path by connecting
  42234. * the current point with the given one.
  42235. *
  42236. * @param {number} x - The x coordinate of the end point.
  42237. * @param {number} y - The y coordinate of the end point.
  42238. * @return {ShapePath} A reference to this shape path.
  42239. */
  42240. lineTo( x, y ) {
  42241. this.currentPath.lineTo( x, y );
  42242. return this;
  42243. }
  42244. /**
  42245. * Adds an instance of {@link QuadraticBezierCurve} to the path by connecting
  42246. * the current point with the given one.
  42247. *
  42248. * @param {number} aCPx - The x coordinate of the control point.
  42249. * @param {number} aCPy - The y coordinate of the control point.
  42250. * @param {number} aX - The x coordinate of the end point.
  42251. * @param {number} aY - The y coordinate of the end point.
  42252. * @return {ShapePath} A reference to this shape path.
  42253. */
  42254. quadraticCurveTo( aCPx, aCPy, aX, aY ) {
  42255. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  42256. return this;
  42257. }
  42258. /**
  42259. * Adds an instance of {@link CubicBezierCurve} to the path by connecting
  42260. * the current point with the given one.
  42261. *
  42262. * @param {number} aCP1x - The x coordinate of the first control point.
  42263. * @param {number} aCP1y - The y coordinate of the first control point.
  42264. * @param {number} aCP2x - The x coordinate of the second control point.
  42265. * @param {number} aCP2y - The y coordinate of the second control point.
  42266. * @param {number} aX - The x coordinate of the end point.
  42267. * @param {number} aY - The y coordinate of the end point.
  42268. * @return {ShapePath} A reference to this shape path.
  42269. */
  42270. bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  42271. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  42272. return this;
  42273. }
  42274. /**
  42275. * Adds an instance of {@link SplineCurve} to the path by connecting
  42276. * the current point with the given list of points.
  42277. *
  42278. * @param {Array<Vector2>} pts - An array of points in 2D space.
  42279. * @return {ShapePath} A reference to this shape path.
  42280. */
  42281. splineThru( pts ) {
  42282. this.currentPath.splineThru( pts );
  42283. return this;
  42284. }
  42285. /**
  42286. * Converts the paths into an array of shapes.
  42287. *
  42288. * @param {boolean} isCCW - By default solid shapes are defined clockwise (CW) and holes are defined counterclockwise (CCW).
  42289. * If this flag is set to `true`, then those are flipped.
  42290. * @return {Array<Shape>} An array of shapes.
  42291. */
  42292. toShapes( isCCW ) {
  42293. function toShapesNoHoles( inSubpaths ) {
  42294. const shapes = [];
  42295. for ( let i = 0, l = inSubpaths.length; i < l; i ++ ) {
  42296. const tmpPath = inSubpaths[ i ];
  42297. const tmpShape = new Shape();
  42298. tmpShape.curves = tmpPath.curves;
  42299. shapes.push( tmpShape );
  42300. }
  42301. return shapes;
  42302. }
  42303. function isPointInsidePolygon( inPt, inPolygon ) {
  42304. const polyLen = inPolygon.length;
  42305. // inPt on polygon contour => immediate success or
  42306. // toggling of inside/outside at every single! intersection point of an edge
  42307. // with the horizontal line through inPt, left of inPt
  42308. // not counting lowerY endpoints of edges and whole edges on that line
  42309. let inside = false;
  42310. for ( let p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  42311. let edgeLowPt = inPolygon[ p ];
  42312. let edgeHighPt = inPolygon[ q ];
  42313. let edgeDx = edgeHighPt.x - edgeLowPt.x;
  42314. let edgeDy = edgeHighPt.y - edgeLowPt.y;
  42315. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  42316. // not parallel
  42317. if ( edgeDy < 0 ) {
  42318. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  42319. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  42320. }
  42321. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  42322. if ( inPt.y === edgeLowPt.y ) {
  42323. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  42324. // continue; // no intersection or edgeLowPt => doesn't count !!!
  42325. } else {
  42326. const perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  42327. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  42328. if ( perpEdge < 0 ) continue;
  42329. inside = ! inside; // true intersection left of inPt
  42330. }
  42331. } else {
  42332. // parallel or collinear
  42333. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  42334. // edge lies on the same horizontal line as inPt
  42335. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  42336. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  42337. // continue;
  42338. }
  42339. }
  42340. return inside;
  42341. }
  42342. const isClockWise = ShapeUtils.isClockWise;
  42343. const subPaths = this.subPaths;
  42344. if ( subPaths.length === 0 ) return [];
  42345. let solid, tmpPath, tmpShape;
  42346. const shapes = [];
  42347. if ( subPaths.length === 1 ) {
  42348. tmpPath = subPaths[ 0 ];
  42349. tmpShape = new Shape();
  42350. tmpShape.curves = tmpPath.curves;
  42351. shapes.push( tmpShape );
  42352. return shapes;
  42353. }
  42354. let holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  42355. holesFirst = isCCW ? ! holesFirst : holesFirst;
  42356. // log("Holes first", holesFirst);
  42357. const betterShapeHoles = [];
  42358. const newShapes = [];
  42359. let newShapeHoles = [];
  42360. let mainIdx = 0;
  42361. let tmpPoints;
  42362. newShapes[ mainIdx ] = undefined;
  42363. newShapeHoles[ mainIdx ] = [];
  42364. for ( let i = 0, l = subPaths.length; i < l; i ++ ) {
  42365. tmpPath = subPaths[ i ];
  42366. tmpPoints = tmpPath.getPoints();
  42367. solid = isClockWise( tmpPoints );
  42368. solid = isCCW ? ! solid : solid;
  42369. if ( solid ) {
  42370. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  42371. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  42372. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  42373. if ( holesFirst ) mainIdx ++;
  42374. newShapeHoles[ mainIdx ] = [];
  42375. //log('cw', i);
  42376. } else {
  42377. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  42378. //log('ccw', i);
  42379. }
  42380. }
  42381. // only Holes? -> probably all Shapes with wrong orientation
  42382. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  42383. if ( newShapes.length > 1 ) {
  42384. let ambiguous = false;
  42385. let toChange = 0;
  42386. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42387. betterShapeHoles[ sIdx ] = [];
  42388. }
  42389. for ( let sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  42390. const sho = newShapeHoles[ sIdx ];
  42391. for ( let hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  42392. const ho = sho[ hIdx ];
  42393. let hole_unassigned = true;
  42394. for ( let s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  42395. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  42396. if ( sIdx !== s2Idx ) toChange ++;
  42397. if ( hole_unassigned ) {
  42398. hole_unassigned = false;
  42399. betterShapeHoles[ s2Idx ].push( ho );
  42400. } else {
  42401. ambiguous = true;
  42402. }
  42403. }
  42404. }
  42405. if ( hole_unassigned ) {
  42406. betterShapeHoles[ sIdx ].push( ho );
  42407. }
  42408. }
  42409. }
  42410. if ( toChange > 0 && ambiguous === false ) {
  42411. newShapeHoles = betterShapeHoles;
  42412. }
  42413. }
  42414. let tmpHoles;
  42415. for ( let i = 0, il = newShapes.length; i < il; i ++ ) {
  42416. tmpShape = newShapes[ i ].s;
  42417. shapes.push( tmpShape );
  42418. tmpHoles = newShapeHoles[ i ];
  42419. for ( let j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  42420. tmpShape.holes.push( tmpHoles[ j ].h );
  42421. }
  42422. }
  42423. //log("shape", shapes);
  42424. return shapes;
  42425. }
  42426. }
  42427. /**
  42428. * Abstract base class for controls.
  42429. *
  42430. * @abstract
  42431. * @augments EventDispatcher
  42432. */
  42433. class Controls extends EventDispatcher {
  42434. /**
  42435. * Constructs a new controls instance.
  42436. *
  42437. * @param {Object3D} object - The object that is managed by the controls.
  42438. * @param {?HTMLElement} domElement - The HTML element used for event listeners.
  42439. */
  42440. constructor( object, domElement = null ) {
  42441. super();
  42442. /**
  42443. * The object that is managed by the controls.
  42444. *
  42445. * @type {Object3D}
  42446. */
  42447. this.object = object;
  42448. /**
  42449. * The HTML element used for event listeners.
  42450. *
  42451. * @type {?HTMLElement}
  42452. * @default null
  42453. */
  42454. this.domElement = domElement;
  42455. /**
  42456. * Whether the controls responds to user input or not.
  42457. *
  42458. * @type {boolean}
  42459. * @default true
  42460. */
  42461. this.enabled = true;
  42462. /**
  42463. * The internal state of the controls.
  42464. *
  42465. * @type {number}
  42466. * @default -1
  42467. */
  42468. this.state = -1;
  42469. /**
  42470. * This object defines the keyboard input of the controls.
  42471. *
  42472. * @type {Object}
  42473. */
  42474. this.keys = {};
  42475. /**
  42476. * This object defines what type of actions are assigned to the available mouse buttons.
  42477. * It depends on the control implementation what kind of mouse buttons and actions are supported.
  42478. *
  42479. * @type {{LEFT: ?number, MIDDLE: ?number, RIGHT: ?number}}
  42480. */
  42481. this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
  42482. /**
  42483. * This object defines what type of actions are assigned to what kind of touch interaction.
  42484. * It depends on the control implementation what kind of touch interaction and actions are supported.
  42485. *
  42486. * @type {{ONE: ?number, TWO: ?number}}
  42487. */
  42488. this.touches = { ONE: null, TWO: null };
  42489. }
  42490. /**
  42491. * Connects the controls to the DOM. This method has so called "side effects" since
  42492. * it adds the module's event listeners to the DOM.
  42493. *
  42494. * @param {HTMLElement} element - The DOM element to connect to.
  42495. */
  42496. connect( element ) {
  42497. if ( element === undefined ) {
  42498. warn( 'Controls: connect() now requires an element.' ); // @deprecated, the warning can be removed with r185
  42499. return;
  42500. }
  42501. if ( this.domElement !== null ) this.disconnect();
  42502. this.domElement = element;
  42503. }
  42504. /**
  42505. * Disconnects the controls from the DOM.
  42506. */
  42507. disconnect() {}
  42508. /**
  42509. * Call this method if you no longer want use to the controls. It frees all internal
  42510. * resources and removes all event listeners.
  42511. */
  42512. dispose() {}
  42513. /**
  42514. * Controls should implement this method if they have to update their internal state
  42515. * per simulation step.
  42516. *
  42517. * @param {number} [delta] - The time delta in seconds.
  42518. */
  42519. update( /* delta */ ) {}
  42520. }
  42521. /**
  42522. * Scales the texture as large as possible within its surface without cropping
  42523. * or stretching the texture. The method preserves the original aspect ratio of
  42524. * the texture. Akin to CSS `object-fit: contain`
  42525. *
  42526. * @param {Texture} texture - The texture.
  42527. * @param {number} aspect - The texture's aspect ratio.
  42528. * @return {Texture} The updated texture.
  42529. */
  42530. function contain( texture, aspect ) {
  42531. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42532. if ( imageAspect > aspect ) {
  42533. texture.repeat.x = 1;
  42534. texture.repeat.y = imageAspect / aspect;
  42535. texture.offset.x = 0;
  42536. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42537. } else {
  42538. texture.repeat.x = aspect / imageAspect;
  42539. texture.repeat.y = 1;
  42540. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42541. texture.offset.y = 0;
  42542. }
  42543. return texture;
  42544. }
  42545. /**
  42546. * Scales the texture to the smallest possible size to fill the surface, leaving
  42547. * no empty space. The method preserves the original aspect ratio of the texture.
  42548. * Akin to CSS `object-fit: cover`.
  42549. *
  42550. * @param {Texture} texture - The texture.
  42551. * @param {number} aspect - The texture's aspect ratio.
  42552. * @return {Texture} The updated texture.
  42553. */
  42554. function cover( texture, aspect ) {
  42555. const imageAspect = ( texture.image && texture.image.width ) ? texture.image.width / texture.image.height : 1;
  42556. if ( imageAspect > aspect ) {
  42557. texture.repeat.x = aspect / imageAspect;
  42558. texture.repeat.y = 1;
  42559. texture.offset.x = ( 1 - texture.repeat.x ) / 2;
  42560. texture.offset.y = 0;
  42561. } else {
  42562. texture.repeat.x = 1;
  42563. texture.repeat.y = imageAspect / aspect;
  42564. texture.offset.x = 0;
  42565. texture.offset.y = ( 1 - texture.repeat.y ) / 2;
  42566. }
  42567. return texture;
  42568. }
  42569. /**
  42570. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42571. *
  42572. * @param {Texture} texture - The texture.
  42573. * @return {Texture} The updated texture.
  42574. */
  42575. function fill( texture ) {
  42576. texture.repeat.x = 1;
  42577. texture.repeat.y = 1;
  42578. texture.offset.x = 0;
  42579. texture.offset.y = 0;
  42580. return texture;
  42581. }
  42582. /**
  42583. * Determines how many bytes must be used to represent the texture.
  42584. *
  42585. * @param {number} width - The width of the texture.
  42586. * @param {number} height - The height of the texture.
  42587. * @param {number} format - The texture's format.
  42588. * @param {number} type - The texture's type.
  42589. * @return {number} The byte length.
  42590. */
  42591. function getByteLength( width, height, format, type ) {
  42592. const typeByteLength = getTextureTypeByteLength( type );
  42593. switch ( format ) {
  42594. // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml
  42595. case AlphaFormat:
  42596. return width * height;
  42597. case RedFormat:
  42598. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42599. case RedIntegerFormat:
  42600. return ( ( width * height ) / typeByteLength.components ) * typeByteLength.byteLength;
  42601. case RGFormat:
  42602. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42603. case RGIntegerFormat:
  42604. return ( ( width * height * 2 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42605. case RGBFormat:
  42606. return ( ( width * height * 3 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42607. case RGBAFormat:
  42608. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42609. case RGBAIntegerFormat:
  42610. return ( ( width * height * 4 ) / typeByteLength.components ) * typeByteLength.byteLength;
  42611. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/
  42612. case RGB_S3TC_DXT1_Format:
  42613. case RGBA_S3TC_DXT1_Format:
  42614. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42615. case RGBA_S3TC_DXT3_Format:
  42616. case RGBA_S3TC_DXT5_Format:
  42617. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42618. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/
  42619. case RGB_PVRTC_2BPPV1_Format:
  42620. case RGBA_PVRTC_2BPPV1_Format:
  42621. return ( Math.max( width, 16 ) * Math.max( height, 8 ) ) / 4;
  42622. case RGB_PVRTC_4BPPV1_Format:
  42623. case RGBA_PVRTC_4BPPV1_Format:
  42624. return ( Math.max( width, 8 ) * Math.max( height, 8 ) ) / 2;
  42625. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/
  42626. case RGB_ETC1_Format:
  42627. case RGB_ETC2_Format:
  42628. case R11_EAC_Format:
  42629. case SIGNED_R11_EAC_Format:
  42630. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 8;
  42631. case RGBA_ETC2_EAC_Format:
  42632. case RG11_EAC_Format:
  42633. case SIGNED_RG11_EAC_Format:
  42634. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42635. // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/
  42636. case RGBA_ASTC_4x4_Format:
  42637. return Math.floor( ( width + 3 ) / 4 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42638. case RGBA_ASTC_5x4_Format:
  42639. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 3 ) / 4 ) * 16;
  42640. case RGBA_ASTC_5x5_Format:
  42641. return Math.floor( ( width + 4 ) / 5 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42642. case RGBA_ASTC_6x5_Format:
  42643. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42644. case RGBA_ASTC_6x6_Format:
  42645. return Math.floor( ( width + 5 ) / 6 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42646. case RGBA_ASTC_8x5_Format:
  42647. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42648. case RGBA_ASTC_8x6_Format:
  42649. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42650. case RGBA_ASTC_8x8_Format:
  42651. return Math.floor( ( width + 7 ) / 8 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42652. case RGBA_ASTC_10x5_Format:
  42653. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 4 ) / 5 ) * 16;
  42654. case RGBA_ASTC_10x6_Format:
  42655. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 5 ) / 6 ) * 16;
  42656. case RGBA_ASTC_10x8_Format:
  42657. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 7 ) / 8 ) * 16;
  42658. case RGBA_ASTC_10x10_Format:
  42659. return Math.floor( ( width + 9 ) / 10 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42660. case RGBA_ASTC_12x10_Format:
  42661. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 9 ) / 10 ) * 16;
  42662. case RGBA_ASTC_12x12_Format:
  42663. return Math.floor( ( width + 11 ) / 12 ) * Math.floor( ( height + 11 ) / 12 ) * 16;
  42664. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/
  42665. case RGBA_BPTC_Format:
  42666. case RGB_BPTC_SIGNED_Format:
  42667. case RGB_BPTC_UNSIGNED_Format:
  42668. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42669. // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/
  42670. case RED_RGTC1_Format:
  42671. case SIGNED_RED_RGTC1_Format:
  42672. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 8;
  42673. case RED_GREEN_RGTC2_Format:
  42674. case SIGNED_RED_GREEN_RGTC2_Format:
  42675. return Math.ceil( width / 4 ) * Math.ceil( height / 4 ) * 16;
  42676. }
  42677. throw new Error(
  42678. `Unable to determine texture byte length for ${format} format.`,
  42679. );
  42680. }
  42681. function getTextureTypeByteLength( type ) {
  42682. switch ( type ) {
  42683. case UnsignedByteType:
  42684. case ByteType:
  42685. return { byteLength: 1, components: 1 };
  42686. case UnsignedShortType:
  42687. case ShortType:
  42688. case HalfFloatType:
  42689. return { byteLength: 2, components: 1 };
  42690. case UnsignedShort4444Type:
  42691. case UnsignedShort5551Type:
  42692. return { byteLength: 2, components: 4 };
  42693. case UnsignedIntType:
  42694. case IntType:
  42695. case FloatType:
  42696. return { byteLength: 4, components: 1 };
  42697. case UnsignedInt5999Type:
  42698. case UnsignedInt101111Type:
  42699. return { byteLength: 4, components: 3 };
  42700. }
  42701. throw new Error( `Unknown texture type ${type}.` );
  42702. }
  42703. /**
  42704. * A class containing utility functions for textures.
  42705. *
  42706. * @hideconstructor
  42707. */
  42708. class TextureUtils {
  42709. /**
  42710. * Scales the texture as large as possible within its surface without cropping
  42711. * or stretching the texture. The method preserves the original aspect ratio of
  42712. * the texture. Akin to CSS `object-fit: contain`
  42713. *
  42714. * @param {Texture} texture - The texture.
  42715. * @param {number} aspect - The texture's aspect ratio.
  42716. * @return {Texture} The updated texture.
  42717. */
  42718. static contain( texture, aspect ) {
  42719. return contain( texture, aspect );
  42720. }
  42721. /**
  42722. * Scales the texture to the smallest possible size to fill the surface, leaving
  42723. * no empty space. The method preserves the original aspect ratio of the texture.
  42724. * Akin to CSS `object-fit: cover`.
  42725. *
  42726. * @param {Texture} texture - The texture.
  42727. * @param {number} aspect - The texture's aspect ratio.
  42728. * @return {Texture} The updated texture.
  42729. */
  42730. static cover( texture, aspect ) {
  42731. return cover( texture, aspect );
  42732. }
  42733. /**
  42734. * Configures the texture to the default transformation. Akin to CSS `object-fit: fill`.
  42735. *
  42736. * @param {Texture} texture - The texture.
  42737. * @return {Texture} The updated texture.
  42738. */
  42739. static fill( texture ) {
  42740. return fill( texture );
  42741. }
  42742. /**
  42743. * Determines how many bytes must be used to represent the texture.
  42744. *
  42745. * @param {number} width - The width of the texture.
  42746. * @param {number} height - The height of the texture.
  42747. * @param {number} format - The texture's format.
  42748. * @param {number} type - The texture's type.
  42749. * @return {number} The byte length.
  42750. */
  42751. static getByteLength( width, height, format, type ) {
  42752. return getByteLength( width, height, format, type );
  42753. }
  42754. }
  42755. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  42756. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'register', { detail: {
  42757. revision: REVISION,
  42758. } } ) );
  42759. }
  42760. if ( typeof window !== 'undefined' ) {
  42761. if ( window.__THREE__ ) {
  42762. warn( 'WARNING: Multiple instances of Three.js being imported.' );
  42763. } else {
  42764. window.__THREE__ = REVISION;
  42765. }
  42766. }
  42767. function WebGLAnimation() {
  42768. let context = null;
  42769. let isAnimating = false;
  42770. let animationLoop = null;
  42771. let requestId = null;
  42772. function onAnimationFrame( time, frame ) {
  42773. animationLoop( time, frame );
  42774. requestId = context.requestAnimationFrame( onAnimationFrame );
  42775. }
  42776. return {
  42777. start: function () {
  42778. if ( isAnimating === true ) return;
  42779. if ( animationLoop === null ) return;
  42780. requestId = context.requestAnimationFrame( onAnimationFrame );
  42781. isAnimating = true;
  42782. },
  42783. stop: function () {
  42784. context.cancelAnimationFrame( requestId );
  42785. isAnimating = false;
  42786. },
  42787. setAnimationLoop: function ( callback ) {
  42788. animationLoop = callback;
  42789. },
  42790. setContext: function ( value ) {
  42791. context = value;
  42792. }
  42793. };
  42794. }
  42795. function WebGLAttributes( gl ) {
  42796. const buffers = new WeakMap();
  42797. function createBuffer( attribute, bufferType ) {
  42798. const array = attribute.array;
  42799. const usage = attribute.usage;
  42800. const size = array.byteLength;
  42801. const buffer = gl.createBuffer();
  42802. gl.bindBuffer( bufferType, buffer );
  42803. gl.bufferData( bufferType, array, usage );
  42804. attribute.onUploadCallback();
  42805. let type;
  42806. if ( array instanceof Float32Array ) {
  42807. type = gl.FLOAT;
  42808. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42809. type = gl.HALF_FLOAT;
  42810. } else if ( array instanceof Uint16Array ) {
  42811. if ( attribute.isFloat16BufferAttribute ) {
  42812. type = gl.HALF_FLOAT;
  42813. } else {
  42814. type = gl.UNSIGNED_SHORT;
  42815. }
  42816. } else if ( array instanceof Int16Array ) {
  42817. type = gl.SHORT;
  42818. } else if ( array instanceof Uint32Array ) {
  42819. type = gl.UNSIGNED_INT;
  42820. } else if ( array instanceof Int32Array ) {
  42821. type = gl.INT;
  42822. } else if ( array instanceof Int8Array ) {
  42823. type = gl.BYTE;
  42824. } else if ( array instanceof Uint8Array ) {
  42825. type = gl.UNSIGNED_BYTE;
  42826. } else if ( array instanceof Uint8ClampedArray ) {
  42827. type = gl.UNSIGNED_BYTE;
  42828. } else {
  42829. throw new Error( 'THREE.WebGLAttributes: Unsupported buffer data format: ' + array );
  42830. }
  42831. return {
  42832. buffer: buffer,
  42833. type: type,
  42834. bytesPerElement: array.BYTES_PER_ELEMENT,
  42835. version: attribute.version,
  42836. size: size
  42837. };
  42838. }
  42839. function updateBuffer( buffer, attribute, bufferType ) {
  42840. const array = attribute.array;
  42841. const updateRanges = attribute.updateRanges;
  42842. gl.bindBuffer( bufferType, buffer );
  42843. if ( updateRanges.length === 0 ) {
  42844. // Not using update ranges
  42845. gl.bufferSubData( bufferType, 0, array );
  42846. } else {
  42847. // Before applying update ranges, we merge any adjacent / overlapping
  42848. // ranges to reduce load on `gl.bufferSubData`. Empirically, this has led
  42849. // to performance improvements for applications which make heavy use of
  42850. // update ranges. Likely due to GPU command overhead.
  42851. //
  42852. // Note that to reduce garbage collection between frames, we merge the
  42853. // update ranges in-place. This is safe because this method will clear the
  42854. // update ranges once updated.
  42855. updateRanges.sort( ( a, b ) => a.start - b.start );
  42856. // To merge the update ranges in-place, we work from left to right in the
  42857. // existing updateRanges array, merging ranges. This may result in a final
  42858. // array which is smaller than the original. This index tracks the last
  42859. // index representing a merged range, any data after this index can be
  42860. // trimmed once the merge algorithm is completed.
  42861. let mergeIndex = 0;
  42862. for ( let i = 1; i < updateRanges.length; i ++ ) {
  42863. const previousRange = updateRanges[ mergeIndex ];
  42864. const range = updateRanges[ i ];
  42865. // We add one here to merge adjacent ranges. This is safe because ranges
  42866. // operate over positive integers.
  42867. if ( range.start <= previousRange.start + previousRange.count + 1 ) {
  42868. previousRange.count = Math.max(
  42869. previousRange.count,
  42870. range.start + range.count - previousRange.start
  42871. );
  42872. } else {
  42873. ++ mergeIndex;
  42874. updateRanges[ mergeIndex ] = range;
  42875. }
  42876. }
  42877. // Trim the array to only contain the merged ranges.
  42878. updateRanges.length = mergeIndex + 1;
  42879. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42880. const range = updateRanges[ i ];
  42881. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42882. array, range.start, range.count );
  42883. }
  42884. attribute.clearUpdateRanges();
  42885. }
  42886. attribute.onUploadCallback();
  42887. }
  42888. //
  42889. function get( attribute ) {
  42890. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42891. return buffers.get( attribute );
  42892. }
  42893. function remove( attribute ) {
  42894. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42895. const data = buffers.get( attribute );
  42896. if ( data ) {
  42897. gl.deleteBuffer( data.buffer );
  42898. buffers.delete( attribute );
  42899. }
  42900. }
  42901. function update( attribute, bufferType ) {
  42902. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  42903. if ( attribute.isGLBufferAttribute ) {
  42904. const cached = buffers.get( attribute );
  42905. if ( ! cached || cached.version < attribute.version ) {
  42906. buffers.set( attribute, {
  42907. buffer: attribute.buffer,
  42908. type: attribute.type,
  42909. bytesPerElement: attribute.elementSize,
  42910. version: attribute.version
  42911. } );
  42912. }
  42913. return;
  42914. }
  42915. const data = buffers.get( attribute );
  42916. if ( data === undefined ) {
  42917. buffers.set( attribute, createBuffer( attribute, bufferType ) );
  42918. } else if ( data.version < attribute.version ) {
  42919. if ( data.size !== attribute.array.byteLength ) {
  42920. 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.' );
  42921. }
  42922. updateBuffer( data.buffer, attribute, bufferType );
  42923. data.version = attribute.version;
  42924. }
  42925. }
  42926. return {
  42927. get: get,
  42928. remove: remove,
  42929. update: update
  42930. };
  42931. }
  42932. var alphahash_fragment = "#ifdef USE_ALPHAHASH\n\tif ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard;\n#endif";
  42933. 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";
  42934. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g;\n#endif";
  42935. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif";
  42936. 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";
  42937. var alphatest_pars_fragment = "#ifdef USE_ALPHATEST\n\tuniform float alphaTest;\n#endif";
  42938. 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";
  42939. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  42940. 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";
  42941. var batching_vertex = "#ifdef USE_BATCHING\n\tmat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) );\n#endif";
  42942. var begin_vertex = "vec3 transformed = vec3( position );\n#ifdef USE_ALPHAHASH\n\tvPosition = vec3( position );\n#endif";
  42943. var beginnormal_vertex = "vec3 objectNormal = vec3( normal );\n#ifdef USE_TANGENT\n\tvec3 objectTangent = vec3( tangent.xyz );\n#endif";
  42944. 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";
  42945. 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";
  42946. 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";
  42947. 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";
  42948. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif";
  42949. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvarying vec3 vClipPosition;\n#endif";
  42950. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0\n\tvClipPosition = - mvPosition.xyz;\n#endif";
  42951. var color_fragment = "#if defined( USE_COLOR_ALPHA )\n\tdiffuseColor *= vColor;\n#elif defined( USE_COLOR )\n\tdiffuseColor.rgb *= vColor;\n#endif";
  42952. var color_pars_fragment = "#if defined( USE_COLOR_ALPHA )\n\tvarying vec4 vColor;\n#elif defined( USE_COLOR )\n\tvarying vec3 vColor;\n#endif";
  42953. 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";
  42954. 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";
  42955. 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";
  42956. 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";
  42957. 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";
  42958. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif";
  42959. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias );\n#endif";
  42960. 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";
  42961. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif";
  42962. var colorspace_fragment = "gl_FragColor = linearToOutputTexel( gl_FragColor );";
  42963. 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}";
  42964. 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";
  42965. 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";
  42966. 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";
  42967. 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";
  42968. 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";
  42969. var fog_vertex = "#ifdef USE_FOG\n\tvFogDepth = - mvPosition.z;\n#endif";
  42970. var fog_pars_vertex = "#ifdef USE_FOG\n\tvarying float vFogDepth;\n#endif";
  42971. 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";
  42972. 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";
  42973. 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}";
  42974. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  42975. var lights_lambert_fragment = "LambertMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularStrength = specularStrength;";
  42976. 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";
  42977. 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";
  42978. 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";
  42979. var lights_toon_fragment = "ToonMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;";
  42980. 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";
  42981. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;";
  42982. 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";
  42983. 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.07, 1.0 );\n\t#ifdef USE_SHEEN_ROUGHNESSMAP\n\t\tmaterial.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a;\n\t#endif\n#endif\n#ifdef USE_ANISOTROPY\n\t#ifdef USE_ANISOTROPYMAP\n\t\tmat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x );\n\t\tvec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb;\n\t\tvec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b;\n\t#else\n\t\tvec2 anisotropyV = anisotropyVector;\n\t#endif\n\tmaterial.anisotropy = length( anisotropyV );\n\tif( material.anisotropy == 0.0 ) {\n\t\tanisotropyV = vec2( 1.0, 0.0 );\n\t} else {\n\t\tanisotropyV /= material.anisotropy;\n\t\tmaterial.anisotropy = saturate( material.anisotropy );\n\t}\n\tmaterial.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );\n\tmaterial.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y;\n\tmaterial.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y;\n#endif";
  42984. 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 a = roughness < 0.25 ? -339.2 * r2 + 161.4 * roughness - 25.9 : -8.48 * r2 + 14.3 * roughness - 9.95;\n\tfloat b = roughness < 0.25 ? 44.0 * r2 - 23.7 * roughness + 3.26 : 1.97 * r2 - 3.27 * roughness + 0.72;\n\tfloat DG = exp( a * dotNV + b ) + ( roughness < 0.25 ? 0.0 : 0.1 * ( roughness - 0.25 ) );\n\treturn saturate( DG * RECIPROCAL_PI );\n}\nvec2 DFGApprox( const in vec3 normal, const in vec3 viewDir, const in float roughness ) {\n\tfloat dotNV = saturate( dot( normal, viewDir ) );\n\tvec2 uv = vec2( roughness, dotNV );\n\treturn texture2D( dfgLUT, uv ).rg;\n}\nvec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) {\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\treturn specularColor * fab.x + specularF90 * fab.y;\n}\n#ifdef USE_IRIDESCENCE\nvoid computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#else\nvoid computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) {\n#endif\n\tvec2 fab = DFGApprox( normal, viewDir, roughness );\n\t#ifdef USE_IRIDESCENCE\n\t\tvec3 Fr = mix( specularColor, iridescenceF0, iridescence );\n\t#else\n\t\tvec3 Fr = specularColor;\n\t#endif\n\tvec3 FssEss = Fr * fab.x + specularF90 * fab.y;\n\tfloat Ess = fab.x + fab.y;\n\tfloat Ems = 1.0 - Ess;\n\tvec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619;\tvec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg );\n\tsingleScatter += FssEss;\n\tmultiScatter += Fms * Ems;\n}\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 = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNV * dotNV), 0.0, dotNV), material.roughness );\n\tvec2 dfgL = DFGApprox( vec3(0.0, 0.0, 1.0), vec3(sqrt(1.0 - dotNL * dotNL), 0.0, dotNL), material.roughness );\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\t\tsheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness );\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\treflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\t#ifdef USE_CLEARCOAT\n\t\tclearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness );\n\t#endif\n\t#ifdef USE_SHEEN\n\t\tsheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness );\n\t#endif\n\tvec3 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\treflectedLight.indirectSpecular += radiance * singleScattering;\n\treflectedLight.indirectSpecular += multiScattering * cosineWeightedIrradiance;\n\treflectedLight.indirectDiffuse += diffuse * cosineWeightedIrradiance;\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}";
  42985. 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";
  42986. 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";
  42987. 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";
  42988. 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";
  42989. var logdepthbuf_pars_fragment = "#if defined( USE_LOGARITHMIC_DEPTH_BUFFER )\n\tuniform float logDepthBufFC;\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42990. var logdepthbuf_pars_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvarying float vFragDepth;\n\tvarying float vIsPerspective;\n#endif";
  42991. var logdepthbuf_vertex = "#ifdef USE_LOGARITHMIC_DEPTH_BUFFER\n\tvFragDepth = 1.0 + gl_Position.w;\n\tvIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) );\n#endif";
  42992. 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";
  42993. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif";
  42994. 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";
  42995. 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";
  42996. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv );\n\tmetalnessFactor *= texelMetalness.b;\n#endif";
  42997. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  42998. 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";
  42999. 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";
  43000. 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";
  43001. 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";
  43002. 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";
  43003. 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;";
  43004. 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";
  43005. 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";
  43006. 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";
  43007. 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";
  43008. 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";
  43009. var clearcoat_normal_fragment_begin = "#ifdef USE_CLEARCOAT\n\tvec3 clearcoatNormal = nonPerturbedNormal;\n#endif";
  43010. 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";
  43011. 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";
  43012. var iridescence_pars_fragment = "#ifdef USE_IRIDESCENCEMAP\n\tuniform sampler2D iridescenceMap;\n#endif\n#ifdef USE_IRIDESCENCE_THICKNESSMAP\n\tuniform sampler2D iridescenceThicknessMap;\n#endif";
  43013. 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 );";
  43014. 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}";
  43015. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif";
  43016. 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;";
  43017. var dithering_fragment = "#ifdef DITHERING\n\tgl_FragColor.rgb = dithering( gl_FragColor.rgb );\n#endif";
  43018. 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";
  43019. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv );\n\troughnessFactor *= texelRoughness.g;\n#endif";
  43020. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  43021. 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 ) / sqrt( 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";
  43022. 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";
  43023. 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";
  43024. 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}";
  43025. 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";
  43026. 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";
  43027. 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";
  43028. 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";
  43029. 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";
  43030. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  43031. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n\tgl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif";
  43032. 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; }";
  43033. 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";
  43034. 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";
  43035. 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";
  43036. 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";
  43037. 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";
  43038. 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";
  43039. 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}";
  43040. 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}";
  43041. 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}";
  43042. 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}";
  43043. 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}";
  43044. 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}";
  43045. 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}";
  43046. 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#elif DEPTH_PACKING == 3204\n\t\tgl_FragColor = vec4( vec3( fragCoordZ ), 1.0 );\n\t#endif\n}";
  43047. 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}";
  43048. 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}";
  43049. 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}";
  43050. 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}";
  43051. 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}";
  43052. 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}";
  43053. 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}";
  43054. 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}";
  43055. 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}";
  43056. 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}";
  43057. 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}";
  43058. 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}";
  43059. 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}";
  43060. 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}";
  43061. 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}";
  43062. 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}";
  43063. 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}";
  43064. 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\t\tfloat sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );\n\t\toutgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;\n\t#endif\n\t#ifdef USE_CLEARCOAT\n\t\tfloat dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );\n\t\tvec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );\n\t\toutgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;\n\t#endif\n\t#include <opaque_fragment>\n\t#include <tonemapping_fragment>\n\t#include <colorspace_fragment>\n\t#include <fog_fragment>\n\t#include <premultiplied_alpha_fragment>\n\t#include <dithering_fragment>\n}";
  43065. 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}";
  43066. 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}";
  43067. 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}";
  43068. 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}";
  43069. 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}";
  43070. 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}";
  43071. 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}";
  43072. 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}";
  43073. const ShaderChunk = {
  43074. alphahash_fragment: alphahash_fragment,
  43075. alphahash_pars_fragment: alphahash_pars_fragment,
  43076. alphamap_fragment: alphamap_fragment,
  43077. alphamap_pars_fragment: alphamap_pars_fragment,
  43078. alphatest_fragment: alphatest_fragment,
  43079. alphatest_pars_fragment: alphatest_pars_fragment,
  43080. aomap_fragment: aomap_fragment,
  43081. aomap_pars_fragment: aomap_pars_fragment,
  43082. batching_pars_vertex: batching_pars_vertex,
  43083. batching_vertex: batching_vertex,
  43084. begin_vertex: begin_vertex,
  43085. beginnormal_vertex: beginnormal_vertex,
  43086. bsdfs: bsdfs,
  43087. iridescence_fragment: iridescence_fragment,
  43088. bumpmap_pars_fragment: bumpmap_pars_fragment,
  43089. clipping_planes_fragment: clipping_planes_fragment,
  43090. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  43091. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  43092. clipping_planes_vertex: clipping_planes_vertex,
  43093. color_fragment: color_fragment,
  43094. color_pars_fragment: color_pars_fragment,
  43095. color_pars_vertex: color_pars_vertex,
  43096. color_vertex: color_vertex,
  43097. common: common,
  43098. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  43099. defaultnormal_vertex: defaultnormal_vertex,
  43100. displacementmap_pars_vertex: displacementmap_pars_vertex,
  43101. displacementmap_vertex: displacementmap_vertex,
  43102. emissivemap_fragment: emissivemap_fragment,
  43103. emissivemap_pars_fragment: emissivemap_pars_fragment,
  43104. colorspace_fragment: colorspace_fragment,
  43105. colorspace_pars_fragment: colorspace_pars_fragment,
  43106. envmap_fragment: envmap_fragment,
  43107. envmap_common_pars_fragment: envmap_common_pars_fragment,
  43108. envmap_pars_fragment: envmap_pars_fragment,
  43109. envmap_pars_vertex: envmap_pars_vertex,
  43110. envmap_physical_pars_fragment: envmap_physical_pars_fragment,
  43111. envmap_vertex: envmap_vertex,
  43112. fog_vertex: fog_vertex,
  43113. fog_pars_vertex: fog_pars_vertex,
  43114. fog_fragment: fog_fragment,
  43115. fog_pars_fragment: fog_pars_fragment,
  43116. gradientmap_pars_fragment: gradientmap_pars_fragment,
  43117. lightmap_pars_fragment: lightmap_pars_fragment,
  43118. lights_lambert_fragment: lights_lambert_fragment,
  43119. lights_lambert_pars_fragment: lights_lambert_pars_fragment,
  43120. lights_pars_begin: lights_pars_begin,
  43121. lights_toon_fragment: lights_toon_fragment,
  43122. lights_toon_pars_fragment: lights_toon_pars_fragment,
  43123. lights_phong_fragment: lights_phong_fragment,
  43124. lights_phong_pars_fragment: lights_phong_pars_fragment,
  43125. lights_physical_fragment: lights_physical_fragment,
  43126. lights_physical_pars_fragment: lights_physical_pars_fragment,
  43127. lights_fragment_begin: lights_fragment_begin,
  43128. lights_fragment_maps: lights_fragment_maps,
  43129. lights_fragment_end: lights_fragment_end,
  43130. logdepthbuf_fragment: logdepthbuf_fragment,
  43131. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  43132. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  43133. logdepthbuf_vertex: logdepthbuf_vertex,
  43134. map_fragment: map_fragment,
  43135. map_pars_fragment: map_pars_fragment,
  43136. map_particle_fragment: map_particle_fragment,
  43137. map_particle_pars_fragment: map_particle_pars_fragment,
  43138. metalnessmap_fragment: metalnessmap_fragment,
  43139. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  43140. morphinstance_vertex: morphinstance_vertex,
  43141. morphcolor_vertex: morphcolor_vertex,
  43142. morphnormal_vertex: morphnormal_vertex,
  43143. morphtarget_pars_vertex: morphtarget_pars_vertex,
  43144. morphtarget_vertex: morphtarget_vertex,
  43145. normal_fragment_begin: normal_fragment_begin,
  43146. normal_fragment_maps: normal_fragment_maps,
  43147. normal_pars_fragment: normal_pars_fragment,
  43148. normal_pars_vertex: normal_pars_vertex,
  43149. normal_vertex: normal_vertex,
  43150. normalmap_pars_fragment: normalmap_pars_fragment,
  43151. clearcoat_normal_fragment_begin: clearcoat_normal_fragment_begin,
  43152. clearcoat_normal_fragment_maps: clearcoat_normal_fragment_maps,
  43153. clearcoat_pars_fragment: clearcoat_pars_fragment,
  43154. iridescence_pars_fragment: iridescence_pars_fragment,
  43155. opaque_fragment: opaque_fragment,
  43156. packing: packing,
  43157. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  43158. project_vertex: project_vertex,
  43159. dithering_fragment: dithering_fragment,
  43160. dithering_pars_fragment: dithering_pars_fragment,
  43161. roughnessmap_fragment: roughnessmap_fragment,
  43162. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  43163. shadowmap_pars_fragment: shadowmap_pars_fragment,
  43164. shadowmap_pars_vertex: shadowmap_pars_vertex,
  43165. shadowmap_vertex: shadowmap_vertex,
  43166. shadowmask_pars_fragment: shadowmask_pars_fragment,
  43167. skinbase_vertex: skinbase_vertex,
  43168. skinning_pars_vertex: skinning_pars_vertex,
  43169. skinning_vertex: skinning_vertex,
  43170. skinnormal_vertex: skinnormal_vertex,
  43171. specularmap_fragment: specularmap_fragment,
  43172. specularmap_pars_fragment: specularmap_pars_fragment,
  43173. tonemapping_fragment: tonemapping_fragment,
  43174. tonemapping_pars_fragment: tonemapping_pars_fragment,
  43175. transmission_fragment: transmission_fragment,
  43176. transmission_pars_fragment: transmission_pars_fragment,
  43177. uv_pars_fragment: uv_pars_fragment,
  43178. uv_pars_vertex: uv_pars_vertex,
  43179. uv_vertex: uv_vertex,
  43180. worldpos_vertex: worldpos_vertex,
  43181. background_vert: vertex$h,
  43182. background_frag: fragment$h,
  43183. backgroundCube_vert: vertex$g,
  43184. backgroundCube_frag: fragment$g,
  43185. cube_vert: vertex$f,
  43186. cube_frag: fragment$f,
  43187. depth_vert: vertex$e,
  43188. depth_frag: fragment$e,
  43189. distance_vert: vertex$d,
  43190. distance_frag: fragment$d,
  43191. equirect_vert: vertex$c,
  43192. equirect_frag: fragment$c,
  43193. linedashed_vert: vertex$b,
  43194. linedashed_frag: fragment$b,
  43195. meshbasic_vert: vertex$a,
  43196. meshbasic_frag: fragment$a,
  43197. meshlambert_vert: vertex$9,
  43198. meshlambert_frag: fragment$9,
  43199. meshmatcap_vert: vertex$8,
  43200. meshmatcap_frag: fragment$8,
  43201. meshnormal_vert: vertex$7,
  43202. meshnormal_frag: fragment$7,
  43203. meshphong_vert: vertex$6,
  43204. meshphong_frag: fragment$6,
  43205. meshphysical_vert: vertex$5,
  43206. meshphysical_frag: fragment$5,
  43207. meshtoon_vert: vertex$4,
  43208. meshtoon_frag: fragment$4,
  43209. points_vert: vertex$3,
  43210. points_frag: fragment$3,
  43211. shadow_vert: vertex$2,
  43212. shadow_frag: fragment$2,
  43213. sprite_vert: vertex$1,
  43214. sprite_frag: fragment$1
  43215. };
  43216. // Uniforms library for shared webgl shaders
  43217. const UniformsLib = {
  43218. common: {
  43219. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43220. opacity: { value: 1.0 },
  43221. map: { value: null },
  43222. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43223. alphaMap: { value: null },
  43224. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43225. alphaTest: { value: 0 }
  43226. },
  43227. specularmap: {
  43228. specularMap: { value: null },
  43229. specularMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43230. },
  43231. envmap: {
  43232. envMap: { value: null },
  43233. envMapRotation: { value: /*@__PURE__*/ new Matrix3() },
  43234. flipEnvMap: { value: -1 },
  43235. reflectivity: { value: 1.0 }, // basic, lambert, phong
  43236. ior: { value: 1.5 }, // physical
  43237. refractionRatio: { value: 0.98 }, // basic, lambert, phong
  43238. dfgLUT: { value: null } // DFG LUT for physically-based rendering
  43239. },
  43240. aomap: {
  43241. aoMap: { value: null },
  43242. aoMapIntensity: { value: 1 },
  43243. aoMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43244. },
  43245. lightmap: {
  43246. lightMap: { value: null },
  43247. lightMapIntensity: { value: 1 },
  43248. lightMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43249. },
  43250. bumpmap: {
  43251. bumpMap: { value: null },
  43252. bumpMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43253. bumpScale: { value: 1 }
  43254. },
  43255. normalmap: {
  43256. normalMap: { value: null },
  43257. normalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43258. normalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) }
  43259. },
  43260. displacementmap: {
  43261. displacementMap: { value: null },
  43262. displacementMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43263. displacementScale: { value: 1 },
  43264. displacementBias: { value: 0 }
  43265. },
  43266. emissivemap: {
  43267. emissiveMap: { value: null },
  43268. emissiveMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43269. },
  43270. metalnessmap: {
  43271. metalnessMap: { value: null },
  43272. metalnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43273. },
  43274. roughnessmap: {
  43275. roughnessMap: { value: null },
  43276. roughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() }
  43277. },
  43278. gradientmap: {
  43279. gradientMap: { value: null }
  43280. },
  43281. fog: {
  43282. fogDensity: { value: 0.00025 },
  43283. fogNear: { value: 1 },
  43284. fogFar: { value: 2000 },
  43285. fogColor: { value: /*@__PURE__*/ new Color( 0xffffff ) }
  43286. },
  43287. lights: {
  43288. ambientLightColor: { value: [] },
  43289. lightProbe: { value: [] },
  43290. directionalLights: { value: [], properties: {
  43291. direction: {},
  43292. color: {}
  43293. } },
  43294. directionalLightShadows: { value: [], properties: {
  43295. shadowIntensity: 1,
  43296. shadowBias: {},
  43297. shadowNormalBias: {},
  43298. shadowRadius: {},
  43299. shadowMapSize: {}
  43300. } },
  43301. directionalShadowMap: { value: [] },
  43302. directionalShadowMatrix: { value: [] },
  43303. spotLights: { value: [], properties: {
  43304. color: {},
  43305. position: {},
  43306. direction: {},
  43307. distance: {},
  43308. coneCos: {},
  43309. penumbraCos: {},
  43310. decay: {}
  43311. } },
  43312. spotLightShadows: { value: [], properties: {
  43313. shadowIntensity: 1,
  43314. shadowBias: {},
  43315. shadowNormalBias: {},
  43316. shadowRadius: {},
  43317. shadowMapSize: {}
  43318. } },
  43319. spotLightMap: { value: [] },
  43320. spotShadowMap: { value: [] },
  43321. spotLightMatrix: { value: [] },
  43322. pointLights: { value: [], properties: {
  43323. color: {},
  43324. position: {},
  43325. decay: {},
  43326. distance: {}
  43327. } },
  43328. pointLightShadows: { value: [], properties: {
  43329. shadowIntensity: 1,
  43330. shadowBias: {},
  43331. shadowNormalBias: {},
  43332. shadowRadius: {},
  43333. shadowMapSize: {},
  43334. shadowCameraNear: {},
  43335. shadowCameraFar: {}
  43336. } },
  43337. pointShadowMap: { value: [] },
  43338. pointShadowMatrix: { value: [] },
  43339. hemisphereLights: { value: [], properties: {
  43340. direction: {},
  43341. skyColor: {},
  43342. groundColor: {}
  43343. } },
  43344. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  43345. rectAreaLights: { value: [], properties: {
  43346. color: {},
  43347. position: {},
  43348. width: {},
  43349. height: {}
  43350. } },
  43351. ltc_1: { value: null },
  43352. ltc_2: { value: null }
  43353. },
  43354. points: {
  43355. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43356. opacity: { value: 1.0 },
  43357. size: { value: 1.0 },
  43358. scale: { value: 1.0 },
  43359. map: { value: null },
  43360. alphaMap: { value: null },
  43361. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43362. alphaTest: { value: 0 },
  43363. uvTransform: { value: /*@__PURE__*/ new Matrix3() }
  43364. },
  43365. sprite: {
  43366. diffuse: { value: /*@__PURE__*/ new Color( 0xffffff ) },
  43367. opacity: { value: 1.0 },
  43368. center: { value: /*@__PURE__*/ new Vector2( 0.5, 0.5 ) },
  43369. rotation: { value: 0.0 },
  43370. map: { value: null },
  43371. mapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43372. alphaMap: { value: null },
  43373. alphaMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43374. alphaTest: { value: 0 }
  43375. }
  43376. };
  43377. const ShaderLib = {
  43378. basic: {
  43379. uniforms: /*@__PURE__*/ mergeUniforms( [
  43380. UniformsLib.common,
  43381. UniformsLib.specularmap,
  43382. UniformsLib.envmap,
  43383. UniformsLib.aomap,
  43384. UniformsLib.lightmap,
  43385. UniformsLib.fog
  43386. ] ),
  43387. vertexShader: ShaderChunk.meshbasic_vert,
  43388. fragmentShader: ShaderChunk.meshbasic_frag
  43389. },
  43390. lambert: {
  43391. uniforms: /*@__PURE__*/ mergeUniforms( [
  43392. UniformsLib.common,
  43393. UniformsLib.specularmap,
  43394. UniformsLib.envmap,
  43395. UniformsLib.aomap,
  43396. UniformsLib.lightmap,
  43397. UniformsLib.emissivemap,
  43398. UniformsLib.bumpmap,
  43399. UniformsLib.normalmap,
  43400. UniformsLib.displacementmap,
  43401. UniformsLib.fog,
  43402. UniformsLib.lights,
  43403. {
  43404. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43405. }
  43406. ] ),
  43407. vertexShader: ShaderChunk.meshlambert_vert,
  43408. fragmentShader: ShaderChunk.meshlambert_frag
  43409. },
  43410. phong: {
  43411. uniforms: /*@__PURE__*/ mergeUniforms( [
  43412. UniformsLib.common,
  43413. UniformsLib.specularmap,
  43414. UniformsLib.envmap,
  43415. UniformsLib.aomap,
  43416. UniformsLib.lightmap,
  43417. UniformsLib.emissivemap,
  43418. UniformsLib.bumpmap,
  43419. UniformsLib.normalmap,
  43420. UniformsLib.displacementmap,
  43421. UniformsLib.fog,
  43422. UniformsLib.lights,
  43423. {
  43424. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43425. specular: { value: /*@__PURE__*/ new Color( 0x111111 ) },
  43426. shininess: { value: 30 }
  43427. }
  43428. ] ),
  43429. vertexShader: ShaderChunk.meshphong_vert,
  43430. fragmentShader: ShaderChunk.meshphong_frag
  43431. },
  43432. standard: {
  43433. uniforms: /*@__PURE__*/ mergeUniforms( [
  43434. UniformsLib.common,
  43435. UniformsLib.envmap,
  43436. UniformsLib.aomap,
  43437. UniformsLib.lightmap,
  43438. UniformsLib.emissivemap,
  43439. UniformsLib.bumpmap,
  43440. UniformsLib.normalmap,
  43441. UniformsLib.displacementmap,
  43442. UniformsLib.roughnessmap,
  43443. UniformsLib.metalnessmap,
  43444. UniformsLib.fog,
  43445. UniformsLib.lights,
  43446. {
  43447. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43448. roughness: { value: 1.0 },
  43449. metalness: { value: 0.0 },
  43450. envMapIntensity: { value: 1 }
  43451. }
  43452. ] ),
  43453. vertexShader: ShaderChunk.meshphysical_vert,
  43454. fragmentShader: ShaderChunk.meshphysical_frag
  43455. },
  43456. toon: {
  43457. uniforms: /*@__PURE__*/ mergeUniforms( [
  43458. UniformsLib.common,
  43459. UniformsLib.aomap,
  43460. UniformsLib.lightmap,
  43461. UniformsLib.emissivemap,
  43462. UniformsLib.bumpmap,
  43463. UniformsLib.normalmap,
  43464. UniformsLib.displacementmap,
  43465. UniformsLib.gradientmap,
  43466. UniformsLib.fog,
  43467. UniformsLib.lights,
  43468. {
  43469. emissive: { value: /*@__PURE__*/ new Color( 0x000000 ) }
  43470. }
  43471. ] ),
  43472. vertexShader: ShaderChunk.meshtoon_vert,
  43473. fragmentShader: ShaderChunk.meshtoon_frag
  43474. },
  43475. matcap: {
  43476. uniforms: /*@__PURE__*/ mergeUniforms( [
  43477. UniformsLib.common,
  43478. UniformsLib.bumpmap,
  43479. UniformsLib.normalmap,
  43480. UniformsLib.displacementmap,
  43481. UniformsLib.fog,
  43482. {
  43483. matcap: { value: null }
  43484. }
  43485. ] ),
  43486. vertexShader: ShaderChunk.meshmatcap_vert,
  43487. fragmentShader: ShaderChunk.meshmatcap_frag
  43488. },
  43489. points: {
  43490. uniforms: /*@__PURE__*/ mergeUniforms( [
  43491. UniformsLib.points,
  43492. UniformsLib.fog
  43493. ] ),
  43494. vertexShader: ShaderChunk.points_vert,
  43495. fragmentShader: ShaderChunk.points_frag
  43496. },
  43497. dashed: {
  43498. uniforms: /*@__PURE__*/ mergeUniforms( [
  43499. UniformsLib.common,
  43500. UniformsLib.fog,
  43501. {
  43502. scale: { value: 1 },
  43503. dashSize: { value: 1 },
  43504. totalSize: { value: 2 }
  43505. }
  43506. ] ),
  43507. vertexShader: ShaderChunk.linedashed_vert,
  43508. fragmentShader: ShaderChunk.linedashed_frag
  43509. },
  43510. depth: {
  43511. uniforms: /*@__PURE__*/ mergeUniforms( [
  43512. UniformsLib.common,
  43513. UniformsLib.displacementmap
  43514. ] ),
  43515. vertexShader: ShaderChunk.depth_vert,
  43516. fragmentShader: ShaderChunk.depth_frag
  43517. },
  43518. normal: {
  43519. uniforms: /*@__PURE__*/ mergeUniforms( [
  43520. UniformsLib.common,
  43521. UniformsLib.bumpmap,
  43522. UniformsLib.normalmap,
  43523. UniformsLib.displacementmap,
  43524. {
  43525. opacity: { value: 1.0 }
  43526. }
  43527. ] ),
  43528. vertexShader: ShaderChunk.meshnormal_vert,
  43529. fragmentShader: ShaderChunk.meshnormal_frag
  43530. },
  43531. sprite: {
  43532. uniforms: /*@__PURE__*/ mergeUniforms( [
  43533. UniformsLib.sprite,
  43534. UniformsLib.fog
  43535. ] ),
  43536. vertexShader: ShaderChunk.sprite_vert,
  43537. fragmentShader: ShaderChunk.sprite_frag
  43538. },
  43539. background: {
  43540. uniforms: {
  43541. uvTransform: { value: /*@__PURE__*/ new Matrix3() },
  43542. t2D: { value: null },
  43543. backgroundIntensity: { value: 1 }
  43544. },
  43545. vertexShader: ShaderChunk.background_vert,
  43546. fragmentShader: ShaderChunk.background_frag
  43547. },
  43548. backgroundCube: {
  43549. uniforms: {
  43550. envMap: { value: null },
  43551. flipEnvMap: { value: -1 },
  43552. backgroundBlurriness: { value: 0 },
  43553. backgroundIntensity: { value: 1 },
  43554. backgroundRotation: { value: /*@__PURE__*/ new Matrix3() }
  43555. },
  43556. vertexShader: ShaderChunk.backgroundCube_vert,
  43557. fragmentShader: ShaderChunk.backgroundCube_frag
  43558. },
  43559. cube: {
  43560. uniforms: {
  43561. tCube: { value: null },
  43562. tFlip: { value: -1 },
  43563. opacity: { value: 1.0 }
  43564. },
  43565. vertexShader: ShaderChunk.cube_vert,
  43566. fragmentShader: ShaderChunk.cube_frag
  43567. },
  43568. equirect: {
  43569. uniforms: {
  43570. tEquirect: { value: null },
  43571. },
  43572. vertexShader: ShaderChunk.equirect_vert,
  43573. fragmentShader: ShaderChunk.equirect_frag
  43574. },
  43575. distance: {
  43576. uniforms: /*@__PURE__*/ mergeUniforms( [
  43577. UniformsLib.common,
  43578. UniformsLib.displacementmap,
  43579. {
  43580. referencePosition: { value: /*@__PURE__*/ new Vector3() },
  43581. nearDistance: { value: 1 },
  43582. farDistance: { value: 1000 }
  43583. }
  43584. ] ),
  43585. vertexShader: ShaderChunk.distance_vert,
  43586. fragmentShader: ShaderChunk.distance_frag
  43587. },
  43588. shadow: {
  43589. uniforms: /*@__PURE__*/ mergeUniforms( [
  43590. UniformsLib.lights,
  43591. UniformsLib.fog,
  43592. {
  43593. color: { value: /*@__PURE__*/ new Color( 0x00000 ) },
  43594. opacity: { value: 1.0 }
  43595. },
  43596. ] ),
  43597. vertexShader: ShaderChunk.shadow_vert,
  43598. fragmentShader: ShaderChunk.shadow_frag
  43599. }
  43600. };
  43601. ShaderLib.physical = {
  43602. uniforms: /*@__PURE__*/ mergeUniforms( [
  43603. ShaderLib.standard.uniforms,
  43604. {
  43605. clearcoat: { value: 0 },
  43606. clearcoatMap: { value: null },
  43607. clearcoatMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43608. clearcoatNormalMap: { value: null },
  43609. clearcoatNormalMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43610. clearcoatNormalScale: { value: /*@__PURE__*/ new Vector2( 1, 1 ) },
  43611. clearcoatRoughness: { value: 0 },
  43612. clearcoatRoughnessMap: { value: null },
  43613. clearcoatRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43614. dispersion: { value: 0 },
  43615. iridescence: { value: 0 },
  43616. iridescenceMap: { value: null },
  43617. iridescenceMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43618. iridescenceIOR: { value: 1.3 },
  43619. iridescenceThicknessMinimum: { value: 100 },
  43620. iridescenceThicknessMaximum: { value: 400 },
  43621. iridescenceThicknessMap: { value: null },
  43622. iridescenceThicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43623. sheen: { value: 0 },
  43624. sheenColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43625. sheenColorMap: { value: null },
  43626. sheenColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43627. sheenRoughness: { value: 1 },
  43628. sheenRoughnessMap: { value: null },
  43629. sheenRoughnessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43630. transmission: { value: 0 },
  43631. transmissionMap: { value: null },
  43632. transmissionMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43633. transmissionSamplerSize: { value: /*@__PURE__*/ new Vector2() },
  43634. transmissionSamplerMap: { value: null },
  43635. thickness: { value: 0 },
  43636. thicknessMap: { value: null },
  43637. thicknessMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43638. attenuationDistance: { value: 0 },
  43639. attenuationColor: { value: /*@__PURE__*/ new Color( 0x000000 ) },
  43640. specularColor: { value: /*@__PURE__*/ new Color( 1, 1, 1 ) },
  43641. specularColorMap: { value: null },
  43642. specularColorMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43643. specularIntensity: { value: 1 },
  43644. specularIntensityMap: { value: null },
  43645. specularIntensityMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43646. anisotropyVector: { value: /*@__PURE__*/ new Vector2() },
  43647. anisotropyMap: { value: null },
  43648. anisotropyMapTransform: { value: /*@__PURE__*/ new Matrix3() },
  43649. }
  43650. ] ),
  43651. vertexShader: ShaderChunk.meshphysical_vert,
  43652. fragmentShader: ShaderChunk.meshphysical_frag
  43653. };
  43654. const _rgb = { r: 0, b: 0, g: 0 };
  43655. const _e1$1 = /*@__PURE__*/ new Euler();
  43656. const _m1$1 = /*@__PURE__*/ new Matrix4();
  43657. function WebGLBackground( renderer, cubemaps, cubeuvmaps, state, objects, alpha, premultipliedAlpha ) {
  43658. const clearColor = new Color( 0x000000 );
  43659. let clearAlpha = alpha === true ? 0 : 1;
  43660. let planeMesh;
  43661. let boxMesh;
  43662. let currentBackground = null;
  43663. let currentBackgroundVersion = 0;
  43664. let currentTonemapping = null;
  43665. function getBackground( scene ) {
  43666. let background = scene.isScene === true ? scene.background : null;
  43667. if ( background && background.isTexture ) {
  43668. const usePMREM = scene.backgroundBlurriness > 0; // use PMREM if the user wants to blur the background
  43669. background = ( usePMREM ? cubeuvmaps : cubemaps ).get( background );
  43670. }
  43671. return background;
  43672. }
  43673. function render( scene ) {
  43674. let forceClear = false;
  43675. const background = getBackground( scene );
  43676. if ( background === null ) {
  43677. setClear( clearColor, clearAlpha );
  43678. } else if ( background && background.isColor ) {
  43679. setClear( background, 1 );
  43680. forceClear = true;
  43681. }
  43682. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  43683. if ( environmentBlendMode === 'additive' ) {
  43684. state.buffers.color.setClear( 0, 0, 0, 1, premultipliedAlpha );
  43685. } else if ( environmentBlendMode === 'alpha-blend' ) {
  43686. state.buffers.color.setClear( 0, 0, 0, 0, premultipliedAlpha );
  43687. }
  43688. if ( renderer.autoClear || forceClear ) {
  43689. // buffers might not be writable which is required to ensure a correct clear
  43690. state.buffers.depth.setTest( true );
  43691. state.buffers.depth.setMask( true );
  43692. state.buffers.color.setMask( true );
  43693. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  43694. }
  43695. }
  43696. function addToRenderList( renderList, scene ) {
  43697. const background = getBackground( scene );
  43698. if ( background && ( background.isCubeTexture || background.mapping === CubeUVReflectionMapping ) ) {
  43699. if ( boxMesh === undefined ) {
  43700. boxMesh = new Mesh(
  43701. new BoxGeometry( 1, 1, 1 ),
  43702. new ShaderMaterial( {
  43703. name: 'BackgroundCubeMaterial',
  43704. uniforms: cloneUniforms( ShaderLib.backgroundCube.uniforms ),
  43705. vertexShader: ShaderLib.backgroundCube.vertexShader,
  43706. fragmentShader: ShaderLib.backgroundCube.fragmentShader,
  43707. side: BackSide,
  43708. depthTest: false,
  43709. depthWrite: false,
  43710. fog: false,
  43711. allowOverride: false
  43712. } )
  43713. );
  43714. boxMesh.geometry.deleteAttribute( 'normal' );
  43715. boxMesh.geometry.deleteAttribute( 'uv' );
  43716. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  43717. this.matrixWorld.copyPosition( camera.matrixWorld );
  43718. };
  43719. // add "envMap" material property so the renderer can evaluate it like for built-in materials
  43720. Object.defineProperty( boxMesh.material, 'envMap', {
  43721. get: function () {
  43722. return this.uniforms.envMap.value;
  43723. }
  43724. } );
  43725. objects.update( boxMesh );
  43726. }
  43727. _e1$1.copy( scene.backgroundRotation );
  43728. // accommodate left-handed frame
  43729. _e1$1.x *= -1; _e1$1.y *= -1; _e1$1.z *= -1;
  43730. if ( background.isCubeTexture && background.isRenderTargetTexture === false ) {
  43731. // environment maps which are not cube render targets or PMREMs follow a different convention
  43732. _e1$1.y *= -1;
  43733. _e1$1.z *= -1;
  43734. }
  43735. boxMesh.material.uniforms.envMap.value = background;
  43736. boxMesh.material.uniforms.flipEnvMap.value = ( background.isCubeTexture && background.isRenderTargetTexture === false ) ? -1 : 1;
  43737. boxMesh.material.uniforms.backgroundBlurriness.value = scene.backgroundBlurriness;
  43738. boxMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43739. boxMesh.material.uniforms.backgroundRotation.value.setFromMatrix4( _m1$1.makeRotationFromEuler( _e1$1 ) );
  43740. boxMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43741. if ( currentBackground !== background ||
  43742. currentBackgroundVersion !== background.version ||
  43743. currentTonemapping !== renderer.toneMapping ) {
  43744. boxMesh.material.needsUpdate = true;
  43745. currentBackground = background;
  43746. currentBackgroundVersion = background.version;
  43747. currentTonemapping = renderer.toneMapping;
  43748. }
  43749. boxMesh.layers.enableAll();
  43750. // push to the pre-sorted opaque render list
  43751. renderList.unshift( boxMesh, boxMesh.geometry, boxMesh.material, 0, 0, null );
  43752. } else if ( background && background.isTexture ) {
  43753. if ( planeMesh === undefined ) {
  43754. planeMesh = new Mesh(
  43755. new PlaneGeometry( 2, 2 ),
  43756. new ShaderMaterial( {
  43757. name: 'BackgroundMaterial',
  43758. uniforms: cloneUniforms( ShaderLib.background.uniforms ),
  43759. vertexShader: ShaderLib.background.vertexShader,
  43760. fragmentShader: ShaderLib.background.fragmentShader,
  43761. side: FrontSide,
  43762. depthTest: false,
  43763. depthWrite: false,
  43764. fog: false,
  43765. allowOverride: false
  43766. } )
  43767. );
  43768. planeMesh.geometry.deleteAttribute( 'normal' );
  43769. // add "map" material property so the renderer can evaluate it like for built-in materials
  43770. Object.defineProperty( planeMesh.material, 'map', {
  43771. get: function () {
  43772. return this.uniforms.t2D.value;
  43773. }
  43774. } );
  43775. objects.update( planeMesh );
  43776. }
  43777. planeMesh.material.uniforms.t2D.value = background;
  43778. planeMesh.material.uniforms.backgroundIntensity.value = scene.backgroundIntensity;
  43779. planeMesh.material.toneMapped = ColorManagement.getTransfer( background.colorSpace ) !== SRGBTransfer;
  43780. if ( background.matrixAutoUpdate === true ) {
  43781. background.updateMatrix();
  43782. }
  43783. planeMesh.material.uniforms.uvTransform.value.copy( background.matrix );
  43784. if ( currentBackground !== background ||
  43785. currentBackgroundVersion !== background.version ||
  43786. currentTonemapping !== renderer.toneMapping ) {
  43787. planeMesh.material.needsUpdate = true;
  43788. currentBackground = background;
  43789. currentBackgroundVersion = background.version;
  43790. currentTonemapping = renderer.toneMapping;
  43791. }
  43792. planeMesh.layers.enableAll();
  43793. // push to the pre-sorted opaque render list
  43794. renderList.unshift( planeMesh, planeMesh.geometry, planeMesh.material, 0, 0, null );
  43795. }
  43796. }
  43797. function setClear( color, alpha ) {
  43798. color.getRGB( _rgb, getUnlitUniformColorSpace( renderer ) );
  43799. state.buffers.color.setClear( _rgb.r, _rgb.g, _rgb.b, alpha, premultipliedAlpha );
  43800. }
  43801. function dispose() {
  43802. if ( boxMesh !== undefined ) {
  43803. boxMesh.geometry.dispose();
  43804. boxMesh.material.dispose();
  43805. boxMesh = undefined;
  43806. }
  43807. if ( planeMesh !== undefined ) {
  43808. planeMesh.geometry.dispose();
  43809. planeMesh.material.dispose();
  43810. planeMesh = undefined;
  43811. }
  43812. }
  43813. return {
  43814. getClearColor: function () {
  43815. return clearColor;
  43816. },
  43817. setClearColor: function ( color, alpha = 1 ) {
  43818. clearColor.set( color );
  43819. clearAlpha = alpha;
  43820. setClear( clearColor, clearAlpha );
  43821. },
  43822. getClearAlpha: function () {
  43823. return clearAlpha;
  43824. },
  43825. setClearAlpha: function ( alpha ) {
  43826. clearAlpha = alpha;
  43827. setClear( clearColor, clearAlpha );
  43828. },
  43829. render: render,
  43830. addToRenderList: addToRenderList,
  43831. dispose: dispose
  43832. };
  43833. }
  43834. function WebGLBindingStates( gl, attributes ) {
  43835. const maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  43836. const bindingStates = {};
  43837. const defaultState = createBindingState( null );
  43838. let currentState = defaultState;
  43839. let forceUpdate = false;
  43840. function setup( object, material, program, geometry, index ) {
  43841. let updateBuffers = false;
  43842. const state = getBindingState( geometry, program, material );
  43843. if ( currentState !== state ) {
  43844. currentState = state;
  43845. bindVertexArrayObject( currentState.object );
  43846. }
  43847. updateBuffers = needsUpdate( object, geometry, program, index );
  43848. if ( updateBuffers ) saveCache( object, geometry, program, index );
  43849. if ( index !== null ) {
  43850. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  43851. }
  43852. if ( updateBuffers || forceUpdate ) {
  43853. forceUpdate = false;
  43854. setupVertexAttributes( object, material, program, geometry );
  43855. if ( index !== null ) {
  43856. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, attributes.get( index ).buffer );
  43857. }
  43858. }
  43859. }
  43860. function createVertexArrayObject() {
  43861. return gl.createVertexArray();
  43862. }
  43863. function bindVertexArrayObject( vao ) {
  43864. return gl.bindVertexArray( vao );
  43865. }
  43866. function deleteVertexArrayObject( vao ) {
  43867. return gl.deleteVertexArray( vao );
  43868. }
  43869. function getBindingState( geometry, program, material ) {
  43870. const wireframe = ( material.wireframe === true );
  43871. let programMap = bindingStates[ geometry.id ];
  43872. if ( programMap === undefined ) {
  43873. programMap = {};
  43874. bindingStates[ geometry.id ] = programMap;
  43875. }
  43876. let stateMap = programMap[ program.id ];
  43877. if ( stateMap === undefined ) {
  43878. stateMap = {};
  43879. programMap[ program.id ] = stateMap;
  43880. }
  43881. let state = stateMap[ wireframe ];
  43882. if ( state === undefined ) {
  43883. state = createBindingState( createVertexArrayObject() );
  43884. stateMap[ wireframe ] = state;
  43885. }
  43886. return state;
  43887. }
  43888. function createBindingState( vao ) {
  43889. const newAttributes = [];
  43890. const enabledAttributes = [];
  43891. const attributeDivisors = [];
  43892. for ( let i = 0; i < maxVertexAttributes; i ++ ) {
  43893. newAttributes[ i ] = 0;
  43894. enabledAttributes[ i ] = 0;
  43895. attributeDivisors[ i ] = 0;
  43896. }
  43897. return {
  43898. // for backward compatibility on non-VAO support browser
  43899. geometry: null,
  43900. program: null,
  43901. wireframe: false,
  43902. newAttributes: newAttributes,
  43903. enabledAttributes: enabledAttributes,
  43904. attributeDivisors: attributeDivisors,
  43905. object: vao,
  43906. attributes: {},
  43907. index: null
  43908. };
  43909. }
  43910. function needsUpdate( object, geometry, program, index ) {
  43911. const cachedAttributes = currentState.attributes;
  43912. const geometryAttributes = geometry.attributes;
  43913. let attributesNum = 0;
  43914. const programAttributes = program.getAttributes();
  43915. for ( const name in programAttributes ) {
  43916. const programAttribute = programAttributes[ name ];
  43917. if ( programAttribute.location >= 0 ) {
  43918. const cachedAttribute = cachedAttributes[ name ];
  43919. let geometryAttribute = geometryAttributes[ name ];
  43920. if ( geometryAttribute === undefined ) {
  43921. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  43922. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  43923. }
  43924. if ( cachedAttribute === undefined ) return true;
  43925. if ( cachedAttribute.attribute !== geometryAttribute ) return true;
  43926. if ( geometryAttribute && cachedAttribute.data !== geometryAttribute.data ) return true;
  43927. attributesNum ++;
  43928. }
  43929. }
  43930. if ( currentState.attributesNum !== attributesNum ) return true;
  43931. if ( currentState.index !== index ) return true;
  43932. return false;
  43933. }
  43934. function saveCache( object, geometry, program, index ) {
  43935. const cache = {};
  43936. const attributes = geometry.attributes;
  43937. let attributesNum = 0;
  43938. const programAttributes = program.getAttributes();
  43939. for ( const name in programAttributes ) {
  43940. const programAttribute = programAttributes[ name ];
  43941. if ( programAttribute.location >= 0 ) {
  43942. let attribute = attributes[ name ];
  43943. if ( attribute === undefined ) {
  43944. if ( name === 'instanceMatrix' && object.instanceMatrix ) attribute = object.instanceMatrix;
  43945. if ( name === 'instanceColor' && object.instanceColor ) attribute = object.instanceColor;
  43946. }
  43947. const data = {};
  43948. data.attribute = attribute;
  43949. if ( attribute && attribute.data ) {
  43950. data.data = attribute.data;
  43951. }
  43952. cache[ name ] = data;
  43953. attributesNum ++;
  43954. }
  43955. }
  43956. currentState.attributes = cache;
  43957. currentState.attributesNum = attributesNum;
  43958. currentState.index = index;
  43959. }
  43960. function initAttributes() {
  43961. const newAttributes = currentState.newAttributes;
  43962. for ( let i = 0, il = newAttributes.length; i < il; i ++ ) {
  43963. newAttributes[ i ] = 0;
  43964. }
  43965. }
  43966. function enableAttribute( attribute ) {
  43967. enableAttributeAndDivisor( attribute, 0 );
  43968. }
  43969. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  43970. const newAttributes = currentState.newAttributes;
  43971. const enabledAttributes = currentState.enabledAttributes;
  43972. const attributeDivisors = currentState.attributeDivisors;
  43973. newAttributes[ attribute ] = 1;
  43974. if ( enabledAttributes[ attribute ] === 0 ) {
  43975. gl.enableVertexAttribArray( attribute );
  43976. enabledAttributes[ attribute ] = 1;
  43977. }
  43978. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  43979. gl.vertexAttribDivisor( attribute, meshPerAttribute );
  43980. attributeDivisors[ attribute ] = meshPerAttribute;
  43981. }
  43982. }
  43983. function disableUnusedAttributes() {
  43984. const newAttributes = currentState.newAttributes;
  43985. const enabledAttributes = currentState.enabledAttributes;
  43986. for ( let i = 0, il = enabledAttributes.length; i < il; i ++ ) {
  43987. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  43988. gl.disableVertexAttribArray( i );
  43989. enabledAttributes[ i ] = 0;
  43990. }
  43991. }
  43992. }
  43993. function vertexAttribPointer( index, size, type, normalized, stride, offset, integer ) {
  43994. if ( integer === true ) {
  43995. gl.vertexAttribIPointer( index, size, type, stride, offset );
  43996. } else {
  43997. gl.vertexAttribPointer( index, size, type, normalized, stride, offset );
  43998. }
  43999. }
  44000. function setupVertexAttributes( object, material, program, geometry ) {
  44001. initAttributes();
  44002. const geometryAttributes = geometry.attributes;
  44003. const programAttributes = program.getAttributes();
  44004. const materialDefaultAttributeValues = material.defaultAttributeValues;
  44005. for ( const name in programAttributes ) {
  44006. const programAttribute = programAttributes[ name ];
  44007. if ( programAttribute.location >= 0 ) {
  44008. let geometryAttribute = geometryAttributes[ name ];
  44009. if ( geometryAttribute === undefined ) {
  44010. if ( name === 'instanceMatrix' && object.instanceMatrix ) geometryAttribute = object.instanceMatrix;
  44011. if ( name === 'instanceColor' && object.instanceColor ) geometryAttribute = object.instanceColor;
  44012. }
  44013. if ( geometryAttribute !== undefined ) {
  44014. const normalized = geometryAttribute.normalized;
  44015. const size = geometryAttribute.itemSize;
  44016. const attribute = attributes.get( geometryAttribute );
  44017. // TODO Attribute may not be available on context restore
  44018. if ( attribute === undefined ) continue;
  44019. const buffer = attribute.buffer;
  44020. const type = attribute.type;
  44021. const bytesPerElement = attribute.bytesPerElement;
  44022. // check for integer attributes
  44023. const integer = ( type === gl.INT || type === gl.UNSIGNED_INT || geometryAttribute.gpuType === IntType );
  44024. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  44025. const data = geometryAttribute.data;
  44026. const stride = data.stride;
  44027. const offset = geometryAttribute.offset;
  44028. if ( data.isInstancedInterleavedBuffer ) {
  44029. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44030. enableAttributeAndDivisor( programAttribute.location + i, data.meshPerAttribute );
  44031. }
  44032. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44033. geometry._maxInstanceCount = data.meshPerAttribute * data.count;
  44034. }
  44035. } else {
  44036. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44037. enableAttribute( programAttribute.location + i );
  44038. }
  44039. }
  44040. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44041. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44042. vertexAttribPointer(
  44043. programAttribute.location + i,
  44044. size / programAttribute.locationSize,
  44045. type,
  44046. normalized,
  44047. stride * bytesPerElement,
  44048. ( offset + ( size / programAttribute.locationSize ) * i ) * bytesPerElement,
  44049. integer
  44050. );
  44051. }
  44052. } else {
  44053. if ( geometryAttribute.isInstancedBufferAttribute ) {
  44054. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44055. enableAttributeAndDivisor( programAttribute.location + i, geometryAttribute.meshPerAttribute );
  44056. }
  44057. if ( object.isInstancedMesh !== true && geometry._maxInstanceCount === undefined ) {
  44058. geometry._maxInstanceCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  44059. }
  44060. } else {
  44061. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44062. enableAttribute( programAttribute.location + i );
  44063. }
  44064. }
  44065. gl.bindBuffer( gl.ARRAY_BUFFER, buffer );
  44066. for ( let i = 0; i < programAttribute.locationSize; i ++ ) {
  44067. vertexAttribPointer(
  44068. programAttribute.location + i,
  44069. size / programAttribute.locationSize,
  44070. type,
  44071. normalized,
  44072. size * bytesPerElement,
  44073. ( size / programAttribute.locationSize ) * i * bytesPerElement,
  44074. integer
  44075. );
  44076. }
  44077. }
  44078. } else if ( materialDefaultAttributeValues !== undefined ) {
  44079. const value = materialDefaultAttributeValues[ name ];
  44080. if ( value !== undefined ) {
  44081. switch ( value.length ) {
  44082. case 2:
  44083. gl.vertexAttrib2fv( programAttribute.location, value );
  44084. break;
  44085. case 3:
  44086. gl.vertexAttrib3fv( programAttribute.location, value );
  44087. break;
  44088. case 4:
  44089. gl.vertexAttrib4fv( programAttribute.location, value );
  44090. break;
  44091. default:
  44092. gl.vertexAttrib1fv( programAttribute.location, value );
  44093. }
  44094. }
  44095. }
  44096. }
  44097. }
  44098. disableUnusedAttributes();
  44099. }
  44100. function dispose() {
  44101. reset();
  44102. for ( const geometryId in bindingStates ) {
  44103. const programMap = bindingStates[ geometryId ];
  44104. for ( const programId in programMap ) {
  44105. const stateMap = programMap[ programId ];
  44106. for ( const wireframe in stateMap ) {
  44107. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44108. delete stateMap[ wireframe ];
  44109. }
  44110. delete programMap[ programId ];
  44111. }
  44112. delete bindingStates[ geometryId ];
  44113. }
  44114. }
  44115. function releaseStatesOfGeometry( geometry ) {
  44116. if ( bindingStates[ geometry.id ] === undefined ) return;
  44117. const programMap = bindingStates[ geometry.id ];
  44118. for ( const programId in programMap ) {
  44119. const stateMap = programMap[ programId ];
  44120. for ( const wireframe in stateMap ) {
  44121. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44122. delete stateMap[ wireframe ];
  44123. }
  44124. delete programMap[ programId ];
  44125. }
  44126. delete bindingStates[ geometry.id ];
  44127. }
  44128. function releaseStatesOfProgram( program ) {
  44129. for ( const geometryId in bindingStates ) {
  44130. const programMap = bindingStates[ geometryId ];
  44131. if ( programMap[ program.id ] === undefined ) continue;
  44132. const stateMap = programMap[ program.id ];
  44133. for ( const wireframe in stateMap ) {
  44134. deleteVertexArrayObject( stateMap[ wireframe ].object );
  44135. delete stateMap[ wireframe ];
  44136. }
  44137. delete programMap[ program.id ];
  44138. }
  44139. }
  44140. function reset() {
  44141. resetDefaultState();
  44142. forceUpdate = true;
  44143. if ( currentState === defaultState ) return;
  44144. currentState = defaultState;
  44145. bindVertexArrayObject( currentState.object );
  44146. }
  44147. // for backward-compatibility
  44148. function resetDefaultState() {
  44149. defaultState.geometry = null;
  44150. defaultState.program = null;
  44151. defaultState.wireframe = false;
  44152. }
  44153. return {
  44154. setup: setup,
  44155. reset: reset,
  44156. resetDefaultState: resetDefaultState,
  44157. dispose: dispose,
  44158. releaseStatesOfGeometry: releaseStatesOfGeometry,
  44159. releaseStatesOfProgram: releaseStatesOfProgram,
  44160. initAttributes: initAttributes,
  44161. enableAttribute: enableAttribute,
  44162. disableUnusedAttributes: disableUnusedAttributes
  44163. };
  44164. }
  44165. function WebGLBufferRenderer( gl, extensions, info ) {
  44166. let mode;
  44167. function setMode( value ) {
  44168. mode = value;
  44169. }
  44170. function render( start, count ) {
  44171. gl.drawArrays( mode, start, count );
  44172. info.update( count, mode, 1 );
  44173. }
  44174. function renderInstances( start, count, primcount ) {
  44175. if ( primcount === 0 ) return;
  44176. gl.drawArraysInstanced( mode, start, count, primcount );
  44177. info.update( count, mode, primcount );
  44178. }
  44179. function renderMultiDraw( starts, counts, drawCount ) {
  44180. if ( drawCount === 0 ) return;
  44181. const extension = extensions.get( 'WEBGL_multi_draw' );
  44182. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44183. let elementCount = 0;
  44184. for ( let i = 0; i < drawCount; i ++ ) {
  44185. elementCount += counts[ i ];
  44186. }
  44187. info.update( elementCount, mode, 1 );
  44188. }
  44189. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44190. if ( drawCount === 0 ) return;
  44191. const extension = extensions.get( 'WEBGL_multi_draw' );
  44192. if ( extension === null ) {
  44193. for ( let i = 0; i < starts.length; i ++ ) {
  44194. renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44195. }
  44196. } else {
  44197. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44198. let elementCount = 0;
  44199. for ( let i = 0; i < drawCount; i ++ ) {
  44200. elementCount += counts[ i ] * primcount[ i ];
  44201. }
  44202. info.update( elementCount, mode, 1 );
  44203. }
  44204. }
  44205. //
  44206. this.setMode = setMode;
  44207. this.render = render;
  44208. this.renderInstances = renderInstances;
  44209. this.renderMultiDraw = renderMultiDraw;
  44210. this.renderMultiDrawInstances = renderMultiDrawInstances;
  44211. }
  44212. function WebGLCapabilities( gl, extensions, parameters, utils ) {
  44213. let maxAnisotropy;
  44214. function getMaxAnisotropy() {
  44215. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  44216. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44217. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44218. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44219. } else {
  44220. maxAnisotropy = 0;
  44221. }
  44222. return maxAnisotropy;
  44223. }
  44224. function textureFormatReadable( textureFormat ) {
  44225. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  44226. return false;
  44227. }
  44228. return true;
  44229. }
  44230. function textureTypeReadable( textureType ) {
  44231. const halfFloatSupportedByExt = ( textureType === HalfFloatType ) && ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) );
  44232. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // Edge and Chrome Mac < 52 (#9513)
  44233. textureType !== FloatType && ! halfFloatSupportedByExt ) {
  44234. return false;
  44235. }
  44236. return true;
  44237. }
  44238. function getMaxPrecision( precision ) {
  44239. if ( precision === 'highp' ) {
  44240. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  44241. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  44242. return 'highp';
  44243. }
  44244. precision = 'mediump';
  44245. }
  44246. if ( precision === 'mediump' ) {
  44247. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  44248. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  44249. return 'mediump';
  44250. }
  44251. }
  44252. return 'lowp';
  44253. }
  44254. let precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  44255. const maxPrecision = getMaxPrecision( precision );
  44256. if ( maxPrecision !== precision ) {
  44257. warn( 'WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  44258. precision = maxPrecision;
  44259. }
  44260. const logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  44261. const reversedDepthBuffer = parameters.reversedDepthBuffer === true && extensions.has( 'EXT_clip_control' );
  44262. const maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  44263. const maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  44264. const maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  44265. const maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  44266. const maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  44267. const maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  44268. const maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  44269. const maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  44270. const vertexTextures = maxVertexTextures > 0;
  44271. const maxSamples = gl.getParameter( gl.MAX_SAMPLES );
  44272. return {
  44273. isWebGL2: true, // keeping this for backwards compatibility
  44274. getMaxAnisotropy: getMaxAnisotropy,
  44275. getMaxPrecision: getMaxPrecision,
  44276. textureFormatReadable: textureFormatReadable,
  44277. textureTypeReadable: textureTypeReadable,
  44278. precision: precision,
  44279. logarithmicDepthBuffer: logarithmicDepthBuffer,
  44280. reversedDepthBuffer: reversedDepthBuffer,
  44281. maxTextures: maxTextures,
  44282. maxVertexTextures: maxVertexTextures,
  44283. maxTextureSize: maxTextureSize,
  44284. maxCubemapSize: maxCubemapSize,
  44285. maxAttributes: maxAttributes,
  44286. maxVertexUniforms: maxVertexUniforms,
  44287. maxVaryings: maxVaryings,
  44288. maxFragmentUniforms: maxFragmentUniforms,
  44289. vertexTextures: vertexTextures,
  44290. maxSamples: maxSamples
  44291. };
  44292. }
  44293. function WebGLClipping( properties ) {
  44294. const scope = this;
  44295. let globalState = null,
  44296. numGlobalPlanes = 0,
  44297. localClippingEnabled = false,
  44298. renderingShadows = false;
  44299. const plane = new Plane(),
  44300. viewNormalMatrix = new Matrix3(),
  44301. uniform = { value: null, needsUpdate: false };
  44302. this.uniform = uniform;
  44303. this.numPlanes = 0;
  44304. this.numIntersection = 0;
  44305. this.init = function ( planes, enableLocalClipping ) {
  44306. const enabled =
  44307. planes.length !== 0 ||
  44308. enableLocalClipping ||
  44309. // enable state of previous frame - the clipping code has to
  44310. // run another frame in order to reset the state:
  44311. numGlobalPlanes !== 0 ||
  44312. localClippingEnabled;
  44313. localClippingEnabled = enableLocalClipping;
  44314. numGlobalPlanes = planes.length;
  44315. return enabled;
  44316. };
  44317. this.beginShadows = function () {
  44318. renderingShadows = true;
  44319. projectPlanes( null );
  44320. };
  44321. this.endShadows = function () {
  44322. renderingShadows = false;
  44323. };
  44324. this.setGlobalState = function ( planes, camera ) {
  44325. globalState = projectPlanes( planes, camera, 0 );
  44326. };
  44327. this.setState = function ( material, camera, useCache ) {
  44328. const planes = material.clippingPlanes,
  44329. clipIntersection = material.clipIntersection,
  44330. clipShadows = material.clipShadows;
  44331. const materialProperties = properties.get( material );
  44332. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  44333. // there's no local clipping
  44334. if ( renderingShadows ) {
  44335. // there's no global clipping
  44336. projectPlanes( null );
  44337. } else {
  44338. resetGlobalState();
  44339. }
  44340. } else {
  44341. const nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  44342. lGlobal = nGlobal * 4;
  44343. let dstArray = materialProperties.clippingState || null;
  44344. uniform.value = dstArray; // ensure unique state
  44345. dstArray = projectPlanes( planes, camera, lGlobal, useCache );
  44346. for ( let i = 0; i !== lGlobal; ++ i ) {
  44347. dstArray[ i ] = globalState[ i ];
  44348. }
  44349. materialProperties.clippingState = dstArray;
  44350. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  44351. this.numPlanes += nGlobal;
  44352. }
  44353. };
  44354. function resetGlobalState() {
  44355. if ( uniform.value !== globalState ) {
  44356. uniform.value = globalState;
  44357. uniform.needsUpdate = numGlobalPlanes > 0;
  44358. }
  44359. scope.numPlanes = numGlobalPlanes;
  44360. scope.numIntersection = 0;
  44361. }
  44362. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  44363. const nPlanes = planes !== null ? planes.length : 0;
  44364. let dstArray = null;
  44365. if ( nPlanes !== 0 ) {
  44366. dstArray = uniform.value;
  44367. if ( skipTransform !== true || dstArray === null ) {
  44368. const flatSize = dstOffset + nPlanes * 4,
  44369. viewMatrix = camera.matrixWorldInverse;
  44370. viewNormalMatrix.getNormalMatrix( viewMatrix );
  44371. if ( dstArray === null || dstArray.length < flatSize ) {
  44372. dstArray = new Float32Array( flatSize );
  44373. }
  44374. for ( let i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  44375. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  44376. plane.normal.toArray( dstArray, i4 );
  44377. dstArray[ i4 + 3 ] = plane.constant;
  44378. }
  44379. }
  44380. uniform.value = dstArray;
  44381. uniform.needsUpdate = true;
  44382. }
  44383. scope.numPlanes = nPlanes;
  44384. scope.numIntersection = 0;
  44385. return dstArray;
  44386. }
  44387. }
  44388. function WebGLCubeMaps( renderer ) {
  44389. let cubemaps = new WeakMap();
  44390. function mapTextureMapping( texture, mapping ) {
  44391. if ( mapping === EquirectangularReflectionMapping ) {
  44392. texture.mapping = CubeReflectionMapping;
  44393. } else if ( mapping === EquirectangularRefractionMapping ) {
  44394. texture.mapping = CubeRefractionMapping;
  44395. }
  44396. return texture;
  44397. }
  44398. function get( texture ) {
  44399. if ( texture && texture.isTexture ) {
  44400. const mapping = texture.mapping;
  44401. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  44402. if ( cubemaps.has( texture ) ) {
  44403. const cubemap = cubemaps.get( texture ).texture;
  44404. return mapTextureMapping( cubemap, texture.mapping );
  44405. } else {
  44406. const image = texture.image;
  44407. if ( image && image.height > 0 ) {
  44408. const renderTarget = new WebGLCubeRenderTarget( image.height );
  44409. renderTarget.fromEquirectangularTexture( renderer, texture );
  44410. cubemaps.set( texture, renderTarget );
  44411. texture.addEventListener( 'dispose', onTextureDispose );
  44412. return mapTextureMapping( renderTarget.texture, texture.mapping );
  44413. } else {
  44414. // image not yet ready. try the conversion next frame
  44415. return null;
  44416. }
  44417. }
  44418. }
  44419. }
  44420. return texture;
  44421. }
  44422. function onTextureDispose( event ) {
  44423. const texture = event.target;
  44424. texture.removeEventListener( 'dispose', onTextureDispose );
  44425. const cubemap = cubemaps.get( texture );
  44426. if ( cubemap !== undefined ) {
  44427. cubemaps.delete( texture );
  44428. cubemap.dispose();
  44429. }
  44430. }
  44431. function dispose() {
  44432. cubemaps = new WeakMap();
  44433. }
  44434. return {
  44435. get: get,
  44436. dispose: dispose
  44437. };
  44438. }
  44439. const LOD_MIN = 4;
  44440. // The standard deviations (radians) associated with the extra mips.
  44441. // Used for scene blur in fromScene() method.
  44442. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  44443. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  44444. // samples and exit early, but not recompile the shader.
  44445. // Used for scene blur in fromScene() method.
  44446. const MAX_SAMPLES = 20;
  44447. // GGX VNDF importance sampling configuration
  44448. const GGX_SAMPLES = 256;
  44449. const _flatCamera = /*@__PURE__*/ new OrthographicCamera();
  44450. const _clearColor = /*@__PURE__*/ new Color();
  44451. let _oldTarget = null;
  44452. let _oldActiveCubeFace = 0;
  44453. let _oldActiveMipmapLevel = 0;
  44454. let _oldXrEnabled = false;
  44455. const _origin = /*@__PURE__*/ new Vector3();
  44456. /**
  44457. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  44458. * (PMREM) from a cubeMap environment texture. This allows different levels of
  44459. * blur to be quickly accessed based on material roughness. It is packed into a
  44460. * special CubeUV format that allows us to perform custom interpolation so that
  44461. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  44462. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  44463. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  44464. * higher roughness levels. In this way we maintain resolution to smoothly
  44465. * interpolate diffuse lighting while limiting sampling computation.
  44466. *
  44467. * The prefiltering uses GGX VNDF (Visible Normal Distribution Function)
  44468. * importance sampling based on "Sampling the GGX Distribution of Visible Normals"
  44469. * (Heitz, 2018) to generate environment maps that accurately match the GGX BRDF
  44470. * used in material rendering for physically-based image-based lighting.
  44471. */
  44472. class PMREMGenerator {
  44473. /**
  44474. * Constructs a new PMREM generator.
  44475. *
  44476. * @param {WebGLRenderer} renderer - The renderer.
  44477. */
  44478. constructor( renderer ) {
  44479. this._renderer = renderer;
  44480. this._pingPongRenderTarget = null;
  44481. this._lodMax = 0;
  44482. this._cubeSize = 0;
  44483. this._sizeLods = [];
  44484. this._sigmas = [];
  44485. this._lodMeshes = [];
  44486. this._backgroundBox = null;
  44487. this._cubemapMaterial = null;
  44488. this._equirectMaterial = null;
  44489. this._blurMaterial = null;
  44490. this._ggxMaterial = null;
  44491. }
  44492. /**
  44493. * Generates a PMREM from a supplied Scene, which can be faster than using an
  44494. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  44495. * in radians to be applied to the scene before PMREM generation. Optional near
  44496. * and far planes ensure the scene is rendered in its entirety.
  44497. *
  44498. * @param {Scene} scene - The scene to be captured.
  44499. * @param {number} [sigma=0] - The blur radius in radians.
  44500. * @param {number} [near=0.1] - The near plane distance.
  44501. * @param {number} [far=100] - The far plane distance.
  44502. * @param {Object} [options={}] - The configuration options.
  44503. * @param {number} [options.size=256] - The texture size of the PMREM.
  44504. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  44505. * @return {WebGLRenderTarget} The resulting PMREM.
  44506. */
  44507. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  44508. const {
  44509. size = 256,
  44510. position = _origin,
  44511. } = options;
  44512. _oldTarget = this._renderer.getRenderTarget();
  44513. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44514. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44515. _oldXrEnabled = this._renderer.xr.enabled;
  44516. this._renderer.xr.enabled = false;
  44517. this._setSize( size );
  44518. const cubeUVRenderTarget = this._allocateTargets();
  44519. cubeUVRenderTarget.depthBuffer = true;
  44520. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  44521. if ( sigma > 0 ) {
  44522. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  44523. }
  44524. this._applyPMREM( cubeUVRenderTarget );
  44525. this._cleanup( cubeUVRenderTarget );
  44526. return cubeUVRenderTarget;
  44527. }
  44528. /**
  44529. * Generates a PMREM from an equirectangular texture, which can be either LDR
  44530. * or HDR. The ideal input image size is 1k (1024 x 512),
  44531. * as this matches best with the 256 x 256 cubemap output.
  44532. *
  44533. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  44534. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44535. * @return {WebGLRenderTarget} The resulting PMREM.
  44536. */
  44537. fromEquirectangular( equirectangular, renderTarget = null ) {
  44538. return this._fromTexture( equirectangular, renderTarget );
  44539. }
  44540. /**
  44541. * Generates a PMREM from an cubemap texture, which can be either LDR
  44542. * or HDR. The ideal input cube size is 256 x 256,
  44543. * as this matches best with the 256 x 256 cubemap output.
  44544. *
  44545. * @param {Texture} cubemap - The cubemap texture to be converted.
  44546. * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use.
  44547. * @return {WebGLRenderTarget} The resulting PMREM.
  44548. */
  44549. fromCubemap( cubemap, renderTarget = null ) {
  44550. return this._fromTexture( cubemap, renderTarget );
  44551. }
  44552. /**
  44553. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  44554. * your texture's network fetch for increased concurrency.
  44555. */
  44556. compileCubemapShader() {
  44557. if ( this._cubemapMaterial === null ) {
  44558. this._cubemapMaterial = _getCubemapMaterial();
  44559. this._compileMaterial( this._cubemapMaterial );
  44560. }
  44561. }
  44562. /**
  44563. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  44564. * your texture's network fetch for increased concurrency.
  44565. */
  44566. compileEquirectangularShader() {
  44567. if ( this._equirectMaterial === null ) {
  44568. this._equirectMaterial = _getEquirectMaterial();
  44569. this._compileMaterial( this._equirectMaterial );
  44570. }
  44571. }
  44572. /**
  44573. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  44574. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  44575. * one of them will cause any others to also become unusable.
  44576. */
  44577. dispose() {
  44578. this._dispose();
  44579. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  44580. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  44581. if ( this._backgroundBox !== null ) {
  44582. this._backgroundBox.geometry.dispose();
  44583. this._backgroundBox.material.dispose();
  44584. }
  44585. }
  44586. // private interface
  44587. _setSize( cubeSize ) {
  44588. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  44589. this._cubeSize = Math.pow( 2, this._lodMax );
  44590. }
  44591. _dispose() {
  44592. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  44593. if ( this._ggxMaterial !== null ) this._ggxMaterial.dispose();
  44594. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  44595. for ( let i = 0; i < this._lodMeshes.length; i ++ ) {
  44596. this._lodMeshes[ i ].geometry.dispose();
  44597. }
  44598. }
  44599. _cleanup( outputTarget ) {
  44600. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  44601. this._renderer.xr.enabled = _oldXrEnabled;
  44602. outputTarget.scissorTest = false;
  44603. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  44604. }
  44605. _fromTexture( texture, renderTarget ) {
  44606. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  44607. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  44608. } else { // Equirectangular
  44609. this._setSize( texture.image.width / 4 );
  44610. }
  44611. _oldTarget = this._renderer.getRenderTarget();
  44612. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  44613. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  44614. _oldXrEnabled = this._renderer.xr.enabled;
  44615. this._renderer.xr.enabled = false;
  44616. const cubeUVRenderTarget = renderTarget || this._allocateTargets();
  44617. this._textureToCubeUV( texture, cubeUVRenderTarget );
  44618. this._applyPMREM( cubeUVRenderTarget );
  44619. this._cleanup( cubeUVRenderTarget );
  44620. return cubeUVRenderTarget;
  44621. }
  44622. _allocateTargets() {
  44623. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  44624. const height = 4 * this._cubeSize;
  44625. const params = {
  44626. magFilter: LinearFilter,
  44627. minFilter: LinearFilter,
  44628. generateMipmaps: false,
  44629. type: HalfFloatType,
  44630. format: RGBAFormat,
  44631. colorSpace: LinearSRGBColorSpace,
  44632. depthBuffer: false
  44633. };
  44634. const cubeUVRenderTarget = _createRenderTarget( width, height, params );
  44635. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== width || this._pingPongRenderTarget.height !== height ) {
  44636. if ( this._pingPongRenderTarget !== null ) {
  44637. this._dispose();
  44638. }
  44639. this._pingPongRenderTarget = _createRenderTarget( width, height, params );
  44640. const { _lodMax } = this;
  44641. ( { lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = _createPlanes( _lodMax ) );
  44642. this._blurMaterial = _getBlurShader( _lodMax, width, height );
  44643. this._ggxMaterial = _getGGXShader( _lodMax, width, height );
  44644. }
  44645. return cubeUVRenderTarget;
  44646. }
  44647. _compileMaterial( material ) {
  44648. const mesh = new Mesh( new BufferGeometry(), material );
  44649. this._renderer.compile( mesh, _flatCamera );
  44650. }
  44651. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  44652. const fov = 90;
  44653. const aspect = 1;
  44654. const cubeCamera = new PerspectiveCamera( fov, aspect, near, far );
  44655. const upSign = [ 1, -1, 1, 1, 1, 1 ];
  44656. const forwardSign = [ 1, 1, 1, -1, -1, -1 ];
  44657. const renderer = this._renderer;
  44658. const originalAutoClear = renderer.autoClear;
  44659. const toneMapping = renderer.toneMapping;
  44660. renderer.getClearColor( _clearColor );
  44661. renderer.toneMapping = NoToneMapping;
  44662. renderer.autoClear = false;
  44663. // https://github.com/mrdoob/three.js/issues/31413#issuecomment-3095966812
  44664. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  44665. if ( reversedDepthBuffer ) {
  44666. renderer.setRenderTarget( cubeUVRenderTarget );
  44667. renderer.clearDepth();
  44668. renderer.setRenderTarget( null );
  44669. }
  44670. if ( this._backgroundBox === null ) {
  44671. this._backgroundBox = new Mesh(
  44672. new BoxGeometry(),
  44673. new MeshBasicMaterial( {
  44674. name: 'PMREM.Background',
  44675. side: BackSide,
  44676. depthWrite: false,
  44677. depthTest: false,
  44678. } )
  44679. );
  44680. }
  44681. const backgroundBox = this._backgroundBox;
  44682. const backgroundMaterial = backgroundBox.material;
  44683. let useSolidColor = false;
  44684. const background = scene.background;
  44685. if ( background ) {
  44686. if ( background.isColor ) {
  44687. backgroundMaterial.color.copy( background );
  44688. scene.background = null;
  44689. useSolidColor = true;
  44690. }
  44691. } else {
  44692. backgroundMaterial.color.copy( _clearColor );
  44693. useSolidColor = true;
  44694. }
  44695. for ( let i = 0; i < 6; i ++ ) {
  44696. const col = i % 3;
  44697. if ( col === 0 ) {
  44698. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44699. cubeCamera.position.set( position.x, position.y, position.z );
  44700. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  44701. } else if ( col === 1 ) {
  44702. cubeCamera.up.set( 0, 0, upSign[ i ] );
  44703. cubeCamera.position.set( position.x, position.y, position.z );
  44704. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  44705. } else {
  44706. cubeCamera.up.set( 0, upSign[ i ], 0 );
  44707. cubeCamera.position.set( position.x, position.y, position.z );
  44708. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  44709. }
  44710. const size = this._cubeSize;
  44711. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  44712. renderer.setRenderTarget( cubeUVRenderTarget );
  44713. if ( useSolidColor ) {
  44714. renderer.render( backgroundBox, cubeCamera );
  44715. }
  44716. renderer.render( scene, cubeCamera );
  44717. }
  44718. renderer.toneMapping = toneMapping;
  44719. renderer.autoClear = originalAutoClear;
  44720. scene.background = background;
  44721. }
  44722. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  44723. const renderer = this._renderer;
  44724. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  44725. if ( isCubeTexture ) {
  44726. if ( this._cubemapMaterial === null ) {
  44727. this._cubemapMaterial = _getCubemapMaterial();
  44728. }
  44729. this._cubemapMaterial.uniforms.flipEnvMap.value = ( texture.isRenderTargetTexture === false ) ? -1 : 1;
  44730. } else {
  44731. if ( this._equirectMaterial === null ) {
  44732. this._equirectMaterial = _getEquirectMaterial();
  44733. }
  44734. }
  44735. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  44736. const mesh = this._lodMeshes[ 0 ];
  44737. mesh.material = material;
  44738. const uniforms = material.uniforms;
  44739. uniforms[ 'envMap' ].value = texture;
  44740. const size = this._cubeSize;
  44741. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  44742. renderer.setRenderTarget( cubeUVRenderTarget );
  44743. renderer.render( mesh, _flatCamera );
  44744. }
  44745. _applyPMREM( cubeUVRenderTarget ) {
  44746. const renderer = this._renderer;
  44747. const autoClear = renderer.autoClear;
  44748. renderer.autoClear = false;
  44749. const n = this._lodMeshes.length;
  44750. // Use GGX VNDF importance sampling
  44751. for ( let i = 1; i < n; i ++ ) {
  44752. this._applyGGXFilter( cubeUVRenderTarget, i - 1, i );
  44753. }
  44754. renderer.autoClear = autoClear;
  44755. }
  44756. /**
  44757. * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map.
  44758. * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the
  44759. * GGX BRDF for physically-based rendering. Reads from the previous LOD level and
  44760. * applies incremental roughness filtering to avoid over-blurring.
  44761. *
  44762. * @private
  44763. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44764. * @param {number} lodIn - Source LOD level to read from
  44765. * @param {number} lodOut - Target LOD level to write to
  44766. */
  44767. _applyGGXFilter( cubeUVRenderTarget, lodIn, lodOut ) {
  44768. const renderer = this._renderer;
  44769. const pingPongRenderTarget = this._pingPongRenderTarget;
  44770. const ggxMaterial = this._ggxMaterial;
  44771. const ggxMesh = this._lodMeshes[ lodOut ];
  44772. ggxMesh.material = ggxMaterial;
  44773. const ggxUniforms = ggxMaterial.uniforms;
  44774. // Calculate incremental roughness between LOD levels
  44775. const targetRoughness = lodOut / ( this._lodMeshes.length - 1 );
  44776. const sourceRoughness = lodIn / ( this._lodMeshes.length - 1 );
  44777. const incrementalRoughness = Math.sqrt( targetRoughness * targetRoughness - sourceRoughness * sourceRoughness );
  44778. // Apply blur strength mapping for better quality across the roughness range
  44779. const blurStrength = 0.0 + targetRoughness * 1.25;
  44780. const adjustedRoughness = incrementalRoughness * blurStrength;
  44781. // Calculate viewport position based on output LOD level
  44782. const { _lodMax } = this;
  44783. const outputSize = this._sizeLods[ lodOut ];
  44784. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44785. const y = 4 * ( this._cubeSize - outputSize );
  44786. // Read from previous LOD with incremental roughness
  44787. ggxUniforms[ 'envMap' ].value = cubeUVRenderTarget.texture;
  44788. ggxUniforms[ 'roughness' ].value = adjustedRoughness;
  44789. ggxUniforms[ 'mipInt' ].value = _lodMax - lodIn; // Sample from input LOD
  44790. _setViewport( pingPongRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44791. renderer.setRenderTarget( pingPongRenderTarget );
  44792. renderer.render( ggxMesh, _flatCamera );
  44793. // Copy from pingPong back to cubeUV (simple direct copy)
  44794. ggxUniforms[ 'envMap' ].value = pingPongRenderTarget.texture;
  44795. ggxUniforms[ 'roughness' ].value = 0.0; // Direct copy
  44796. ggxUniforms[ 'mipInt' ].value = _lodMax - lodOut; // Read from the level we just wrote
  44797. _setViewport( cubeUVRenderTarget, x, y, 3 * outputSize, 2 * outputSize );
  44798. renderer.setRenderTarget( cubeUVRenderTarget );
  44799. renderer.render( ggxMesh, _flatCamera );
  44800. }
  44801. /**
  44802. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  44803. * vertically and horizontally, but this breaks down on a cube. Here we apply
  44804. * the blur latitudinally (around the poles), and then longitudinally (towards
  44805. * the poles) to approximate the orthogonally-separable blur. It is least
  44806. * accurate at the poles, but still does a decent job.
  44807. *
  44808. * Used for initial scene blur in fromScene() method when sigma > 0.
  44809. *
  44810. * @private
  44811. * @param {WebGLRenderTarget} cubeUVRenderTarget
  44812. * @param {number} lodIn
  44813. * @param {number} lodOut
  44814. * @param {number} sigma
  44815. * @param {Vector3} [poleAxis]
  44816. */
  44817. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  44818. const pingPongRenderTarget = this._pingPongRenderTarget;
  44819. this._halfBlur(
  44820. cubeUVRenderTarget,
  44821. pingPongRenderTarget,
  44822. lodIn,
  44823. lodOut,
  44824. sigma,
  44825. 'latitudinal',
  44826. poleAxis );
  44827. this._halfBlur(
  44828. pingPongRenderTarget,
  44829. cubeUVRenderTarget,
  44830. lodOut,
  44831. lodOut,
  44832. sigma,
  44833. 'longitudinal',
  44834. poleAxis );
  44835. }
  44836. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  44837. const renderer = this._renderer;
  44838. const blurMaterial = this._blurMaterial;
  44839. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  44840. error(
  44841. 'blur direction must be either latitudinal or longitudinal!' );
  44842. }
  44843. // Number of standard deviations at which to cut off the discrete approximation.
  44844. const STANDARD_DEVIATIONS = 3;
  44845. const blurMesh = this._lodMeshes[ lodOut ];
  44846. blurMesh.material = blurMaterial;
  44847. const blurUniforms = blurMaterial.uniforms;
  44848. const pixels = this._sizeLods[ lodIn ] - 1;
  44849. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  44850. const sigmaPixels = sigmaRadians / radiansPerPixel;
  44851. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  44852. if ( samples > MAX_SAMPLES ) {
  44853. warn( `sigmaRadians, ${
  44854. sigmaRadians}, is too large and will clip, as it requested ${
  44855. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  44856. }
  44857. const weights = [];
  44858. let sum = 0;
  44859. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  44860. const x = i / sigmaPixels;
  44861. const weight = Math.exp( - x * x / 2 );
  44862. weights.push( weight );
  44863. if ( i === 0 ) {
  44864. sum += weight;
  44865. } else if ( i < samples ) {
  44866. sum += 2 * weight;
  44867. }
  44868. }
  44869. for ( let i = 0; i < weights.length; i ++ ) {
  44870. weights[ i ] = weights[ i ] / sum;
  44871. }
  44872. blurUniforms[ 'envMap' ].value = targetIn.texture;
  44873. blurUniforms[ 'samples' ].value = samples;
  44874. blurUniforms[ 'weights' ].value = weights;
  44875. blurUniforms[ 'latitudinal' ].value = direction === 'latitudinal';
  44876. if ( poleAxis ) {
  44877. blurUniforms[ 'poleAxis' ].value = poleAxis;
  44878. }
  44879. const { _lodMax } = this;
  44880. blurUniforms[ 'dTheta' ].value = radiansPerPixel;
  44881. blurUniforms[ 'mipInt' ].value = _lodMax - lodIn;
  44882. const outputSize = this._sizeLods[ lodOut ];
  44883. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  44884. const y = 4 * ( this._cubeSize - outputSize );
  44885. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  44886. renderer.setRenderTarget( targetOut );
  44887. renderer.render( blurMesh, _flatCamera );
  44888. }
  44889. }
  44890. function _createPlanes( lodMax ) {
  44891. const sizeLods = [];
  44892. const sigmas = [];
  44893. const lodMeshes = [];
  44894. let lod = lodMax;
  44895. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  44896. for ( let i = 0; i < totalLods; i ++ ) {
  44897. const sizeLod = Math.pow( 2, lod );
  44898. sizeLods.push( sizeLod );
  44899. let sigma = 1.0 / sizeLod;
  44900. if ( i > lodMax - LOD_MIN ) {
  44901. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  44902. } else if ( i === 0 ) {
  44903. sigma = 0;
  44904. }
  44905. sigmas.push( sigma );
  44906. const texelSize = 1.0 / ( sizeLod - 2 );
  44907. const min = - texelSize;
  44908. const max = 1 + texelSize;
  44909. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  44910. const cubeFaces = 6;
  44911. const vertices = 6;
  44912. const positionSize = 3;
  44913. const uvSize = 2;
  44914. const faceIndexSize = 1;
  44915. const position = new Float32Array( positionSize * vertices * cubeFaces );
  44916. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  44917. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  44918. for ( let face = 0; face < cubeFaces; face ++ ) {
  44919. const x = ( face % 3 ) * 2 / 3 - 1;
  44920. const y = face > 2 ? 0 : -1;
  44921. const coordinates = [
  44922. x, y, 0,
  44923. x + 2 / 3, y, 0,
  44924. x + 2 / 3, y + 1, 0,
  44925. x, y, 0,
  44926. x + 2 / 3, y + 1, 0,
  44927. x, y + 1, 0
  44928. ];
  44929. position.set( coordinates, positionSize * vertices * face );
  44930. uv.set( uv1, uvSize * vertices * face );
  44931. const fill = [ face, face, face, face, face, face ];
  44932. faceIndex.set( fill, faceIndexSize * vertices * face );
  44933. }
  44934. const planes = new BufferGeometry();
  44935. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  44936. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  44937. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  44938. lodMeshes.push( new Mesh( planes, null ) );
  44939. if ( lod > LOD_MIN ) {
  44940. lod --;
  44941. }
  44942. }
  44943. return { lodMeshes, sizeLods, sigmas };
  44944. }
  44945. function _createRenderTarget( width, height, params ) {
  44946. const cubeUVRenderTarget = new WebGLRenderTarget( width, height, params );
  44947. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  44948. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  44949. cubeUVRenderTarget.scissorTest = true;
  44950. return cubeUVRenderTarget;
  44951. }
  44952. function _setViewport( target, x, y, width, height ) {
  44953. target.viewport.set( x, y, width, height );
  44954. target.scissor.set( x, y, width, height );
  44955. }
  44956. function _getGGXShader( lodMax, width, height ) {
  44957. const shaderMaterial = new ShaderMaterial( {
  44958. name: 'PMREMGGXConvolution',
  44959. defines: {
  44960. 'GGX_SAMPLES': GGX_SAMPLES,
  44961. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  44962. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  44963. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  44964. },
  44965. uniforms: {
  44966. 'envMap': { value: null },
  44967. 'roughness': { value: 0.0 },
  44968. 'mipInt': { value: 0 }
  44969. },
  44970. vertexShader: _getCommonVertexShader(),
  44971. fragmentShader: /* glsl */`
  44972. precision highp float;
  44973. precision highp int;
  44974. varying vec3 vOutputDirection;
  44975. uniform sampler2D envMap;
  44976. uniform float roughness;
  44977. uniform float mipInt;
  44978. #define ENVMAP_TYPE_CUBE_UV
  44979. #include <cube_uv_reflection_fragment>
  44980. #define PI 3.14159265359
  44981. // Van der Corput radical inverse
  44982. float radicalInverse_VdC(uint bits) {
  44983. bits = (bits << 16u) | (bits >> 16u);
  44984. bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
  44985. bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
  44986. bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
  44987. bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
  44988. return float(bits) * 2.3283064365386963e-10; // / 0x100000000
  44989. }
  44990. // Hammersley sequence
  44991. vec2 hammersley(uint i, uint N) {
  44992. return vec2(float(i) / float(N), radicalInverse_VdC(i));
  44993. }
  44994. // GGX VNDF importance sampling (Eric Heitz 2018)
  44995. // "Sampling the GGX Distribution of Visible Normals"
  44996. // https://jcgt.org/published/0007/04/01/
  44997. vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) {
  44998. float alpha = roughness * roughness;
  44999. // Section 3.2: Transform view direction to hemisphere configuration
  45000. vec3 Vh = normalize(vec3(alpha * V.x, alpha * V.y, V.z));
  45001. // Section 4.1: Orthonormal basis
  45002. float lensq = Vh.x * Vh.x + Vh.y * Vh.y;
  45003. vec3 T1 = lensq > 0.0 ? vec3(-Vh.y, Vh.x, 0.0) / sqrt(lensq) : vec3(1.0, 0.0, 0.0);
  45004. vec3 T2 = cross(Vh, T1);
  45005. // Section 4.2: Parameterization of projected area
  45006. float r = sqrt(Xi.x);
  45007. float phi = 2.0 * PI * Xi.y;
  45008. float t1 = r * cos(phi);
  45009. float t2 = r * sin(phi);
  45010. float s = 0.5 * (1.0 + Vh.z);
  45011. t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2;
  45012. // Section 4.3: Reprojection onto hemisphere
  45013. vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * Vh;
  45014. // Section 3.4: Transform back to ellipsoid configuration
  45015. return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z)));
  45016. }
  45017. void main() {
  45018. vec3 N = normalize(vOutputDirection);
  45019. vec3 V = N; // Assume view direction equals normal for pre-filtering
  45020. vec3 prefilteredColor = vec3(0.0);
  45021. float totalWeight = 0.0;
  45022. // For very low roughness, just sample the environment directly
  45023. if (roughness < 0.001) {
  45024. gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0);
  45025. return;
  45026. }
  45027. // Tangent space basis for VNDF sampling
  45028. vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0);
  45029. vec3 tangent = normalize(cross(up, N));
  45030. vec3 bitangent = cross(N, tangent);
  45031. for(uint i = 0u; i < uint(GGX_SAMPLES); i++) {
  45032. vec2 Xi = hammersley(i, uint(GGX_SAMPLES));
  45033. // For PMREM, V = N, so in tangent space V is always (0, 0, 1)
  45034. vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness);
  45035. // Transform H back to world space
  45036. vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z);
  45037. vec3 L = normalize(2.0 * dot(V, H) * H - V);
  45038. float NdotL = max(dot(N, L), 0.0);
  45039. if(NdotL > 0.0) {
  45040. // Sample environment at fixed mip level
  45041. // VNDF importance sampling handles the distribution filtering
  45042. vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt);
  45043. // Weight by NdotL for the split-sum approximation
  45044. // VNDF PDF naturally accounts for the visible microfacet distribution
  45045. prefilteredColor += sampleColor * NdotL;
  45046. totalWeight += NdotL;
  45047. }
  45048. }
  45049. if (totalWeight > 0.0) {
  45050. prefilteredColor = prefilteredColor / totalWeight;
  45051. }
  45052. gl_FragColor = vec4(prefilteredColor, 1.0);
  45053. }
  45054. `,
  45055. blending: NoBlending,
  45056. depthTest: false,
  45057. depthWrite: false
  45058. } );
  45059. return shaderMaterial;
  45060. }
  45061. function _getBlurShader( lodMax, width, height ) {
  45062. const weights = new Float32Array( MAX_SAMPLES );
  45063. const poleAxis = new Vector3( 0, 1, 0 );
  45064. const shaderMaterial = new ShaderMaterial( {
  45065. name: 'SphericalGaussianBlur',
  45066. defines: {
  45067. 'n': MAX_SAMPLES,
  45068. 'CUBEUV_TEXEL_WIDTH': 1.0 / width,
  45069. 'CUBEUV_TEXEL_HEIGHT': 1.0 / height,
  45070. 'CUBEUV_MAX_MIP': `${lodMax}.0`,
  45071. },
  45072. uniforms: {
  45073. 'envMap': { value: null },
  45074. 'samples': { value: 1 },
  45075. 'weights': { value: weights },
  45076. 'latitudinal': { value: false },
  45077. 'dTheta': { value: 0 },
  45078. 'mipInt': { value: 0 },
  45079. 'poleAxis': { value: poleAxis }
  45080. },
  45081. vertexShader: _getCommonVertexShader(),
  45082. fragmentShader: /* glsl */`
  45083. precision mediump float;
  45084. precision mediump int;
  45085. varying vec3 vOutputDirection;
  45086. uniform sampler2D envMap;
  45087. uniform int samples;
  45088. uniform float weights[ n ];
  45089. uniform bool latitudinal;
  45090. uniform float dTheta;
  45091. uniform float mipInt;
  45092. uniform vec3 poleAxis;
  45093. #define ENVMAP_TYPE_CUBE_UV
  45094. #include <cube_uv_reflection_fragment>
  45095. vec3 getSample( float theta, vec3 axis ) {
  45096. float cosTheta = cos( theta );
  45097. // Rodrigues' axis-angle rotation
  45098. vec3 sampleDirection = vOutputDirection * cosTheta
  45099. + cross( axis, vOutputDirection ) * sin( theta )
  45100. + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta );
  45101. return bilinearCubeUV( envMap, sampleDirection, mipInt );
  45102. }
  45103. void main() {
  45104. vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection );
  45105. if ( all( equal( axis, vec3( 0.0 ) ) ) ) {
  45106. axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x );
  45107. }
  45108. axis = normalize( axis );
  45109. gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 );
  45110. gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis );
  45111. for ( int i = 1; i < n; i++ ) {
  45112. if ( i >= samples ) {
  45113. break;
  45114. }
  45115. float theta = dTheta * float( i );
  45116. gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis );
  45117. gl_FragColor.rgb += weights[ i ] * getSample( theta, axis );
  45118. }
  45119. }
  45120. `,
  45121. blending: NoBlending,
  45122. depthTest: false,
  45123. depthWrite: false
  45124. } );
  45125. return shaderMaterial;
  45126. }
  45127. function _getEquirectMaterial() {
  45128. return new ShaderMaterial( {
  45129. name: 'EquirectangularToCubeUV',
  45130. uniforms: {
  45131. 'envMap': { value: null }
  45132. },
  45133. vertexShader: _getCommonVertexShader(),
  45134. fragmentShader: /* glsl */`
  45135. precision mediump float;
  45136. precision mediump int;
  45137. varying vec3 vOutputDirection;
  45138. uniform sampler2D envMap;
  45139. #include <common>
  45140. void main() {
  45141. vec3 outputDirection = normalize( vOutputDirection );
  45142. vec2 uv = equirectUv( outputDirection );
  45143. gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 );
  45144. }
  45145. `,
  45146. blending: NoBlending,
  45147. depthTest: false,
  45148. depthWrite: false
  45149. } );
  45150. }
  45151. function _getCubemapMaterial() {
  45152. return new ShaderMaterial( {
  45153. name: 'CubemapToCubeUV',
  45154. uniforms: {
  45155. 'envMap': { value: null },
  45156. 'flipEnvMap': { value: -1 }
  45157. },
  45158. vertexShader: _getCommonVertexShader(),
  45159. fragmentShader: /* glsl */`
  45160. precision mediump float;
  45161. precision mediump int;
  45162. uniform float flipEnvMap;
  45163. varying vec3 vOutputDirection;
  45164. uniform samplerCube envMap;
  45165. void main() {
  45166. gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) );
  45167. }
  45168. `,
  45169. blending: NoBlending,
  45170. depthTest: false,
  45171. depthWrite: false
  45172. } );
  45173. }
  45174. function _getCommonVertexShader() {
  45175. return /* glsl */`
  45176. precision mediump float;
  45177. precision mediump int;
  45178. attribute float faceIndex;
  45179. varying vec3 vOutputDirection;
  45180. // RH coordinate system; PMREM face-indexing convention
  45181. vec3 getDirection( vec2 uv, float face ) {
  45182. uv = 2.0 * uv - 1.0;
  45183. vec3 direction = vec3( uv, 1.0 );
  45184. if ( face == 0.0 ) {
  45185. direction = direction.zyx; // ( 1, v, u ) pos x
  45186. } else if ( face == 1.0 ) {
  45187. direction = direction.xzy;
  45188. direction.xz *= -1.0; // ( -u, 1, -v ) pos y
  45189. } else if ( face == 2.0 ) {
  45190. direction.x *= -1.0; // ( -u, v, 1 ) pos z
  45191. } else if ( face == 3.0 ) {
  45192. direction = direction.zyx;
  45193. direction.xz *= -1.0; // ( -1, v, -u ) neg x
  45194. } else if ( face == 4.0 ) {
  45195. direction = direction.xzy;
  45196. direction.xy *= -1.0; // ( -u, -1, v ) neg y
  45197. } else if ( face == 5.0 ) {
  45198. direction.z *= -1.0; // ( u, v, -1 ) neg z
  45199. }
  45200. return direction;
  45201. }
  45202. void main() {
  45203. vOutputDirection = getDirection( uv, faceIndex );
  45204. gl_Position = vec4( position, 1.0 );
  45205. }
  45206. `;
  45207. }
  45208. function WebGLCubeUVMaps( renderer ) {
  45209. let cubeUVmaps = new WeakMap();
  45210. let pmremGenerator = null;
  45211. function get( texture ) {
  45212. if ( texture && texture.isTexture ) {
  45213. const mapping = texture.mapping;
  45214. const isEquirectMap = ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping );
  45215. const isCubeMap = ( mapping === CubeReflectionMapping || mapping === CubeRefractionMapping );
  45216. // equirect/cube map to cubeUV conversion
  45217. if ( isEquirectMap || isCubeMap ) {
  45218. let renderTarget = cubeUVmaps.get( texture );
  45219. const currentPMREMVersion = renderTarget !== undefined ? renderTarget.texture.pmremVersion : 0;
  45220. if ( texture.isRenderTargetTexture && texture.pmremVersion !== currentPMREMVersion ) {
  45221. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45222. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture, renderTarget ) : pmremGenerator.fromCubemap( texture, renderTarget );
  45223. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45224. cubeUVmaps.set( texture, renderTarget );
  45225. return renderTarget.texture;
  45226. } else {
  45227. if ( renderTarget !== undefined ) {
  45228. return renderTarget.texture;
  45229. } else {
  45230. const image = texture.image;
  45231. if ( ( isEquirectMap && image && image.height > 0 ) || ( isCubeMap && image && isCubeTextureComplete( image ) ) ) {
  45232. if ( pmremGenerator === null ) pmremGenerator = new PMREMGenerator( renderer );
  45233. renderTarget = isEquirectMap ? pmremGenerator.fromEquirectangular( texture ) : pmremGenerator.fromCubemap( texture );
  45234. renderTarget.texture.pmremVersion = texture.pmremVersion;
  45235. cubeUVmaps.set( texture, renderTarget );
  45236. texture.addEventListener( 'dispose', onTextureDispose );
  45237. return renderTarget.texture;
  45238. } else {
  45239. // image not yet ready. try the conversion next frame
  45240. return null;
  45241. }
  45242. }
  45243. }
  45244. }
  45245. }
  45246. return texture;
  45247. }
  45248. function isCubeTextureComplete( image ) {
  45249. let count = 0;
  45250. const length = 6;
  45251. for ( let i = 0; i < length; i ++ ) {
  45252. if ( image[ i ] !== undefined ) count ++;
  45253. }
  45254. return count === length;
  45255. }
  45256. function onTextureDispose( event ) {
  45257. const texture = event.target;
  45258. texture.removeEventListener( 'dispose', onTextureDispose );
  45259. const cubemapUV = cubeUVmaps.get( texture );
  45260. if ( cubemapUV !== undefined ) {
  45261. cubeUVmaps.delete( texture );
  45262. cubemapUV.dispose();
  45263. }
  45264. }
  45265. function dispose() {
  45266. cubeUVmaps = new WeakMap();
  45267. if ( pmremGenerator !== null ) {
  45268. pmremGenerator.dispose();
  45269. pmremGenerator = null;
  45270. }
  45271. }
  45272. return {
  45273. get: get,
  45274. dispose: dispose
  45275. };
  45276. }
  45277. function WebGLExtensions( gl ) {
  45278. const extensions = {};
  45279. function getExtension( name ) {
  45280. if ( extensions[ name ] !== undefined ) {
  45281. return extensions[ name ];
  45282. }
  45283. const extension = gl.getExtension( name );
  45284. extensions[ name ] = extension;
  45285. return extension;
  45286. }
  45287. return {
  45288. has: function ( name ) {
  45289. return getExtension( name ) !== null;
  45290. },
  45291. init: function () {
  45292. getExtension( 'EXT_color_buffer_float' );
  45293. getExtension( 'WEBGL_clip_cull_distance' );
  45294. getExtension( 'OES_texture_float_linear' );
  45295. getExtension( 'EXT_color_buffer_half_float' );
  45296. getExtension( 'WEBGL_multisampled_render_to_texture' );
  45297. getExtension( 'WEBGL_render_shared_exponent' );
  45298. },
  45299. get: function ( name ) {
  45300. const extension = getExtension( name );
  45301. if ( extension === null ) {
  45302. warnOnce( 'WebGLRenderer: ' + name + ' extension not supported.' );
  45303. }
  45304. return extension;
  45305. }
  45306. };
  45307. }
  45308. function WebGLGeometries( gl, attributes, info, bindingStates ) {
  45309. const geometries = {};
  45310. const wireframeAttributes = new WeakMap();
  45311. function onGeometryDispose( event ) {
  45312. const geometry = event.target;
  45313. if ( geometry.index !== null ) {
  45314. attributes.remove( geometry.index );
  45315. }
  45316. for ( const name in geometry.attributes ) {
  45317. attributes.remove( geometry.attributes[ name ] );
  45318. }
  45319. geometry.removeEventListener( 'dispose', onGeometryDispose );
  45320. delete geometries[ geometry.id ];
  45321. const attribute = wireframeAttributes.get( geometry );
  45322. if ( attribute ) {
  45323. attributes.remove( attribute );
  45324. wireframeAttributes.delete( geometry );
  45325. }
  45326. bindingStates.releaseStatesOfGeometry( geometry );
  45327. if ( geometry.isInstancedBufferGeometry === true ) {
  45328. delete geometry._maxInstanceCount;
  45329. }
  45330. //
  45331. info.memory.geometries --;
  45332. }
  45333. function get( object, geometry ) {
  45334. if ( geometries[ geometry.id ] === true ) return geometry;
  45335. geometry.addEventListener( 'dispose', onGeometryDispose );
  45336. geometries[ geometry.id ] = true;
  45337. info.memory.geometries ++;
  45338. return geometry;
  45339. }
  45340. function update( geometry ) {
  45341. const geometryAttributes = geometry.attributes;
  45342. // Updating index buffer in VAO now. See WebGLBindingStates.
  45343. for ( const name in geometryAttributes ) {
  45344. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  45345. }
  45346. }
  45347. function updateWireframeAttribute( geometry ) {
  45348. const indices = [];
  45349. const geometryIndex = geometry.index;
  45350. const geometryPosition = geometry.attributes.position;
  45351. let version = 0;
  45352. if ( geometryIndex !== null ) {
  45353. const array = geometryIndex.array;
  45354. version = geometryIndex.version;
  45355. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  45356. const a = array[ i + 0 ];
  45357. const b = array[ i + 1 ];
  45358. const c = array[ i + 2 ];
  45359. indices.push( a, b, b, c, c, a );
  45360. }
  45361. } else if ( geometryPosition !== undefined ) {
  45362. const array = geometryPosition.array;
  45363. version = geometryPosition.version;
  45364. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  45365. const a = i + 0;
  45366. const b = i + 1;
  45367. const c = i + 2;
  45368. indices.push( a, b, b, c, c, a );
  45369. }
  45370. } else {
  45371. return;
  45372. }
  45373. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  45374. attribute.version = version;
  45375. // Updating index buffer in VAO now. See WebGLBindingStates
  45376. //
  45377. const previousAttribute = wireframeAttributes.get( geometry );
  45378. if ( previousAttribute ) attributes.remove( previousAttribute );
  45379. //
  45380. wireframeAttributes.set( geometry, attribute );
  45381. }
  45382. function getWireframeAttribute( geometry ) {
  45383. const currentAttribute = wireframeAttributes.get( geometry );
  45384. if ( currentAttribute ) {
  45385. const geometryIndex = geometry.index;
  45386. if ( geometryIndex !== null ) {
  45387. // if the attribute is obsolete, create a new one
  45388. if ( currentAttribute.version < geometryIndex.version ) {
  45389. updateWireframeAttribute( geometry );
  45390. }
  45391. }
  45392. } else {
  45393. updateWireframeAttribute( geometry );
  45394. }
  45395. return wireframeAttributes.get( geometry );
  45396. }
  45397. return {
  45398. get: get,
  45399. update: update,
  45400. getWireframeAttribute: getWireframeAttribute
  45401. };
  45402. }
  45403. function WebGLIndexedBufferRenderer( gl, extensions, info ) {
  45404. let mode;
  45405. function setMode( value ) {
  45406. mode = value;
  45407. }
  45408. let type, bytesPerElement;
  45409. function setIndex( value ) {
  45410. type = value.type;
  45411. bytesPerElement = value.bytesPerElement;
  45412. }
  45413. function render( start, count ) {
  45414. gl.drawElements( mode, count, type, start * bytesPerElement );
  45415. info.update( count, mode, 1 );
  45416. }
  45417. function renderInstances( start, count, primcount ) {
  45418. if ( primcount === 0 ) return;
  45419. gl.drawElementsInstanced( mode, count, type, start * bytesPerElement, primcount );
  45420. info.update( count, mode, primcount );
  45421. }
  45422. function renderMultiDraw( starts, counts, drawCount ) {
  45423. if ( drawCount === 0 ) return;
  45424. const extension = extensions.get( 'WEBGL_multi_draw' );
  45425. extension.multiDrawElementsWEBGL( mode, counts, 0, type, starts, 0, drawCount );
  45426. let elementCount = 0;
  45427. for ( let i = 0; i < drawCount; i ++ ) {
  45428. elementCount += counts[ i ];
  45429. }
  45430. info.update( elementCount, mode, 1 );
  45431. }
  45432. function renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45433. if ( drawCount === 0 ) return;
  45434. const extension = extensions.get( 'WEBGL_multi_draw' );
  45435. if ( extension === null ) {
  45436. for ( let i = 0; i < starts.length; i ++ ) {
  45437. renderInstances( starts[ i ] / bytesPerElement, counts[ i ], primcount[ i ] );
  45438. }
  45439. } else {
  45440. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, type, starts, 0, primcount, 0, drawCount );
  45441. let elementCount = 0;
  45442. for ( let i = 0; i < drawCount; i ++ ) {
  45443. elementCount += counts[ i ] * primcount[ i ];
  45444. }
  45445. info.update( elementCount, mode, 1 );
  45446. }
  45447. }
  45448. //
  45449. this.setMode = setMode;
  45450. this.setIndex = setIndex;
  45451. this.render = render;
  45452. this.renderInstances = renderInstances;
  45453. this.renderMultiDraw = renderMultiDraw;
  45454. this.renderMultiDrawInstances = renderMultiDrawInstances;
  45455. }
  45456. function WebGLInfo( gl ) {
  45457. const memory = {
  45458. geometries: 0,
  45459. textures: 0
  45460. };
  45461. const render = {
  45462. frame: 0,
  45463. calls: 0,
  45464. triangles: 0,
  45465. points: 0,
  45466. lines: 0
  45467. };
  45468. function update( count, mode, instanceCount ) {
  45469. render.calls ++;
  45470. switch ( mode ) {
  45471. case gl.TRIANGLES:
  45472. render.triangles += instanceCount * ( count / 3 );
  45473. break;
  45474. case gl.LINES:
  45475. render.lines += instanceCount * ( count / 2 );
  45476. break;
  45477. case gl.LINE_STRIP:
  45478. render.lines += instanceCount * ( count - 1 );
  45479. break;
  45480. case gl.LINE_LOOP:
  45481. render.lines += instanceCount * count;
  45482. break;
  45483. case gl.POINTS:
  45484. render.points += instanceCount * count;
  45485. break;
  45486. default:
  45487. error( 'WebGLInfo: Unknown draw mode:', mode );
  45488. break;
  45489. }
  45490. }
  45491. function reset() {
  45492. render.calls = 0;
  45493. render.triangles = 0;
  45494. render.points = 0;
  45495. render.lines = 0;
  45496. }
  45497. return {
  45498. memory: memory,
  45499. render: render,
  45500. programs: null,
  45501. autoReset: true,
  45502. reset: reset,
  45503. update: update
  45504. };
  45505. }
  45506. function WebGLMorphtargets( gl, capabilities, textures ) {
  45507. const morphTextures = new WeakMap();
  45508. const morph = new Vector4();
  45509. function update( object, geometry, program ) {
  45510. const objectInfluences = object.morphTargetInfluences;
  45511. // the following encodes morph targets into an array of data textures. Each layer represents a single morph target.
  45512. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  45513. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  45514. let entry = morphTextures.get( geometry );
  45515. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  45516. if ( entry !== undefined ) entry.texture.dispose();
  45517. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  45518. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  45519. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  45520. const morphTargets = geometry.morphAttributes.position || [];
  45521. const morphNormals = geometry.morphAttributes.normal || [];
  45522. const morphColors = geometry.morphAttributes.color || [];
  45523. let vertexDataCount = 0;
  45524. if ( hasMorphPosition === true ) vertexDataCount = 1;
  45525. if ( hasMorphNormals === true ) vertexDataCount = 2;
  45526. if ( hasMorphColors === true ) vertexDataCount = 3;
  45527. let width = geometry.attributes.position.count * vertexDataCount;
  45528. let height = 1;
  45529. if ( width > capabilities.maxTextureSize ) {
  45530. height = Math.ceil( width / capabilities.maxTextureSize );
  45531. width = capabilities.maxTextureSize;
  45532. }
  45533. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  45534. const texture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  45535. texture.type = FloatType;
  45536. texture.needsUpdate = true;
  45537. // fill buffer
  45538. const vertexDataStride = vertexDataCount * 4;
  45539. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  45540. const morphTarget = morphTargets[ i ];
  45541. const morphNormal = morphNormals[ i ];
  45542. const morphColor = morphColors[ i ];
  45543. const offset = width * height * 4 * i;
  45544. for ( let j = 0; j < morphTarget.count; j ++ ) {
  45545. const stride = j * vertexDataStride;
  45546. if ( hasMorphPosition === true ) {
  45547. morph.fromBufferAttribute( morphTarget, j );
  45548. buffer[ offset + stride + 0 ] = morph.x;
  45549. buffer[ offset + stride + 1 ] = morph.y;
  45550. buffer[ offset + stride + 2 ] = morph.z;
  45551. buffer[ offset + stride + 3 ] = 0;
  45552. }
  45553. if ( hasMorphNormals === true ) {
  45554. morph.fromBufferAttribute( morphNormal, j );
  45555. buffer[ offset + stride + 4 ] = morph.x;
  45556. buffer[ offset + stride + 5 ] = morph.y;
  45557. buffer[ offset + stride + 6 ] = morph.z;
  45558. buffer[ offset + stride + 7 ] = 0;
  45559. }
  45560. if ( hasMorphColors === true ) {
  45561. morph.fromBufferAttribute( morphColor, j );
  45562. buffer[ offset + stride + 8 ] = morph.x;
  45563. buffer[ offset + stride + 9 ] = morph.y;
  45564. buffer[ offset + stride + 10 ] = morph.z;
  45565. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? morph.w : 1;
  45566. }
  45567. }
  45568. }
  45569. entry = {
  45570. count: morphTargetsCount,
  45571. texture: texture,
  45572. size: new Vector2( width, height )
  45573. };
  45574. morphTextures.set( geometry, entry );
  45575. function disposeTexture() {
  45576. texture.dispose();
  45577. morphTextures.delete( geometry );
  45578. geometry.removeEventListener( 'dispose', disposeTexture );
  45579. }
  45580. geometry.addEventListener( 'dispose', disposeTexture );
  45581. }
  45582. //
  45583. if ( object.isInstancedMesh === true && object.morphTexture !== null ) {
  45584. program.getUniforms().setValue( gl, 'morphTexture', object.morphTexture, textures );
  45585. } else {
  45586. let morphInfluencesSum = 0;
  45587. for ( let i = 0; i < objectInfluences.length; i ++ ) {
  45588. morphInfluencesSum += objectInfluences[ i ];
  45589. }
  45590. const morphBaseInfluence = geometry.morphTargetsRelative ? 1 : 1 - morphInfluencesSum;
  45591. program.getUniforms().setValue( gl, 'morphTargetBaseInfluence', morphBaseInfluence );
  45592. program.getUniforms().setValue( gl, 'morphTargetInfluences', objectInfluences );
  45593. }
  45594. program.getUniforms().setValue( gl, 'morphTargetsTexture', entry.texture, textures );
  45595. program.getUniforms().setValue( gl, 'morphTargetsTextureSize', entry.size );
  45596. }
  45597. return {
  45598. update: update
  45599. };
  45600. }
  45601. function WebGLObjects( gl, geometries, attributes, info ) {
  45602. let updateMap = new WeakMap();
  45603. function update( object ) {
  45604. const frame = info.render.frame;
  45605. const geometry = object.geometry;
  45606. const buffergeometry = geometries.get( object, geometry );
  45607. // Update once per frame
  45608. if ( updateMap.get( buffergeometry ) !== frame ) {
  45609. geometries.update( buffergeometry );
  45610. updateMap.set( buffergeometry, frame );
  45611. }
  45612. if ( object.isInstancedMesh ) {
  45613. if ( object.hasEventListener( 'dispose', onInstancedMeshDispose ) === false ) {
  45614. object.addEventListener( 'dispose', onInstancedMeshDispose );
  45615. }
  45616. if ( updateMap.get( object ) !== frame ) {
  45617. attributes.update( object.instanceMatrix, gl.ARRAY_BUFFER );
  45618. if ( object.instanceColor !== null ) {
  45619. attributes.update( object.instanceColor, gl.ARRAY_BUFFER );
  45620. }
  45621. updateMap.set( object, frame );
  45622. }
  45623. }
  45624. if ( object.isSkinnedMesh ) {
  45625. const skeleton = object.skeleton;
  45626. if ( updateMap.get( skeleton ) !== frame ) {
  45627. skeleton.update();
  45628. updateMap.set( skeleton, frame );
  45629. }
  45630. }
  45631. return buffergeometry;
  45632. }
  45633. function dispose() {
  45634. updateMap = new WeakMap();
  45635. }
  45636. function onInstancedMeshDispose( event ) {
  45637. const instancedMesh = event.target;
  45638. instancedMesh.removeEventListener( 'dispose', onInstancedMeshDispose );
  45639. attributes.remove( instancedMesh.instanceMatrix );
  45640. if ( instancedMesh.instanceColor !== null ) attributes.remove( instancedMesh.instanceColor );
  45641. }
  45642. return {
  45643. update: update,
  45644. dispose: dispose
  45645. };
  45646. }
  45647. /**
  45648. * Uniforms of a program.
  45649. * Those form a tree structure with a special top-level container for the root,
  45650. * which you get by calling 'new WebGLUniforms( gl, program )'.
  45651. *
  45652. *
  45653. * Properties of inner nodes including the top-level container:
  45654. *
  45655. * .seq - array of nested uniforms
  45656. * .map - nested uniforms by name
  45657. *
  45658. *
  45659. * Methods of all nodes except the top-level container:
  45660. *
  45661. * .setValue( gl, value, [textures] )
  45662. *
  45663. * uploads a uniform value(s)
  45664. * the 'textures' parameter is needed for sampler uniforms
  45665. *
  45666. *
  45667. * Static methods of the top-level container (textures factorizations):
  45668. *
  45669. * .upload( gl, seq, values, textures )
  45670. *
  45671. * sets uniforms in 'seq' to 'values[id].value'
  45672. *
  45673. * .seqWithValue( seq, values ) : filteredSeq
  45674. *
  45675. * filters 'seq' entries with corresponding entry in values
  45676. *
  45677. *
  45678. * Methods of the top-level container (textures factorizations):
  45679. *
  45680. * .setValue( gl, name, value, textures )
  45681. *
  45682. * sets uniform with name 'name' to 'value'
  45683. *
  45684. * .setOptional( gl, obj, prop )
  45685. *
  45686. * like .set for an optional property of the object
  45687. *
  45688. */
  45689. const emptyTexture = /*@__PURE__*/ new Texture();
  45690. const emptyShadowTexture = /*@__PURE__*/ new DepthTexture( 1, 1 );
  45691. const emptyArrayTexture = /*@__PURE__*/ new DataArrayTexture();
  45692. const empty3dTexture = /*@__PURE__*/ new Data3DTexture();
  45693. const emptyCubeTexture = /*@__PURE__*/ new CubeTexture();
  45694. // --- Utilities ---
  45695. // Array Caches (provide typed arrays for temporary by size)
  45696. const arrayCacheF32 = [];
  45697. const arrayCacheI32 = [];
  45698. // Float32Array caches used for uploading Matrix uniforms
  45699. const mat4array = new Float32Array( 16 );
  45700. const mat3array = new Float32Array( 9 );
  45701. const mat2array = new Float32Array( 4 );
  45702. // Flattening for arrays of vectors and matrices
  45703. function flatten( array, nBlocks, blockSize ) {
  45704. const firstElem = array[ 0 ];
  45705. if ( firstElem <= 0 || firstElem > 0 ) return array;
  45706. // unoptimized: ! isNaN( firstElem )
  45707. // see http://jacksondunstan.com/articles/983
  45708. const n = nBlocks * blockSize;
  45709. let r = arrayCacheF32[ n ];
  45710. if ( r === undefined ) {
  45711. r = new Float32Array( n );
  45712. arrayCacheF32[ n ] = r;
  45713. }
  45714. if ( nBlocks !== 0 ) {
  45715. firstElem.toArray( r, 0 );
  45716. for ( let i = 1, offset = 0; i !== nBlocks; ++ i ) {
  45717. offset += blockSize;
  45718. array[ i ].toArray( r, offset );
  45719. }
  45720. }
  45721. return r;
  45722. }
  45723. function arraysEqual( a, b ) {
  45724. if ( a.length !== b.length ) return false;
  45725. for ( let i = 0, l = a.length; i < l; i ++ ) {
  45726. if ( a[ i ] !== b[ i ] ) return false;
  45727. }
  45728. return true;
  45729. }
  45730. function copyArray( a, b ) {
  45731. for ( let i = 0, l = b.length; i < l; i ++ ) {
  45732. a[ i ] = b[ i ];
  45733. }
  45734. }
  45735. // Texture unit allocation
  45736. function allocTexUnits( textures, n ) {
  45737. let r = arrayCacheI32[ n ];
  45738. if ( r === undefined ) {
  45739. r = new Int32Array( n );
  45740. arrayCacheI32[ n ] = r;
  45741. }
  45742. for ( let i = 0; i !== n; ++ i ) {
  45743. r[ i ] = textures.allocateTextureUnit();
  45744. }
  45745. return r;
  45746. }
  45747. // --- Setters ---
  45748. // Note: Defining these methods externally, because they come in a bunch
  45749. // and this way their names minify.
  45750. // Single scalar
  45751. function setValueV1f( gl, v ) {
  45752. const cache = this.cache;
  45753. if ( cache[ 0 ] === v ) return;
  45754. gl.uniform1f( this.addr, v );
  45755. cache[ 0 ] = v;
  45756. }
  45757. // Single float vector (from flat array or THREE.VectorN)
  45758. function setValueV2f( gl, v ) {
  45759. const cache = this.cache;
  45760. if ( v.x !== undefined ) {
  45761. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45762. gl.uniform2f( this.addr, v.x, v.y );
  45763. cache[ 0 ] = v.x;
  45764. cache[ 1 ] = v.y;
  45765. }
  45766. } else {
  45767. if ( arraysEqual( cache, v ) ) return;
  45768. gl.uniform2fv( this.addr, v );
  45769. copyArray( cache, v );
  45770. }
  45771. }
  45772. function setValueV3f( gl, v ) {
  45773. const cache = this.cache;
  45774. if ( v.x !== undefined ) {
  45775. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45776. gl.uniform3f( this.addr, v.x, v.y, v.z );
  45777. cache[ 0 ] = v.x;
  45778. cache[ 1 ] = v.y;
  45779. cache[ 2 ] = v.z;
  45780. }
  45781. } else if ( v.r !== undefined ) {
  45782. if ( cache[ 0 ] !== v.r || cache[ 1 ] !== v.g || cache[ 2 ] !== v.b ) {
  45783. gl.uniform3f( this.addr, v.r, v.g, v.b );
  45784. cache[ 0 ] = v.r;
  45785. cache[ 1 ] = v.g;
  45786. cache[ 2 ] = v.b;
  45787. }
  45788. } else {
  45789. if ( arraysEqual( cache, v ) ) return;
  45790. gl.uniform3fv( this.addr, v );
  45791. copyArray( cache, v );
  45792. }
  45793. }
  45794. function setValueV4f( gl, v ) {
  45795. const cache = this.cache;
  45796. if ( v.x !== undefined ) {
  45797. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45798. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  45799. cache[ 0 ] = v.x;
  45800. cache[ 1 ] = v.y;
  45801. cache[ 2 ] = v.z;
  45802. cache[ 3 ] = v.w;
  45803. }
  45804. } else {
  45805. if ( arraysEqual( cache, v ) ) return;
  45806. gl.uniform4fv( this.addr, v );
  45807. copyArray( cache, v );
  45808. }
  45809. }
  45810. // Single matrix (from flat array or THREE.MatrixN)
  45811. function setValueM2( gl, v ) {
  45812. const cache = this.cache;
  45813. const elements = v.elements;
  45814. if ( elements === undefined ) {
  45815. if ( arraysEqual( cache, v ) ) return;
  45816. gl.uniformMatrix2fv( this.addr, false, v );
  45817. copyArray( cache, v );
  45818. } else {
  45819. if ( arraysEqual( cache, elements ) ) return;
  45820. mat2array.set( elements );
  45821. gl.uniformMatrix2fv( this.addr, false, mat2array );
  45822. copyArray( cache, elements );
  45823. }
  45824. }
  45825. function setValueM3( gl, v ) {
  45826. const cache = this.cache;
  45827. const elements = v.elements;
  45828. if ( elements === undefined ) {
  45829. if ( arraysEqual( cache, v ) ) return;
  45830. gl.uniformMatrix3fv( this.addr, false, v );
  45831. copyArray( cache, v );
  45832. } else {
  45833. if ( arraysEqual( cache, elements ) ) return;
  45834. mat3array.set( elements );
  45835. gl.uniformMatrix3fv( this.addr, false, mat3array );
  45836. copyArray( cache, elements );
  45837. }
  45838. }
  45839. function setValueM4( gl, v ) {
  45840. const cache = this.cache;
  45841. const elements = v.elements;
  45842. if ( elements === undefined ) {
  45843. if ( arraysEqual( cache, v ) ) return;
  45844. gl.uniformMatrix4fv( this.addr, false, v );
  45845. copyArray( cache, v );
  45846. } else {
  45847. if ( arraysEqual( cache, elements ) ) return;
  45848. mat4array.set( elements );
  45849. gl.uniformMatrix4fv( this.addr, false, mat4array );
  45850. copyArray( cache, elements );
  45851. }
  45852. }
  45853. // Single integer / boolean
  45854. function setValueV1i( gl, v ) {
  45855. const cache = this.cache;
  45856. if ( cache[ 0 ] === v ) return;
  45857. gl.uniform1i( this.addr, v );
  45858. cache[ 0 ] = v;
  45859. }
  45860. // Single integer / boolean vector (from flat array or THREE.VectorN)
  45861. function setValueV2i( gl, v ) {
  45862. const cache = this.cache;
  45863. if ( v.x !== undefined ) {
  45864. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45865. gl.uniform2i( this.addr, v.x, v.y );
  45866. cache[ 0 ] = v.x;
  45867. cache[ 1 ] = v.y;
  45868. }
  45869. } else {
  45870. if ( arraysEqual( cache, v ) ) return;
  45871. gl.uniform2iv( this.addr, v );
  45872. copyArray( cache, v );
  45873. }
  45874. }
  45875. function setValueV3i( gl, v ) {
  45876. const cache = this.cache;
  45877. if ( v.x !== undefined ) {
  45878. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z ) {
  45879. gl.uniform3i( this.addr, v.x, v.y, v.z );
  45880. cache[ 0 ] = v.x;
  45881. cache[ 1 ] = v.y;
  45882. cache[ 2 ] = v.z;
  45883. }
  45884. } else {
  45885. if ( arraysEqual( cache, v ) ) return;
  45886. gl.uniform3iv( this.addr, v );
  45887. copyArray( cache, v );
  45888. }
  45889. }
  45890. function setValueV4i( gl, v ) {
  45891. const cache = this.cache;
  45892. if ( v.x !== undefined ) {
  45893. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45894. gl.uniform4i( this.addr, v.x, v.y, v.z, v.w );
  45895. cache[ 0 ] = v.x;
  45896. cache[ 1 ] = v.y;
  45897. cache[ 2 ] = v.z;
  45898. cache[ 3 ] = v.w;
  45899. }
  45900. } else {
  45901. if ( arraysEqual( cache, v ) ) return;
  45902. gl.uniform4iv( this.addr, v );
  45903. copyArray( cache, v );
  45904. }
  45905. }
  45906. // Single unsigned integer
  45907. function setValueV1ui( gl, v ) {
  45908. const cache = this.cache;
  45909. if ( cache[ 0 ] === v ) return;
  45910. gl.uniform1ui( this.addr, v );
  45911. cache[ 0 ] = v;
  45912. }
  45913. // Single unsigned integer vector (from flat array or THREE.VectorN)
  45914. function setValueV2ui( gl, v ) {
  45915. const cache = this.cache;
  45916. if ( v.x !== undefined ) {
  45917. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y ) {
  45918. gl.uniform2ui( 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.uniform2uiv( this.addr, v );
  45925. copyArray( cache, v );
  45926. }
  45927. }
  45928. function setValueV3ui( 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.uniform3ui( 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 {
  45938. if ( arraysEqual( cache, v ) ) return;
  45939. gl.uniform3uiv( this.addr, v );
  45940. copyArray( cache, v );
  45941. }
  45942. }
  45943. function setValueV4ui( gl, v ) {
  45944. const cache = this.cache;
  45945. if ( v.x !== undefined ) {
  45946. if ( cache[ 0 ] !== v.x || cache[ 1 ] !== v.y || cache[ 2 ] !== v.z || cache[ 3 ] !== v.w ) {
  45947. gl.uniform4ui( this.addr, v.x, v.y, v.z, v.w );
  45948. cache[ 0 ] = v.x;
  45949. cache[ 1 ] = v.y;
  45950. cache[ 2 ] = v.z;
  45951. cache[ 3 ] = v.w;
  45952. }
  45953. } else {
  45954. if ( arraysEqual( cache, v ) ) return;
  45955. gl.uniform4uiv( this.addr, v );
  45956. copyArray( cache, v );
  45957. }
  45958. }
  45959. // Single texture (2D / Cube)
  45960. function setValueT1( gl, v, textures ) {
  45961. const cache = this.cache;
  45962. const unit = textures.allocateTextureUnit();
  45963. if ( cache[ 0 ] !== unit ) {
  45964. gl.uniform1i( this.addr, unit );
  45965. cache[ 0 ] = unit;
  45966. }
  45967. let emptyTexture2D;
  45968. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  45969. emptyShadowTexture.compareFunction = textures.isReversedDepthBuffer() ? GreaterEqualCompare : LessEqualCompare;
  45970. emptyTexture2D = emptyShadowTexture;
  45971. } else {
  45972. emptyTexture2D = emptyTexture;
  45973. }
  45974. textures.setTexture2D( v || emptyTexture2D, unit );
  45975. }
  45976. function setValueT3D1( gl, v, textures ) {
  45977. const cache = this.cache;
  45978. const unit = textures.allocateTextureUnit();
  45979. if ( cache[ 0 ] !== unit ) {
  45980. gl.uniform1i( this.addr, unit );
  45981. cache[ 0 ] = unit;
  45982. }
  45983. textures.setTexture3D( v || empty3dTexture, unit );
  45984. }
  45985. function setValueT6( gl, v, textures ) {
  45986. const cache = this.cache;
  45987. const unit = textures.allocateTextureUnit();
  45988. if ( cache[ 0 ] !== unit ) {
  45989. gl.uniform1i( this.addr, unit );
  45990. cache[ 0 ] = unit;
  45991. }
  45992. textures.setTextureCube( v || emptyCubeTexture, unit );
  45993. }
  45994. function setValueT2DArray1( gl, v, textures ) {
  45995. const cache = this.cache;
  45996. const unit = textures.allocateTextureUnit();
  45997. if ( cache[ 0 ] !== unit ) {
  45998. gl.uniform1i( this.addr, unit );
  45999. cache[ 0 ] = unit;
  46000. }
  46001. textures.setTexture2DArray( v || emptyArrayTexture, unit );
  46002. }
  46003. // Helper to pick the right setter for the singular case
  46004. function getSingularSetter( type ) {
  46005. switch ( type ) {
  46006. case 0x1406: return setValueV1f; // FLOAT
  46007. case 0x8b50: return setValueV2f; // _VEC2
  46008. case 0x8b51: return setValueV3f; // _VEC3
  46009. case 0x8b52: return setValueV4f; // _VEC4
  46010. case 0x8b5a: return setValueM2; // _MAT2
  46011. case 0x8b5b: return setValueM3; // _MAT3
  46012. case 0x8b5c: return setValueM4; // _MAT4
  46013. case 0x1404: case 0x8b56: return setValueV1i; // INT, BOOL
  46014. case 0x8b53: case 0x8b57: return setValueV2i; // _VEC2
  46015. case 0x8b54: case 0x8b58: return setValueV3i; // _VEC3
  46016. case 0x8b55: case 0x8b59: return setValueV4i; // _VEC4
  46017. case 0x1405: return setValueV1ui; // UINT
  46018. case 0x8dc6: return setValueV2ui; // _VEC2
  46019. case 0x8dc7: return setValueV3ui; // _VEC3
  46020. case 0x8dc8: return setValueV4ui; // _VEC4
  46021. case 0x8b5e: // SAMPLER_2D
  46022. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46023. case 0x8dca: // INT_SAMPLER_2D
  46024. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46025. case 0x8b62: // SAMPLER_2D_SHADOW
  46026. return setValueT1;
  46027. case 0x8b5f: // SAMPLER_3D
  46028. case 0x8dcb: // INT_SAMPLER_3D
  46029. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46030. return setValueT3D1;
  46031. case 0x8b60: // SAMPLER_CUBE
  46032. case 0x8dcc: // INT_SAMPLER_CUBE
  46033. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46034. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46035. return setValueT6;
  46036. case 0x8dc1: // SAMPLER_2D_ARRAY
  46037. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46038. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46039. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46040. return setValueT2DArray1;
  46041. }
  46042. }
  46043. // Array of scalars
  46044. function setValueV1fArray( gl, v ) {
  46045. gl.uniform1fv( this.addr, v );
  46046. }
  46047. // Array of vectors (from flat array or array of THREE.VectorN)
  46048. function setValueV2fArray( gl, v ) {
  46049. const data = flatten( v, this.size, 2 );
  46050. gl.uniform2fv( this.addr, data );
  46051. }
  46052. function setValueV3fArray( gl, v ) {
  46053. const data = flatten( v, this.size, 3 );
  46054. gl.uniform3fv( this.addr, data );
  46055. }
  46056. function setValueV4fArray( gl, v ) {
  46057. const data = flatten( v, this.size, 4 );
  46058. gl.uniform4fv( this.addr, data );
  46059. }
  46060. // Array of matrices (from flat array or array of THREE.MatrixN)
  46061. function setValueM2Array( gl, v ) {
  46062. const data = flatten( v, this.size, 4 );
  46063. gl.uniformMatrix2fv( this.addr, false, data );
  46064. }
  46065. function setValueM3Array( gl, v ) {
  46066. const data = flatten( v, this.size, 9 );
  46067. gl.uniformMatrix3fv( this.addr, false, data );
  46068. }
  46069. function setValueM4Array( gl, v ) {
  46070. const data = flatten( v, this.size, 16 );
  46071. gl.uniformMatrix4fv( this.addr, false, data );
  46072. }
  46073. // Array of integer / boolean
  46074. function setValueV1iArray( gl, v ) {
  46075. gl.uniform1iv( this.addr, v );
  46076. }
  46077. // Array of integer / boolean vectors (from flat array)
  46078. function setValueV2iArray( gl, v ) {
  46079. gl.uniform2iv( this.addr, v );
  46080. }
  46081. function setValueV3iArray( gl, v ) {
  46082. gl.uniform3iv( this.addr, v );
  46083. }
  46084. function setValueV4iArray( gl, v ) {
  46085. gl.uniform4iv( this.addr, v );
  46086. }
  46087. // Array of unsigned integer
  46088. function setValueV1uiArray( gl, v ) {
  46089. gl.uniform1uiv( this.addr, v );
  46090. }
  46091. // Array of unsigned integer vectors (from flat array)
  46092. function setValueV2uiArray( gl, v ) {
  46093. gl.uniform2uiv( this.addr, v );
  46094. }
  46095. function setValueV3uiArray( gl, v ) {
  46096. gl.uniform3uiv( this.addr, v );
  46097. }
  46098. function setValueV4uiArray( gl, v ) {
  46099. gl.uniform4uiv( this.addr, v );
  46100. }
  46101. // Array of textures (2D / 3D / Cube / 2DArray)
  46102. function setValueT1Array( gl, v, textures ) {
  46103. const cache = this.cache;
  46104. const n = v.length;
  46105. const units = allocTexUnits( textures, n );
  46106. if ( ! arraysEqual( cache, units ) ) {
  46107. gl.uniform1iv( this.addr, units );
  46108. copyArray( cache, units );
  46109. }
  46110. let emptyTexture2D;
  46111. if ( this.type === gl.SAMPLER_2D_SHADOW ) {
  46112. emptyTexture2D = emptyShadowTexture;
  46113. } else {
  46114. emptyTexture2D = emptyTexture;
  46115. }
  46116. for ( let i = 0; i !== n; ++ i ) {
  46117. textures.setTexture2D( v[ i ] || emptyTexture2D, units[ i ] );
  46118. }
  46119. }
  46120. function setValueT3DArray( gl, v, textures ) {
  46121. const cache = this.cache;
  46122. const n = v.length;
  46123. const units = allocTexUnits( textures, n );
  46124. if ( ! arraysEqual( cache, units ) ) {
  46125. gl.uniform1iv( this.addr, units );
  46126. copyArray( cache, units );
  46127. }
  46128. for ( let i = 0; i !== n; ++ i ) {
  46129. textures.setTexture3D( v[ i ] || empty3dTexture, units[ i ] );
  46130. }
  46131. }
  46132. function setValueT6Array( gl, v, textures ) {
  46133. const cache = this.cache;
  46134. const n = v.length;
  46135. const units = allocTexUnits( textures, n );
  46136. if ( ! arraysEqual( cache, units ) ) {
  46137. gl.uniform1iv( this.addr, units );
  46138. copyArray( cache, units );
  46139. }
  46140. for ( let i = 0; i !== n; ++ i ) {
  46141. textures.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  46142. }
  46143. }
  46144. function setValueT2DArrayArray( gl, v, textures ) {
  46145. const cache = this.cache;
  46146. const n = v.length;
  46147. const units = allocTexUnits( textures, n );
  46148. if ( ! arraysEqual( cache, units ) ) {
  46149. gl.uniform1iv( this.addr, units );
  46150. copyArray( cache, units );
  46151. }
  46152. for ( let i = 0; i !== n; ++ i ) {
  46153. textures.setTexture2DArray( v[ i ] || emptyArrayTexture, units[ i ] );
  46154. }
  46155. }
  46156. // Helper to pick the right setter for a pure (bottom-level) array
  46157. function getPureArraySetter( type ) {
  46158. switch ( type ) {
  46159. case 0x1406: return setValueV1fArray; // FLOAT
  46160. case 0x8b50: return setValueV2fArray; // _VEC2
  46161. case 0x8b51: return setValueV3fArray; // _VEC3
  46162. case 0x8b52: return setValueV4fArray; // _VEC4
  46163. case 0x8b5a: return setValueM2Array; // _MAT2
  46164. case 0x8b5b: return setValueM3Array; // _MAT3
  46165. case 0x8b5c: return setValueM4Array; // _MAT4
  46166. case 0x1404: case 0x8b56: return setValueV1iArray; // INT, BOOL
  46167. case 0x8b53: case 0x8b57: return setValueV2iArray; // _VEC2
  46168. case 0x8b54: case 0x8b58: return setValueV3iArray; // _VEC3
  46169. case 0x8b55: case 0x8b59: return setValueV4iArray; // _VEC4
  46170. case 0x1405: return setValueV1uiArray; // UINT
  46171. case 0x8dc6: return setValueV2uiArray; // _VEC2
  46172. case 0x8dc7: return setValueV3uiArray; // _VEC3
  46173. case 0x8dc8: return setValueV4uiArray; // _VEC4
  46174. case 0x8b5e: // SAMPLER_2D
  46175. case 0x8d66: // SAMPLER_EXTERNAL_OES
  46176. case 0x8dca: // INT_SAMPLER_2D
  46177. case 0x8dd2: // UNSIGNED_INT_SAMPLER_2D
  46178. case 0x8b62: // SAMPLER_2D_SHADOW
  46179. return setValueT1Array;
  46180. case 0x8b5f: // SAMPLER_3D
  46181. case 0x8dcb: // INT_SAMPLER_3D
  46182. case 0x8dd3: // UNSIGNED_INT_SAMPLER_3D
  46183. return setValueT3DArray;
  46184. case 0x8b60: // SAMPLER_CUBE
  46185. case 0x8dcc: // INT_SAMPLER_CUBE
  46186. case 0x8dd4: // UNSIGNED_INT_SAMPLER_CUBE
  46187. case 0x8dc5: // SAMPLER_CUBE_SHADOW
  46188. return setValueT6Array;
  46189. case 0x8dc1: // SAMPLER_2D_ARRAY
  46190. case 0x8dcf: // INT_SAMPLER_2D_ARRAY
  46191. case 0x8dd7: // UNSIGNED_INT_SAMPLER_2D_ARRAY
  46192. case 0x8dc4: // SAMPLER_2D_ARRAY_SHADOW
  46193. return setValueT2DArrayArray;
  46194. }
  46195. }
  46196. // --- Uniform Classes ---
  46197. class SingleUniform {
  46198. constructor( id, activeInfo, addr ) {
  46199. this.id = id;
  46200. this.addr = addr;
  46201. this.cache = [];
  46202. this.type = activeInfo.type;
  46203. this.setValue = getSingularSetter( activeInfo.type );
  46204. // this.path = activeInfo.name; // DEBUG
  46205. }
  46206. }
  46207. class PureArrayUniform {
  46208. constructor( id, activeInfo, addr ) {
  46209. this.id = id;
  46210. this.addr = addr;
  46211. this.cache = [];
  46212. this.type = activeInfo.type;
  46213. this.size = activeInfo.size;
  46214. this.setValue = getPureArraySetter( activeInfo.type );
  46215. // this.path = activeInfo.name; // DEBUG
  46216. }
  46217. }
  46218. class StructuredUniform {
  46219. constructor( id ) {
  46220. this.id = id;
  46221. this.seq = [];
  46222. this.map = {};
  46223. }
  46224. setValue( gl, value, textures ) {
  46225. const seq = this.seq;
  46226. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46227. const u = seq[ i ];
  46228. u.setValue( gl, value[ u.id ], textures );
  46229. }
  46230. }
  46231. }
  46232. // --- Top-level ---
  46233. // Parser - builds up the property tree from the path strings
  46234. const RePathPart = /(\w+)(\])?(\[|\.)?/g;
  46235. // extracts
  46236. // - the identifier (member name or array index)
  46237. // - followed by an optional right bracket (found when array index)
  46238. // - followed by an optional left bracket or dot (type of subscript)
  46239. //
  46240. // Note: These portions can be read in a non-overlapping fashion and
  46241. // allow straightforward parsing of the hierarchy that WebGL encodes
  46242. // in the uniform names.
  46243. function addUniform( container, uniformObject ) {
  46244. container.seq.push( uniformObject );
  46245. container.map[ uniformObject.id ] = uniformObject;
  46246. }
  46247. function parseUniform( activeInfo, addr, container ) {
  46248. const path = activeInfo.name,
  46249. pathLength = path.length;
  46250. // reset RegExp object, because of the early exit of a previous run
  46251. RePathPart.lastIndex = 0;
  46252. while ( true ) {
  46253. const match = RePathPart.exec( path ),
  46254. matchEnd = RePathPart.lastIndex;
  46255. let id = match[ 1 ];
  46256. const idIsIndex = match[ 2 ] === ']',
  46257. subscript = match[ 3 ];
  46258. if ( idIsIndex ) id = id | 0; // convert to integer
  46259. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  46260. // bare name or "pure" bottom-level array "[0]" suffix
  46261. addUniform( container, subscript === undefined ?
  46262. new SingleUniform( id, activeInfo, addr ) :
  46263. new PureArrayUniform( id, activeInfo, addr ) );
  46264. break;
  46265. } else {
  46266. // step into inner node / create it in case it doesn't exist
  46267. const map = container.map;
  46268. let next = map[ id ];
  46269. if ( next === undefined ) {
  46270. next = new StructuredUniform( id );
  46271. addUniform( container, next );
  46272. }
  46273. container = next;
  46274. }
  46275. }
  46276. }
  46277. // Root Container
  46278. class WebGLUniforms {
  46279. constructor( gl, program ) {
  46280. this.seq = [];
  46281. this.map = {};
  46282. const n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  46283. for ( let i = 0; i < n; ++ i ) {
  46284. const info = gl.getActiveUniform( program, i ),
  46285. addr = gl.getUniformLocation( program, info.name );
  46286. parseUniform( info, addr, this );
  46287. }
  46288. // Sort uniforms to prioritize shadow samplers first (for optimal texture unit allocation)
  46289. const shadowSamplers = [];
  46290. const otherUniforms = [];
  46291. for ( const u of this.seq ) {
  46292. if ( u.type === gl.SAMPLER_2D_SHADOW || u.type === gl.SAMPLER_CUBE_SHADOW || u.type === gl.SAMPLER_2D_ARRAY_SHADOW ) {
  46293. shadowSamplers.push( u );
  46294. } else {
  46295. otherUniforms.push( u );
  46296. }
  46297. }
  46298. if ( shadowSamplers.length > 0 ) {
  46299. this.seq = shadowSamplers.concat( otherUniforms );
  46300. }
  46301. }
  46302. setValue( gl, name, value, textures ) {
  46303. const u = this.map[ name ];
  46304. if ( u !== undefined ) u.setValue( gl, value, textures );
  46305. }
  46306. setOptional( gl, object, name ) {
  46307. const v = object[ name ];
  46308. if ( v !== undefined ) this.setValue( gl, name, v );
  46309. }
  46310. static upload( gl, seq, values, textures ) {
  46311. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46312. const u = seq[ i ],
  46313. v = values[ u.id ];
  46314. if ( v.needsUpdate !== false ) {
  46315. // note: always updating when .needsUpdate is undefined
  46316. u.setValue( gl, v.value, textures );
  46317. }
  46318. }
  46319. }
  46320. static seqWithValue( seq, values ) {
  46321. const r = [];
  46322. for ( let i = 0, n = seq.length; i !== n; ++ i ) {
  46323. const u = seq[ i ];
  46324. if ( u.id in values ) r.push( u );
  46325. }
  46326. return r;
  46327. }
  46328. }
  46329. function WebGLShader( gl, type, string ) {
  46330. const shader = gl.createShader( type );
  46331. gl.shaderSource( shader, string );
  46332. gl.compileShader( shader );
  46333. return shader;
  46334. }
  46335. // From https://www.khronos.org/registry/webgl/extensions/KHR_parallel_shader_compile/
  46336. const COMPLETION_STATUS_KHR = 0x91B1;
  46337. let programIdCount = 0;
  46338. function handleSource( string, errorLine ) {
  46339. const lines = string.split( '\n' );
  46340. const lines2 = [];
  46341. const from = Math.max( errorLine - 6, 0 );
  46342. const to = Math.min( errorLine + 6, lines.length );
  46343. for ( let i = from; i < to; i ++ ) {
  46344. const line = i + 1;
  46345. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46346. }
  46347. return lines2.join( '\n' );
  46348. }
  46349. const _m0 = /*@__PURE__*/ new Matrix3();
  46350. function getEncodingComponents( colorSpace ) {
  46351. ColorManagement._getMatrix( _m0, ColorManagement.workingColorSpace, colorSpace );
  46352. const encodingMatrix = `mat3( ${ _m0.elements.map( ( v ) => v.toFixed( 4 ) ) } )`;
  46353. switch ( ColorManagement.getTransfer( colorSpace ) ) {
  46354. case LinearTransfer:
  46355. return [ encodingMatrix, 'LinearTransferOETF' ];
  46356. case SRGBTransfer:
  46357. return [ encodingMatrix, 'sRGBTransferOETF' ];
  46358. default:
  46359. warn( 'WebGLProgram: Unsupported color space: ', colorSpace );
  46360. return [ encodingMatrix, 'LinearTransferOETF' ];
  46361. }
  46362. }
  46363. function getShaderErrors( gl, shader, type ) {
  46364. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46365. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46366. const errors = shaderInfoLog.trim();
  46367. if ( status && errors === '' ) return '';
  46368. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46369. if ( errorMatches ) {
  46370. // --enable-privileged-webgl-extension
  46371. // log( '**' + type + '**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  46372. const errorLine = parseInt( errorMatches[ 1 ] );
  46373. return type.toUpperCase() + '\n\n' + errors + '\n\n' + handleSource( gl.getShaderSource( shader ), errorLine );
  46374. } else {
  46375. return errors;
  46376. }
  46377. }
  46378. function getTexelEncodingFunction( functionName, colorSpace ) {
  46379. const components = getEncodingComponents( colorSpace );
  46380. return [
  46381. `vec4 ${functionName}( vec4 value ) {`,
  46382. ` return ${components[ 1 ]}( vec4( value.rgb * ${components[ 0 ]}, value.a ) );`,
  46383. '}',
  46384. ].join( '\n' );
  46385. }
  46386. function getToneMappingFunction( functionName, toneMapping ) {
  46387. let toneMappingName;
  46388. switch ( toneMapping ) {
  46389. case LinearToneMapping:
  46390. toneMappingName = 'Linear';
  46391. break;
  46392. case ReinhardToneMapping:
  46393. toneMappingName = 'Reinhard';
  46394. break;
  46395. case CineonToneMapping:
  46396. toneMappingName = 'Cineon';
  46397. break;
  46398. case ACESFilmicToneMapping:
  46399. toneMappingName = 'ACESFilmic';
  46400. break;
  46401. case AgXToneMapping:
  46402. toneMappingName = 'AgX';
  46403. break;
  46404. case NeutralToneMapping:
  46405. toneMappingName = 'Neutral';
  46406. break;
  46407. case CustomToneMapping:
  46408. toneMappingName = 'Custom';
  46409. break;
  46410. default:
  46411. warn( 'WebGLProgram: Unsupported toneMapping:', toneMapping );
  46412. toneMappingName = 'Linear';
  46413. }
  46414. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  46415. }
  46416. const _v0 = /*@__PURE__*/ new Vector3();
  46417. function getLuminanceFunction() {
  46418. ColorManagement.getLuminanceCoefficients( _v0 );
  46419. const r = _v0.x.toFixed( 4 );
  46420. const g = _v0.y.toFixed( 4 );
  46421. const b = _v0.z.toFixed( 4 );
  46422. return [
  46423. 'float luminance( const in vec3 rgb ) {',
  46424. ` const vec3 weights = vec3( ${ r }, ${ g }, ${ b } );`,
  46425. ' return dot( weights, rgb );',
  46426. '}'
  46427. ].join( '\n' );
  46428. }
  46429. function generateVertexExtensions( parameters ) {
  46430. const chunks = [
  46431. parameters.extensionClipCullDistance ? '#extension GL_ANGLE_clip_cull_distance : require' : '',
  46432. parameters.extensionMultiDraw ? '#extension GL_ANGLE_multi_draw : require' : '',
  46433. ];
  46434. return chunks.filter( filterEmptyLine ).join( '\n' );
  46435. }
  46436. function generateDefines( defines ) {
  46437. const chunks = [];
  46438. for ( const name in defines ) {
  46439. const value = defines[ name ];
  46440. if ( value === false ) continue;
  46441. chunks.push( '#define ' + name + ' ' + value );
  46442. }
  46443. return chunks.join( '\n' );
  46444. }
  46445. function fetchAttributeLocations( gl, program ) {
  46446. const attributes = {};
  46447. const n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  46448. for ( let i = 0; i < n; i ++ ) {
  46449. const info = gl.getActiveAttrib( program, i );
  46450. const name = info.name;
  46451. let locationSize = 1;
  46452. if ( info.type === gl.FLOAT_MAT2 ) locationSize = 2;
  46453. if ( info.type === gl.FLOAT_MAT3 ) locationSize = 3;
  46454. if ( info.type === gl.FLOAT_MAT4 ) locationSize = 4;
  46455. // log( 'WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  46456. attributes[ name ] = {
  46457. type: info.type,
  46458. location: gl.getAttribLocation( program, name ),
  46459. locationSize: locationSize
  46460. };
  46461. }
  46462. return attributes;
  46463. }
  46464. function filterEmptyLine( string ) {
  46465. return string !== '';
  46466. }
  46467. function replaceLightNums( string, parameters ) {
  46468. const numSpotLightCoords = parameters.numSpotLightShadows + parameters.numSpotLightMaps - parameters.numSpotLightShadowsWithMaps;
  46469. return string
  46470. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  46471. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  46472. .replace( /NUM_SPOT_LIGHT_MAPS/g, parameters.numSpotLightMaps )
  46473. .replace( /NUM_SPOT_LIGHT_COORDS/g, numSpotLightCoords )
  46474. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  46475. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  46476. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights )
  46477. .replace( /NUM_DIR_LIGHT_SHADOWS/g, parameters.numDirLightShadows )
  46478. .replace( /NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, parameters.numSpotLightShadowsWithMaps )
  46479. .replace( /NUM_SPOT_LIGHT_SHADOWS/g, parameters.numSpotLightShadows )
  46480. .replace( /NUM_POINT_LIGHT_SHADOWS/g, parameters.numPointLightShadows );
  46481. }
  46482. function replaceClippingPlaneNums( string, parameters ) {
  46483. return string
  46484. .replace( /NUM_CLIPPING_PLANES/g, parameters.numClippingPlanes )
  46485. .replace( /UNION_CLIPPING_PLANES/g, ( parameters.numClippingPlanes - parameters.numClipIntersection ) );
  46486. }
  46487. // Resolve Includes
  46488. const includePattern = /^[ \t]*#include +<([\w\d./]+)>/gm;
  46489. function resolveIncludes( string ) {
  46490. return string.replace( includePattern, includeReplacer );
  46491. }
  46492. const shaderChunkMap = new Map();
  46493. function includeReplacer( match, include ) {
  46494. let string = ShaderChunk[ include ];
  46495. if ( string === undefined ) {
  46496. const newInclude = shaderChunkMap.get( include );
  46497. if ( newInclude !== undefined ) {
  46498. string = ShaderChunk[ newInclude ];
  46499. warn( 'WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', include, newInclude );
  46500. } else {
  46501. throw new Error( 'Can not resolve #include <' + include + '>' );
  46502. }
  46503. }
  46504. return resolveIncludes( string );
  46505. }
  46506. // Unroll Loops
  46507. 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;
  46508. function unrollLoops( string ) {
  46509. return string.replace( unrollLoopPattern, loopReplacer );
  46510. }
  46511. function loopReplacer( match, start, end, snippet ) {
  46512. let string = '';
  46513. for ( let i = parseInt( start ); i < parseInt( end ); i ++ ) {
  46514. string += snippet
  46515. .replace( /\[\s*i\s*\]/g, '[ ' + i + ' ]' )
  46516. .replace( /UNROLLED_LOOP_INDEX/g, i );
  46517. }
  46518. return string;
  46519. }
  46520. //
  46521. function generatePrecision( parameters ) {
  46522. let precisionstring = `precision ${parameters.precision} float;
  46523. precision ${parameters.precision} int;
  46524. precision ${parameters.precision} sampler2D;
  46525. precision ${parameters.precision} samplerCube;
  46526. precision ${parameters.precision} sampler3D;
  46527. precision ${parameters.precision} sampler2DArray;
  46528. precision ${parameters.precision} sampler2DShadow;
  46529. precision ${parameters.precision} samplerCubeShadow;
  46530. precision ${parameters.precision} sampler2DArrayShadow;
  46531. precision ${parameters.precision} isampler2D;
  46532. precision ${parameters.precision} isampler3D;
  46533. precision ${parameters.precision} isamplerCube;
  46534. precision ${parameters.precision} isampler2DArray;
  46535. precision ${parameters.precision} usampler2D;
  46536. precision ${parameters.precision} usampler3D;
  46537. precision ${parameters.precision} usamplerCube;
  46538. precision ${parameters.precision} usampler2DArray;
  46539. `;
  46540. if ( parameters.precision === 'highp' ) {
  46541. precisionstring += '\n#define HIGH_PRECISION';
  46542. } else if ( parameters.precision === 'mediump' ) {
  46543. precisionstring += '\n#define MEDIUM_PRECISION';
  46544. } else if ( parameters.precision === 'lowp' ) {
  46545. precisionstring += '\n#define LOW_PRECISION';
  46546. }
  46547. return precisionstring;
  46548. }
  46549. function generateShadowMapTypeDefine( parameters ) {
  46550. let shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  46551. if ( parameters.shadowMapType === PCFShadowMap ) {
  46552. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  46553. } else if ( parameters.shadowMapType === VSMShadowMap ) {
  46554. shadowMapTypeDefine = 'SHADOWMAP_TYPE_VSM';
  46555. }
  46556. return shadowMapTypeDefine;
  46557. }
  46558. function generateEnvMapTypeDefine( parameters ) {
  46559. let envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46560. if ( parameters.envMap ) {
  46561. switch ( parameters.envMapMode ) {
  46562. case CubeReflectionMapping:
  46563. case CubeRefractionMapping:
  46564. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  46565. break;
  46566. case CubeUVReflectionMapping:
  46567. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  46568. break;
  46569. }
  46570. }
  46571. return envMapTypeDefine;
  46572. }
  46573. function generateEnvMapModeDefine( parameters ) {
  46574. let envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  46575. if ( parameters.envMap ) {
  46576. switch ( parameters.envMapMode ) {
  46577. case CubeRefractionMapping:
  46578. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  46579. break;
  46580. }
  46581. }
  46582. return envMapModeDefine;
  46583. }
  46584. function generateEnvMapBlendingDefine( parameters ) {
  46585. let envMapBlendingDefine = 'ENVMAP_BLENDING_NONE';
  46586. if ( parameters.envMap ) {
  46587. switch ( parameters.combine ) {
  46588. case MultiplyOperation:
  46589. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  46590. break;
  46591. case MixOperation:
  46592. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  46593. break;
  46594. case AddOperation:
  46595. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  46596. break;
  46597. }
  46598. }
  46599. return envMapBlendingDefine;
  46600. }
  46601. function generateCubeUVSize( parameters ) {
  46602. const imageHeight = parameters.envMapCubeUVHeight;
  46603. if ( imageHeight === null ) return null;
  46604. const maxMip = Math.log2( imageHeight ) - 2;
  46605. const texelHeight = 1.0 / imageHeight;
  46606. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  46607. return { texelWidth, texelHeight, maxMip };
  46608. }
  46609. function WebGLProgram( renderer, cacheKey, parameters, bindingStates ) {
  46610. // TODO Send this event to Three.js DevTools
  46611. // log( 'WebGLProgram', cacheKey );
  46612. const gl = renderer.getContext();
  46613. const defines = parameters.defines;
  46614. let vertexShader = parameters.vertexShader;
  46615. let fragmentShader = parameters.fragmentShader;
  46616. const shadowMapTypeDefine = generateShadowMapTypeDefine( parameters );
  46617. const envMapTypeDefine = generateEnvMapTypeDefine( parameters );
  46618. const envMapModeDefine = generateEnvMapModeDefine( parameters );
  46619. const envMapBlendingDefine = generateEnvMapBlendingDefine( parameters );
  46620. const envMapCubeUVSize = generateCubeUVSize( parameters );
  46621. const customVertexExtensions = generateVertexExtensions( parameters );
  46622. const customDefines = generateDefines( defines );
  46623. const program = gl.createProgram();
  46624. let prefixVertex, prefixFragment;
  46625. let versionString = parameters.glslVersion ? '#version ' + parameters.glslVersion + '\n' : '';
  46626. if ( parameters.isRawShaderMaterial ) {
  46627. prefixVertex = [
  46628. '#define SHADER_TYPE ' + parameters.shaderType,
  46629. '#define SHADER_NAME ' + parameters.shaderName,
  46630. customDefines
  46631. ].filter( filterEmptyLine ).join( '\n' );
  46632. if ( prefixVertex.length > 0 ) {
  46633. prefixVertex += '\n';
  46634. }
  46635. prefixFragment = [
  46636. '#define SHADER_TYPE ' + parameters.shaderType,
  46637. '#define SHADER_NAME ' + parameters.shaderName,
  46638. customDefines
  46639. ].filter( filterEmptyLine ).join( '\n' );
  46640. if ( prefixFragment.length > 0 ) {
  46641. prefixFragment += '\n';
  46642. }
  46643. } else {
  46644. prefixVertex = [
  46645. generatePrecision( parameters ),
  46646. '#define SHADER_TYPE ' + parameters.shaderType,
  46647. '#define SHADER_NAME ' + parameters.shaderName,
  46648. customDefines,
  46649. parameters.extensionClipCullDistance ? '#define USE_CLIP_DISTANCE' : '',
  46650. parameters.batching ? '#define USE_BATCHING' : '',
  46651. parameters.batchingColor ? '#define USE_BATCHING_COLOR' : '',
  46652. parameters.instancing ? '#define USE_INSTANCING' : '',
  46653. parameters.instancingColor ? '#define USE_INSTANCING_COLOR' : '',
  46654. parameters.instancingMorph ? '#define USE_INSTANCING_MORPH' : '',
  46655. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46656. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46657. parameters.map ? '#define USE_MAP' : '',
  46658. parameters.envMap ? '#define USE_ENVMAP' : '',
  46659. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46660. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46661. parameters.aoMap ? '#define USE_AOMAP' : '',
  46662. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46663. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46664. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46665. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46666. parameters.displacementMap ? '#define USE_DISPLACEMENTMAP' : '',
  46667. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46668. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46669. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46670. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46671. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46672. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46673. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46674. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46675. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46676. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46677. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46678. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46679. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46680. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46681. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46682. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46683. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46684. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46685. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46686. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46687. //
  46688. parameters.mapUv ? '#define MAP_UV ' + parameters.mapUv : '',
  46689. parameters.alphaMapUv ? '#define ALPHAMAP_UV ' + parameters.alphaMapUv : '',
  46690. parameters.lightMapUv ? '#define LIGHTMAP_UV ' + parameters.lightMapUv : '',
  46691. parameters.aoMapUv ? '#define AOMAP_UV ' + parameters.aoMapUv : '',
  46692. parameters.emissiveMapUv ? '#define EMISSIVEMAP_UV ' + parameters.emissiveMapUv : '',
  46693. parameters.bumpMapUv ? '#define BUMPMAP_UV ' + parameters.bumpMapUv : '',
  46694. parameters.normalMapUv ? '#define NORMALMAP_UV ' + parameters.normalMapUv : '',
  46695. parameters.displacementMapUv ? '#define DISPLACEMENTMAP_UV ' + parameters.displacementMapUv : '',
  46696. parameters.metalnessMapUv ? '#define METALNESSMAP_UV ' + parameters.metalnessMapUv : '',
  46697. parameters.roughnessMapUv ? '#define ROUGHNESSMAP_UV ' + parameters.roughnessMapUv : '',
  46698. parameters.anisotropyMapUv ? '#define ANISOTROPYMAP_UV ' + parameters.anisotropyMapUv : '',
  46699. parameters.clearcoatMapUv ? '#define CLEARCOATMAP_UV ' + parameters.clearcoatMapUv : '',
  46700. parameters.clearcoatNormalMapUv ? '#define CLEARCOAT_NORMALMAP_UV ' + parameters.clearcoatNormalMapUv : '',
  46701. parameters.clearcoatRoughnessMapUv ? '#define CLEARCOAT_ROUGHNESSMAP_UV ' + parameters.clearcoatRoughnessMapUv : '',
  46702. parameters.iridescenceMapUv ? '#define IRIDESCENCEMAP_UV ' + parameters.iridescenceMapUv : '',
  46703. parameters.iridescenceThicknessMapUv ? '#define IRIDESCENCE_THICKNESSMAP_UV ' + parameters.iridescenceThicknessMapUv : '',
  46704. parameters.sheenColorMapUv ? '#define SHEEN_COLORMAP_UV ' + parameters.sheenColorMapUv : '',
  46705. parameters.sheenRoughnessMapUv ? '#define SHEEN_ROUGHNESSMAP_UV ' + parameters.sheenRoughnessMapUv : '',
  46706. parameters.specularMapUv ? '#define SPECULARMAP_UV ' + parameters.specularMapUv : '',
  46707. parameters.specularColorMapUv ? '#define SPECULAR_COLORMAP_UV ' + parameters.specularColorMapUv : '',
  46708. parameters.specularIntensityMapUv ? '#define SPECULAR_INTENSITYMAP_UV ' + parameters.specularIntensityMapUv : '',
  46709. parameters.transmissionMapUv ? '#define TRANSMISSIONMAP_UV ' + parameters.transmissionMapUv : '',
  46710. parameters.thicknessMapUv ? '#define THICKNESSMAP_UV ' + parameters.thicknessMapUv : '',
  46711. //
  46712. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46713. parameters.vertexColors ? '#define USE_COLOR' : '',
  46714. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46715. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46716. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46717. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46718. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46719. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46720. parameters.skinning ? '#define USE_SKINNING' : '',
  46721. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  46722. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  46723. ( parameters.morphColors ) ? '#define USE_MORPHCOLORS' : '',
  46724. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_TEXTURE_STRIDE ' + parameters.morphTextureStride : '',
  46725. ( parameters.morphTargetsCount > 0 ) ? '#define MORPHTARGETS_COUNT ' + parameters.morphTargetsCount : '',
  46726. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46727. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46728. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46729. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46730. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  46731. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46732. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46733. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46734. 'uniform mat4 modelMatrix;',
  46735. 'uniform mat4 modelViewMatrix;',
  46736. 'uniform mat4 projectionMatrix;',
  46737. 'uniform mat4 viewMatrix;',
  46738. 'uniform mat3 normalMatrix;',
  46739. 'uniform vec3 cameraPosition;',
  46740. 'uniform bool isOrthographic;',
  46741. '#ifdef USE_INSTANCING',
  46742. ' attribute mat4 instanceMatrix;',
  46743. '#endif',
  46744. '#ifdef USE_INSTANCING_COLOR',
  46745. ' attribute vec3 instanceColor;',
  46746. '#endif',
  46747. '#ifdef USE_INSTANCING_MORPH',
  46748. ' uniform sampler2D morphTexture;',
  46749. '#endif',
  46750. 'attribute vec3 position;',
  46751. 'attribute vec3 normal;',
  46752. 'attribute vec2 uv;',
  46753. '#ifdef USE_UV1',
  46754. ' attribute vec2 uv1;',
  46755. '#endif',
  46756. '#ifdef USE_UV2',
  46757. ' attribute vec2 uv2;',
  46758. '#endif',
  46759. '#ifdef USE_UV3',
  46760. ' attribute vec2 uv3;',
  46761. '#endif',
  46762. '#ifdef USE_TANGENT',
  46763. ' attribute vec4 tangent;',
  46764. '#endif',
  46765. '#if defined( USE_COLOR_ALPHA )',
  46766. ' attribute vec4 color;',
  46767. '#elif defined( USE_COLOR )',
  46768. ' attribute vec3 color;',
  46769. '#endif',
  46770. '#ifdef USE_SKINNING',
  46771. ' attribute vec4 skinIndex;',
  46772. ' attribute vec4 skinWeight;',
  46773. '#endif',
  46774. '\n'
  46775. ].filter( filterEmptyLine ).join( '\n' );
  46776. prefixFragment = [
  46777. generatePrecision( parameters ),
  46778. '#define SHADER_TYPE ' + parameters.shaderType,
  46779. '#define SHADER_NAME ' + parameters.shaderName,
  46780. customDefines,
  46781. parameters.useFog && parameters.fog ? '#define USE_FOG' : '',
  46782. parameters.useFog && parameters.fogExp2 ? '#define FOG_EXP2' : '',
  46783. parameters.alphaToCoverage ? '#define ALPHA_TO_COVERAGE' : '',
  46784. parameters.map ? '#define USE_MAP' : '',
  46785. parameters.matcap ? '#define USE_MATCAP' : '',
  46786. parameters.envMap ? '#define USE_ENVMAP' : '',
  46787. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  46788. parameters.envMap ? '#define ' + envMapModeDefine : '',
  46789. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  46790. envMapCubeUVSize ? '#define CUBEUV_TEXEL_WIDTH ' + envMapCubeUVSize.texelWidth : '',
  46791. envMapCubeUVSize ? '#define CUBEUV_TEXEL_HEIGHT ' + envMapCubeUVSize.texelHeight : '',
  46792. envMapCubeUVSize ? '#define CUBEUV_MAX_MIP ' + envMapCubeUVSize.maxMip + '.0' : '',
  46793. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  46794. parameters.aoMap ? '#define USE_AOMAP' : '',
  46795. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  46796. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  46797. parameters.normalMapObjectSpace ? '#define USE_NORMALMAP_OBJECTSPACE' : '',
  46798. parameters.normalMapTangentSpace ? '#define USE_NORMALMAP_TANGENTSPACE' : '',
  46799. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  46800. parameters.anisotropy ? '#define USE_ANISOTROPY' : '',
  46801. parameters.anisotropyMap ? '#define USE_ANISOTROPYMAP' : '',
  46802. parameters.clearcoat ? '#define USE_CLEARCOAT' : '',
  46803. parameters.clearcoatMap ? '#define USE_CLEARCOATMAP' : '',
  46804. parameters.clearcoatRoughnessMap ? '#define USE_CLEARCOAT_ROUGHNESSMAP' : '',
  46805. parameters.clearcoatNormalMap ? '#define USE_CLEARCOAT_NORMALMAP' : '',
  46806. parameters.dispersion ? '#define USE_DISPERSION' : '',
  46807. parameters.iridescence ? '#define USE_IRIDESCENCE' : '',
  46808. parameters.iridescenceMap ? '#define USE_IRIDESCENCEMAP' : '',
  46809. parameters.iridescenceThicknessMap ? '#define USE_IRIDESCENCE_THICKNESSMAP' : '',
  46810. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  46811. parameters.specularColorMap ? '#define USE_SPECULAR_COLORMAP' : '',
  46812. parameters.specularIntensityMap ? '#define USE_SPECULAR_INTENSITYMAP' : '',
  46813. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  46814. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  46815. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  46816. parameters.alphaTest ? '#define USE_ALPHATEST' : '',
  46817. parameters.alphaHash ? '#define USE_ALPHAHASH' : '',
  46818. parameters.sheen ? '#define USE_SHEEN' : '',
  46819. parameters.sheenColorMap ? '#define USE_SHEEN_COLORMAP' : '',
  46820. parameters.sheenRoughnessMap ? '#define USE_SHEEN_ROUGHNESSMAP' : '',
  46821. parameters.transmission ? '#define USE_TRANSMISSION' : '',
  46822. parameters.transmissionMap ? '#define USE_TRANSMISSIONMAP' : '',
  46823. parameters.thicknessMap ? '#define USE_THICKNESSMAP' : '',
  46824. parameters.vertexTangents && parameters.flatShading === false ? '#define USE_TANGENT' : '',
  46825. parameters.vertexColors || parameters.instancingColor || parameters.batchingColor ? '#define USE_COLOR' : '',
  46826. parameters.vertexAlphas ? '#define USE_COLOR_ALPHA' : '',
  46827. parameters.vertexUv1s ? '#define USE_UV1' : '',
  46828. parameters.vertexUv2s ? '#define USE_UV2' : '',
  46829. parameters.vertexUv3s ? '#define USE_UV3' : '',
  46830. parameters.pointsUvs ? '#define USE_POINTS_UV' : '',
  46831. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  46832. parameters.flatShading ? '#define FLAT_SHADED' : '',
  46833. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  46834. parameters.flipSided ? '#define FLIP_SIDED' : '',
  46835. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  46836. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  46837. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  46838. parameters.numLightProbes > 0 ? '#define USE_LIGHT_PROBES' : '',
  46839. parameters.decodeVideoTexture ? '#define DECODE_VIDEO_TEXTURE' : '',
  46840. parameters.decodeVideoTextureEmissive ? '#define DECODE_VIDEO_TEXTURE_EMISSIVE' : '',
  46841. parameters.logarithmicDepthBuffer ? '#define USE_LOGARITHMIC_DEPTH_BUFFER' : '',
  46842. parameters.reversedDepthBuffer ? '#define USE_REVERSED_DEPTH_BUFFER' : '',
  46843. 'uniform mat4 viewMatrix;',
  46844. 'uniform vec3 cameraPosition;',
  46845. 'uniform bool isOrthographic;',
  46846. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  46847. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  46848. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  46849. parameters.dithering ? '#define DITHERING' : '',
  46850. parameters.opaque ? '#define OPAQUE' : '',
  46851. ShaderChunk[ 'colorspace_pars_fragment' ], // this code is required here because it is used by the various encoding/decoding function defined below
  46852. getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputColorSpace ),
  46853. getLuminanceFunction(),
  46854. parameters.useDepthPacking ? '#define DEPTH_PACKING ' + parameters.depthPacking : '',
  46855. '\n'
  46856. ].filter( filterEmptyLine ).join( '\n' );
  46857. }
  46858. vertexShader = resolveIncludes( vertexShader );
  46859. vertexShader = replaceLightNums( vertexShader, parameters );
  46860. vertexShader = replaceClippingPlaneNums( vertexShader, parameters );
  46861. fragmentShader = resolveIncludes( fragmentShader );
  46862. fragmentShader = replaceLightNums( fragmentShader, parameters );
  46863. fragmentShader = replaceClippingPlaneNums( fragmentShader, parameters );
  46864. vertexShader = unrollLoops( vertexShader );
  46865. fragmentShader = unrollLoops( fragmentShader );
  46866. if ( parameters.isRawShaderMaterial !== true ) {
  46867. // GLSL 3.0 conversion for built-in materials and ShaderMaterial
  46868. versionString = '#version 300 es\n';
  46869. prefixVertex = [
  46870. customVertexExtensions,
  46871. '#define attribute in',
  46872. '#define varying out',
  46873. '#define texture2D texture'
  46874. ].join( '\n' ) + '\n' + prefixVertex;
  46875. prefixFragment = [
  46876. '#define varying in',
  46877. ( parameters.glslVersion === GLSL3 ) ? '' : 'layout(location = 0) out highp vec4 pc_fragColor;',
  46878. ( parameters.glslVersion === GLSL3 ) ? '' : '#define gl_FragColor pc_fragColor',
  46879. '#define gl_FragDepthEXT gl_FragDepth',
  46880. '#define texture2D texture',
  46881. '#define textureCube texture',
  46882. '#define texture2DProj textureProj',
  46883. '#define texture2DLodEXT textureLod',
  46884. '#define texture2DProjLodEXT textureProjLod',
  46885. '#define textureCubeLodEXT textureLod',
  46886. '#define texture2DGradEXT textureGrad',
  46887. '#define texture2DProjGradEXT textureProjGrad',
  46888. '#define textureCubeGradEXT textureGrad'
  46889. ].join( '\n' ) + '\n' + prefixFragment;
  46890. }
  46891. const vertexGlsl = versionString + prefixVertex + vertexShader;
  46892. const fragmentGlsl = versionString + prefixFragment + fragmentShader;
  46893. // log( '*VERTEX*', vertexGlsl );
  46894. // log( '*FRAGMENT*', fragmentGlsl );
  46895. const glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  46896. const glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  46897. gl.attachShader( program, glVertexShader );
  46898. gl.attachShader( program, glFragmentShader );
  46899. // Force a particular attribute to index 0.
  46900. if ( parameters.index0AttributeName !== undefined ) {
  46901. gl.bindAttribLocation( program, 0, parameters.index0AttributeName );
  46902. } else if ( parameters.morphTargets === true ) {
  46903. // programs with morphTargets displace position out of attribute 0
  46904. gl.bindAttribLocation( program, 0, 'position' );
  46905. }
  46906. gl.linkProgram( program );
  46907. function onFirstUse( self ) {
  46908. // check for link errors
  46909. if ( renderer.debug.checkShaderErrors ) {
  46910. const programInfoLog = gl.getProgramInfoLog( program ) || '';
  46911. const vertexShaderInfoLog = gl.getShaderInfoLog( glVertexShader ) || '';
  46912. const fragmentShaderInfoLog = gl.getShaderInfoLog( glFragmentShader ) || '';
  46913. const programLog = programInfoLog.trim();
  46914. const vertexLog = vertexShaderInfoLog.trim();
  46915. const fragmentLog = fragmentShaderInfoLog.trim();
  46916. let runnable = true;
  46917. let haveDiagnostics = true;
  46918. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  46919. runnable = false;
  46920. if ( typeof renderer.debug.onShaderError === 'function' ) {
  46921. renderer.debug.onShaderError( gl, program, glVertexShader, glFragmentShader );
  46922. } else {
  46923. // default error reporting
  46924. const vertexErrors = getShaderErrors( gl, glVertexShader, 'vertex' );
  46925. const fragmentErrors = getShaderErrors( gl, glFragmentShader, 'fragment' );
  46926. error(
  46927. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46928. 'VALIDATE_STATUS ' + gl.getProgramParameter( program, gl.VALIDATE_STATUS ) + '\n\n' +
  46929. 'Material Name: ' + self.name + '\n' +
  46930. 'Material Type: ' + self.type + '\n\n' +
  46931. 'Program Info Log: ' + programLog + '\n' +
  46932. vertexErrors + '\n' +
  46933. fragmentErrors
  46934. );
  46935. }
  46936. } else if ( programLog !== '' ) {
  46937. warn( 'WebGLProgram: Program Info Log:', programLog );
  46938. } else if ( vertexLog === '' || fragmentLog === '' ) {
  46939. haveDiagnostics = false;
  46940. }
  46941. if ( haveDiagnostics ) {
  46942. self.diagnostics = {
  46943. runnable: runnable,
  46944. programLog: programLog,
  46945. vertexShader: {
  46946. log: vertexLog,
  46947. prefix: prefixVertex
  46948. },
  46949. fragmentShader: {
  46950. log: fragmentLog,
  46951. prefix: prefixFragment
  46952. }
  46953. };
  46954. }
  46955. }
  46956. // Clean up
  46957. // Crashes in iOS9 and iOS10. #18402
  46958. // gl.detachShader( program, glVertexShader );
  46959. // gl.detachShader( program, glFragmentShader );
  46960. gl.deleteShader( glVertexShader );
  46961. gl.deleteShader( glFragmentShader );
  46962. cachedUniforms = new WebGLUniforms( gl, program );
  46963. cachedAttributes = fetchAttributeLocations( gl, program );
  46964. }
  46965. // set up caching for uniform locations
  46966. let cachedUniforms;
  46967. this.getUniforms = function () {
  46968. if ( cachedUniforms === undefined ) {
  46969. // Populates cachedUniforms and cachedAttributes
  46970. onFirstUse( this );
  46971. }
  46972. return cachedUniforms;
  46973. };
  46974. // set up caching for attribute locations
  46975. let cachedAttributes;
  46976. this.getAttributes = function () {
  46977. if ( cachedAttributes === undefined ) {
  46978. // Populates cachedAttributes and cachedUniforms
  46979. onFirstUse( this );
  46980. }
  46981. return cachedAttributes;
  46982. };
  46983. // indicate when the program is ready to be used. if the KHR_parallel_shader_compile extension isn't supported,
  46984. // flag the program as ready immediately. It may cause a stall when it's first used.
  46985. let programReady = ( parameters.rendererExtensionParallelShaderCompile === false );
  46986. this.isReady = function () {
  46987. if ( programReady === false ) {
  46988. programReady = gl.getProgramParameter( program, COMPLETION_STATUS_KHR );
  46989. }
  46990. return programReady;
  46991. };
  46992. // free resource
  46993. this.destroy = function () {
  46994. bindingStates.releaseStatesOfProgram( this );
  46995. gl.deleteProgram( program );
  46996. this.program = undefined;
  46997. };
  46998. //
  46999. this.type = parameters.shaderType;
  47000. this.name = parameters.shaderName;
  47001. this.id = programIdCount ++;
  47002. this.cacheKey = cacheKey;
  47003. this.usedTimes = 1;
  47004. this.program = program;
  47005. this.vertexShader = glVertexShader;
  47006. this.fragmentShader = glFragmentShader;
  47007. return this;
  47008. }
  47009. let _id = 0;
  47010. class WebGLShaderCache {
  47011. constructor() {
  47012. this.shaderCache = new Map();
  47013. this.materialCache = new Map();
  47014. }
  47015. update( material ) {
  47016. const vertexShader = material.vertexShader;
  47017. const fragmentShader = material.fragmentShader;
  47018. const vertexShaderStage = this._getShaderStage( vertexShader );
  47019. const fragmentShaderStage = this._getShaderStage( fragmentShader );
  47020. const materialShaders = this._getShaderCacheForMaterial( material );
  47021. if ( materialShaders.has( vertexShaderStage ) === false ) {
  47022. materialShaders.add( vertexShaderStage );
  47023. vertexShaderStage.usedTimes ++;
  47024. }
  47025. if ( materialShaders.has( fragmentShaderStage ) === false ) {
  47026. materialShaders.add( fragmentShaderStage );
  47027. fragmentShaderStage.usedTimes ++;
  47028. }
  47029. return this;
  47030. }
  47031. remove( material ) {
  47032. const materialShaders = this.materialCache.get( material );
  47033. for ( const shaderStage of materialShaders ) {
  47034. shaderStage.usedTimes --;
  47035. if ( shaderStage.usedTimes === 0 ) this.shaderCache.delete( shaderStage.code );
  47036. }
  47037. this.materialCache.delete( material );
  47038. return this;
  47039. }
  47040. getVertexShaderID( material ) {
  47041. return this._getShaderStage( material.vertexShader ).id;
  47042. }
  47043. getFragmentShaderID( material ) {
  47044. return this._getShaderStage( material.fragmentShader ).id;
  47045. }
  47046. dispose() {
  47047. this.shaderCache.clear();
  47048. this.materialCache.clear();
  47049. }
  47050. _getShaderCacheForMaterial( material ) {
  47051. const cache = this.materialCache;
  47052. let set = cache.get( material );
  47053. if ( set === undefined ) {
  47054. set = new Set();
  47055. cache.set( material, set );
  47056. }
  47057. return set;
  47058. }
  47059. _getShaderStage( code ) {
  47060. const cache = this.shaderCache;
  47061. let stage = cache.get( code );
  47062. if ( stage === undefined ) {
  47063. stage = new WebGLShaderStage( code );
  47064. cache.set( code, stage );
  47065. }
  47066. return stage;
  47067. }
  47068. }
  47069. class WebGLShaderStage {
  47070. constructor( code ) {
  47071. this.id = _id ++;
  47072. this.code = code;
  47073. this.usedTimes = 0;
  47074. }
  47075. }
  47076. function WebGLPrograms( renderer, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping ) {
  47077. const _programLayers = new Layers();
  47078. const _customShaders = new WebGLShaderCache();
  47079. const _activeChannels = new Set();
  47080. const programs = [];
  47081. const logarithmicDepthBuffer = capabilities.logarithmicDepthBuffer;
  47082. const SUPPORTS_VERTEX_TEXTURES = capabilities.vertexTextures;
  47083. let precision = capabilities.precision;
  47084. const shaderIDs = {
  47085. MeshDepthMaterial: 'depth',
  47086. MeshDistanceMaterial: 'distance',
  47087. MeshNormalMaterial: 'normal',
  47088. MeshBasicMaterial: 'basic',
  47089. MeshLambertMaterial: 'lambert',
  47090. MeshPhongMaterial: 'phong',
  47091. MeshToonMaterial: 'toon',
  47092. MeshStandardMaterial: 'physical',
  47093. MeshPhysicalMaterial: 'physical',
  47094. MeshMatcapMaterial: 'matcap',
  47095. LineBasicMaterial: 'basic',
  47096. LineDashedMaterial: 'dashed',
  47097. PointsMaterial: 'points',
  47098. ShadowMaterial: 'shadow',
  47099. SpriteMaterial: 'sprite'
  47100. };
  47101. function getChannel( value ) {
  47102. _activeChannels.add( value );
  47103. if ( value === 0 ) return 'uv';
  47104. return `uv${ value }`;
  47105. }
  47106. function getParameters( material, lights, shadows, scene, object ) {
  47107. const fog = scene.fog;
  47108. const geometry = object.geometry;
  47109. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  47110. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  47111. const envMapCubeUVHeight = ( !! envMap ) && ( envMap.mapping === CubeUVReflectionMapping ) ? envMap.image.height : null;
  47112. const shaderID = shaderIDs[ material.type ];
  47113. // heuristics to create shader parameters according to lights in the scene
  47114. // (not to blow over maxLights budget)
  47115. if ( material.precision !== null ) {
  47116. precision = capabilities.getMaxPrecision( material.precision );
  47117. if ( precision !== material.precision ) {
  47118. warn( 'WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  47119. }
  47120. }
  47121. //
  47122. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  47123. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  47124. let morphTextureStride = 0;
  47125. if ( geometry.morphAttributes.position !== undefined ) morphTextureStride = 1;
  47126. if ( geometry.morphAttributes.normal !== undefined ) morphTextureStride = 2;
  47127. if ( geometry.morphAttributes.color !== undefined ) morphTextureStride = 3;
  47128. //
  47129. let vertexShader, fragmentShader;
  47130. let customVertexShaderID, customFragmentShaderID;
  47131. if ( shaderID ) {
  47132. const shader = ShaderLib[ shaderID ];
  47133. vertexShader = shader.vertexShader;
  47134. fragmentShader = shader.fragmentShader;
  47135. } else {
  47136. vertexShader = material.vertexShader;
  47137. fragmentShader = material.fragmentShader;
  47138. _customShaders.update( material );
  47139. customVertexShaderID = _customShaders.getVertexShaderID( material );
  47140. customFragmentShaderID = _customShaders.getFragmentShaderID( material );
  47141. }
  47142. const currentRenderTarget = renderer.getRenderTarget();
  47143. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  47144. const IS_INSTANCEDMESH = object.isInstancedMesh === true;
  47145. const IS_BATCHEDMESH = object.isBatchedMesh === true;
  47146. const HAS_MAP = !! material.map;
  47147. const HAS_MATCAP = !! material.matcap;
  47148. const HAS_ENVMAP = !! envMap;
  47149. const HAS_AOMAP = !! material.aoMap;
  47150. const HAS_LIGHTMAP = !! material.lightMap;
  47151. const HAS_BUMPMAP = !! material.bumpMap;
  47152. const HAS_NORMALMAP = !! material.normalMap;
  47153. const HAS_DISPLACEMENTMAP = !! material.displacementMap;
  47154. const HAS_EMISSIVEMAP = !! material.emissiveMap;
  47155. const HAS_METALNESSMAP = !! material.metalnessMap;
  47156. const HAS_ROUGHNESSMAP = !! material.roughnessMap;
  47157. const HAS_ANISOTROPY = material.anisotropy > 0;
  47158. const HAS_CLEARCOAT = material.clearcoat > 0;
  47159. const HAS_DISPERSION = material.dispersion > 0;
  47160. const HAS_IRIDESCENCE = material.iridescence > 0;
  47161. const HAS_SHEEN = material.sheen > 0;
  47162. const HAS_TRANSMISSION = material.transmission > 0;
  47163. const HAS_ANISOTROPYMAP = HAS_ANISOTROPY && !! material.anisotropyMap;
  47164. const HAS_CLEARCOATMAP = HAS_CLEARCOAT && !! material.clearcoatMap;
  47165. const HAS_CLEARCOAT_NORMALMAP = HAS_CLEARCOAT && !! material.clearcoatNormalMap;
  47166. const HAS_CLEARCOAT_ROUGHNESSMAP = HAS_CLEARCOAT && !! material.clearcoatRoughnessMap;
  47167. const HAS_IRIDESCENCEMAP = HAS_IRIDESCENCE && !! material.iridescenceMap;
  47168. const HAS_IRIDESCENCE_THICKNESSMAP = HAS_IRIDESCENCE && !! material.iridescenceThicknessMap;
  47169. const HAS_SHEEN_COLORMAP = HAS_SHEEN && !! material.sheenColorMap;
  47170. const HAS_SHEEN_ROUGHNESSMAP = HAS_SHEEN && !! material.sheenRoughnessMap;
  47171. const HAS_SPECULARMAP = !! material.specularMap;
  47172. const HAS_SPECULAR_COLORMAP = !! material.specularColorMap;
  47173. const HAS_SPECULAR_INTENSITYMAP = !! material.specularIntensityMap;
  47174. const HAS_TRANSMISSIONMAP = HAS_TRANSMISSION && !! material.transmissionMap;
  47175. const HAS_THICKNESSMAP = HAS_TRANSMISSION && !! material.thicknessMap;
  47176. const HAS_GRADIENTMAP = !! material.gradientMap;
  47177. const HAS_ALPHAMAP = !! material.alphaMap;
  47178. const HAS_ALPHATEST = material.alphaTest > 0;
  47179. const HAS_ALPHAHASH = !! material.alphaHash;
  47180. const HAS_EXTENSIONS = !! material.extensions;
  47181. let toneMapping = NoToneMapping;
  47182. if ( material.toneMapped ) {
  47183. if ( currentRenderTarget === null || currentRenderTarget.isXRRenderTarget === true ) {
  47184. toneMapping = renderer.toneMapping;
  47185. }
  47186. }
  47187. const parameters = {
  47188. shaderID: shaderID,
  47189. shaderType: material.type,
  47190. shaderName: material.name,
  47191. vertexShader: vertexShader,
  47192. fragmentShader: fragmentShader,
  47193. defines: material.defines,
  47194. customVertexShaderID: customVertexShaderID,
  47195. customFragmentShaderID: customFragmentShaderID,
  47196. isRawShaderMaterial: material.isRawShaderMaterial === true,
  47197. glslVersion: material.glslVersion,
  47198. precision: precision,
  47199. batching: IS_BATCHEDMESH,
  47200. batchingColor: IS_BATCHEDMESH && object._colorsTexture !== null,
  47201. instancing: IS_INSTANCEDMESH,
  47202. instancingColor: IS_INSTANCEDMESH && object.instanceColor !== null,
  47203. instancingMorph: IS_INSTANCEDMESH && object.morphTexture !== null,
  47204. supportsVertexTextures: SUPPORTS_VERTEX_TEXTURES,
  47205. outputColorSpace: ( currentRenderTarget === null ) ? renderer.outputColorSpace : ( currentRenderTarget.isXRRenderTarget === true ? currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace ),
  47206. alphaToCoverage: !! material.alphaToCoverage,
  47207. map: HAS_MAP,
  47208. matcap: HAS_MATCAP,
  47209. envMap: HAS_ENVMAP,
  47210. envMapMode: HAS_ENVMAP && envMap.mapping,
  47211. envMapCubeUVHeight: envMapCubeUVHeight,
  47212. aoMap: HAS_AOMAP,
  47213. lightMap: HAS_LIGHTMAP,
  47214. bumpMap: HAS_BUMPMAP,
  47215. normalMap: HAS_NORMALMAP,
  47216. displacementMap: SUPPORTS_VERTEX_TEXTURES && HAS_DISPLACEMENTMAP,
  47217. emissiveMap: HAS_EMISSIVEMAP,
  47218. normalMapObjectSpace: HAS_NORMALMAP && material.normalMapType === ObjectSpaceNormalMap,
  47219. normalMapTangentSpace: HAS_NORMALMAP && material.normalMapType === TangentSpaceNormalMap,
  47220. metalnessMap: HAS_METALNESSMAP,
  47221. roughnessMap: HAS_ROUGHNESSMAP,
  47222. anisotropy: HAS_ANISOTROPY,
  47223. anisotropyMap: HAS_ANISOTROPYMAP,
  47224. clearcoat: HAS_CLEARCOAT,
  47225. clearcoatMap: HAS_CLEARCOATMAP,
  47226. clearcoatNormalMap: HAS_CLEARCOAT_NORMALMAP,
  47227. clearcoatRoughnessMap: HAS_CLEARCOAT_ROUGHNESSMAP,
  47228. dispersion: HAS_DISPERSION,
  47229. iridescence: HAS_IRIDESCENCE,
  47230. iridescenceMap: HAS_IRIDESCENCEMAP,
  47231. iridescenceThicknessMap: HAS_IRIDESCENCE_THICKNESSMAP,
  47232. sheen: HAS_SHEEN,
  47233. sheenColorMap: HAS_SHEEN_COLORMAP,
  47234. sheenRoughnessMap: HAS_SHEEN_ROUGHNESSMAP,
  47235. specularMap: HAS_SPECULARMAP,
  47236. specularColorMap: HAS_SPECULAR_COLORMAP,
  47237. specularIntensityMap: HAS_SPECULAR_INTENSITYMAP,
  47238. transmission: HAS_TRANSMISSION,
  47239. transmissionMap: HAS_TRANSMISSIONMAP,
  47240. thicknessMap: HAS_THICKNESSMAP,
  47241. gradientMap: HAS_GRADIENTMAP,
  47242. opaque: material.transparent === false && material.blending === NormalBlending && material.alphaToCoverage === false,
  47243. alphaMap: HAS_ALPHAMAP,
  47244. alphaTest: HAS_ALPHATEST,
  47245. alphaHash: HAS_ALPHAHASH,
  47246. combine: material.combine,
  47247. //
  47248. mapUv: HAS_MAP && getChannel( material.map.channel ),
  47249. aoMapUv: HAS_AOMAP && getChannel( material.aoMap.channel ),
  47250. lightMapUv: HAS_LIGHTMAP && getChannel( material.lightMap.channel ),
  47251. bumpMapUv: HAS_BUMPMAP && getChannel( material.bumpMap.channel ),
  47252. normalMapUv: HAS_NORMALMAP && getChannel( material.normalMap.channel ),
  47253. displacementMapUv: HAS_DISPLACEMENTMAP && getChannel( material.displacementMap.channel ),
  47254. emissiveMapUv: HAS_EMISSIVEMAP && getChannel( material.emissiveMap.channel ),
  47255. metalnessMapUv: HAS_METALNESSMAP && getChannel( material.metalnessMap.channel ),
  47256. roughnessMapUv: HAS_ROUGHNESSMAP && getChannel( material.roughnessMap.channel ),
  47257. anisotropyMapUv: HAS_ANISOTROPYMAP && getChannel( material.anisotropyMap.channel ),
  47258. clearcoatMapUv: HAS_CLEARCOATMAP && getChannel( material.clearcoatMap.channel ),
  47259. clearcoatNormalMapUv: HAS_CLEARCOAT_NORMALMAP && getChannel( material.clearcoatNormalMap.channel ),
  47260. clearcoatRoughnessMapUv: HAS_CLEARCOAT_ROUGHNESSMAP && getChannel( material.clearcoatRoughnessMap.channel ),
  47261. iridescenceMapUv: HAS_IRIDESCENCEMAP && getChannel( material.iridescenceMap.channel ),
  47262. iridescenceThicknessMapUv: HAS_IRIDESCENCE_THICKNESSMAP && getChannel( material.iridescenceThicknessMap.channel ),
  47263. sheenColorMapUv: HAS_SHEEN_COLORMAP && getChannel( material.sheenColorMap.channel ),
  47264. sheenRoughnessMapUv: HAS_SHEEN_ROUGHNESSMAP && getChannel( material.sheenRoughnessMap.channel ),
  47265. specularMapUv: HAS_SPECULARMAP && getChannel( material.specularMap.channel ),
  47266. specularColorMapUv: HAS_SPECULAR_COLORMAP && getChannel( material.specularColorMap.channel ),
  47267. specularIntensityMapUv: HAS_SPECULAR_INTENSITYMAP && getChannel( material.specularIntensityMap.channel ),
  47268. transmissionMapUv: HAS_TRANSMISSIONMAP && getChannel( material.transmissionMap.channel ),
  47269. thicknessMapUv: HAS_THICKNESSMAP && getChannel( material.thicknessMap.channel ),
  47270. alphaMapUv: HAS_ALPHAMAP && getChannel( material.alphaMap.channel ),
  47271. //
  47272. vertexTangents: !! geometry.attributes.tangent && ( HAS_NORMALMAP || HAS_ANISOTROPY ),
  47273. vertexColors: material.vertexColors,
  47274. vertexAlphas: material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4,
  47275. pointsUvs: object.isPoints === true && !! geometry.attributes.uv && ( HAS_MAP || HAS_ALPHAMAP ),
  47276. fog: !! fog,
  47277. useFog: material.fog === true,
  47278. fogExp2: ( !! fog && fog.isFogExp2 ),
  47279. flatShading: ( material.flatShading === true && material.wireframe === false ),
  47280. sizeAttenuation: material.sizeAttenuation === true,
  47281. logarithmicDepthBuffer: logarithmicDepthBuffer,
  47282. reversedDepthBuffer: reversedDepthBuffer,
  47283. skinning: object.isSkinnedMesh === true,
  47284. morphTargets: geometry.morphAttributes.position !== undefined,
  47285. morphNormals: geometry.morphAttributes.normal !== undefined,
  47286. morphColors: geometry.morphAttributes.color !== undefined,
  47287. morphTargetsCount: morphTargetsCount,
  47288. morphTextureStride: morphTextureStride,
  47289. numDirLights: lights.directional.length,
  47290. numPointLights: lights.point.length,
  47291. numSpotLights: lights.spot.length,
  47292. numSpotLightMaps: lights.spotLightMap.length,
  47293. numRectAreaLights: lights.rectArea.length,
  47294. numHemiLights: lights.hemi.length,
  47295. numDirLightShadows: lights.directionalShadowMap.length,
  47296. numPointLightShadows: lights.pointShadowMap.length,
  47297. numSpotLightShadows: lights.spotShadowMap.length,
  47298. numSpotLightShadowsWithMaps: lights.numSpotLightShadowsWithMaps,
  47299. numLightProbes: lights.numLightProbes,
  47300. numClippingPlanes: clipping.numPlanes,
  47301. numClipIntersection: clipping.numIntersection,
  47302. dithering: material.dithering,
  47303. shadowMapEnabled: renderer.shadowMap.enabled && shadows.length > 0,
  47304. shadowMapType: renderer.shadowMap.type,
  47305. toneMapping: toneMapping,
  47306. decodeVideoTexture: HAS_MAP && ( material.map.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.map.colorSpace ) === SRGBTransfer ),
  47307. decodeVideoTextureEmissive: HAS_EMISSIVEMAP && ( material.emissiveMap.isVideoTexture === true ) && ( ColorManagement.getTransfer( material.emissiveMap.colorSpace ) === SRGBTransfer ),
  47308. premultipliedAlpha: material.premultipliedAlpha,
  47309. doubleSided: material.side === DoubleSide,
  47310. flipSided: material.side === BackSide,
  47311. useDepthPacking: material.depthPacking >= 0,
  47312. depthPacking: material.depthPacking || 0,
  47313. index0AttributeName: material.index0AttributeName,
  47314. extensionClipCullDistance: HAS_EXTENSIONS && material.extensions.clipCullDistance === true && extensions.has( 'WEBGL_clip_cull_distance' ),
  47315. extensionMultiDraw: ( HAS_EXTENSIONS && material.extensions.multiDraw === true || IS_BATCHEDMESH ) && extensions.has( 'WEBGL_multi_draw' ),
  47316. rendererExtensionParallelShaderCompile: extensions.has( 'KHR_parallel_shader_compile' ),
  47317. customProgramCacheKey: material.customProgramCacheKey()
  47318. };
  47319. // the usage of getChannel() determines the active texture channels for this shader
  47320. parameters.vertexUv1s = _activeChannels.has( 1 );
  47321. parameters.vertexUv2s = _activeChannels.has( 2 );
  47322. parameters.vertexUv3s = _activeChannels.has( 3 );
  47323. _activeChannels.clear();
  47324. return parameters;
  47325. }
  47326. function getProgramCacheKey( parameters ) {
  47327. const array = [];
  47328. if ( parameters.shaderID ) {
  47329. array.push( parameters.shaderID );
  47330. } else {
  47331. array.push( parameters.customVertexShaderID );
  47332. array.push( parameters.customFragmentShaderID );
  47333. }
  47334. if ( parameters.defines !== undefined ) {
  47335. for ( const name in parameters.defines ) {
  47336. array.push( name );
  47337. array.push( parameters.defines[ name ] );
  47338. }
  47339. }
  47340. if ( parameters.isRawShaderMaterial === false ) {
  47341. getProgramCacheKeyParameters( array, parameters );
  47342. getProgramCacheKeyBooleans( array, parameters );
  47343. array.push( renderer.outputColorSpace );
  47344. }
  47345. array.push( parameters.customProgramCacheKey );
  47346. return array.join();
  47347. }
  47348. function getProgramCacheKeyParameters( array, parameters ) {
  47349. array.push( parameters.precision );
  47350. array.push( parameters.outputColorSpace );
  47351. array.push( parameters.envMapMode );
  47352. array.push( parameters.envMapCubeUVHeight );
  47353. array.push( parameters.mapUv );
  47354. array.push( parameters.alphaMapUv );
  47355. array.push( parameters.lightMapUv );
  47356. array.push( parameters.aoMapUv );
  47357. array.push( parameters.bumpMapUv );
  47358. array.push( parameters.normalMapUv );
  47359. array.push( parameters.displacementMapUv );
  47360. array.push( parameters.emissiveMapUv );
  47361. array.push( parameters.metalnessMapUv );
  47362. array.push( parameters.roughnessMapUv );
  47363. array.push( parameters.anisotropyMapUv );
  47364. array.push( parameters.clearcoatMapUv );
  47365. array.push( parameters.clearcoatNormalMapUv );
  47366. array.push( parameters.clearcoatRoughnessMapUv );
  47367. array.push( parameters.iridescenceMapUv );
  47368. array.push( parameters.iridescenceThicknessMapUv );
  47369. array.push( parameters.sheenColorMapUv );
  47370. array.push( parameters.sheenRoughnessMapUv );
  47371. array.push( parameters.specularMapUv );
  47372. array.push( parameters.specularColorMapUv );
  47373. array.push( parameters.specularIntensityMapUv );
  47374. array.push( parameters.transmissionMapUv );
  47375. array.push( parameters.thicknessMapUv );
  47376. array.push( parameters.combine );
  47377. array.push( parameters.fogExp2 );
  47378. array.push( parameters.sizeAttenuation );
  47379. array.push( parameters.morphTargetsCount );
  47380. array.push( parameters.morphAttributeCount );
  47381. array.push( parameters.numDirLights );
  47382. array.push( parameters.numPointLights );
  47383. array.push( parameters.numSpotLights );
  47384. array.push( parameters.numSpotLightMaps );
  47385. array.push( parameters.numHemiLights );
  47386. array.push( parameters.numRectAreaLights );
  47387. array.push( parameters.numDirLightShadows );
  47388. array.push( parameters.numPointLightShadows );
  47389. array.push( parameters.numSpotLightShadows );
  47390. array.push( parameters.numSpotLightShadowsWithMaps );
  47391. array.push( parameters.numLightProbes );
  47392. array.push( parameters.shadowMapType );
  47393. array.push( parameters.toneMapping );
  47394. array.push( parameters.numClippingPlanes );
  47395. array.push( parameters.numClipIntersection );
  47396. array.push( parameters.depthPacking );
  47397. }
  47398. function getProgramCacheKeyBooleans( array, parameters ) {
  47399. _programLayers.disableAll();
  47400. if ( parameters.supportsVertexTextures )
  47401. _programLayers.enable( 0 );
  47402. if ( parameters.instancing )
  47403. _programLayers.enable( 1 );
  47404. if ( parameters.instancingColor )
  47405. _programLayers.enable( 2 );
  47406. if ( parameters.instancingMorph )
  47407. _programLayers.enable( 3 );
  47408. if ( parameters.matcap )
  47409. _programLayers.enable( 4 );
  47410. if ( parameters.envMap )
  47411. _programLayers.enable( 5 );
  47412. if ( parameters.normalMapObjectSpace )
  47413. _programLayers.enable( 6 );
  47414. if ( parameters.normalMapTangentSpace )
  47415. _programLayers.enable( 7 );
  47416. if ( parameters.clearcoat )
  47417. _programLayers.enable( 8 );
  47418. if ( parameters.iridescence )
  47419. _programLayers.enable( 9 );
  47420. if ( parameters.alphaTest )
  47421. _programLayers.enable( 10 );
  47422. if ( parameters.vertexColors )
  47423. _programLayers.enable( 11 );
  47424. if ( parameters.vertexAlphas )
  47425. _programLayers.enable( 12 );
  47426. if ( parameters.vertexUv1s )
  47427. _programLayers.enable( 13 );
  47428. if ( parameters.vertexUv2s )
  47429. _programLayers.enable( 14 );
  47430. if ( parameters.vertexUv3s )
  47431. _programLayers.enable( 15 );
  47432. if ( parameters.vertexTangents )
  47433. _programLayers.enable( 16 );
  47434. if ( parameters.anisotropy )
  47435. _programLayers.enable( 17 );
  47436. if ( parameters.alphaHash )
  47437. _programLayers.enable( 18 );
  47438. if ( parameters.batching )
  47439. _programLayers.enable( 19 );
  47440. if ( parameters.dispersion )
  47441. _programLayers.enable( 20 );
  47442. if ( parameters.batchingColor )
  47443. _programLayers.enable( 21 );
  47444. if ( parameters.gradientMap )
  47445. _programLayers.enable( 22 );
  47446. array.push( _programLayers.mask );
  47447. _programLayers.disableAll();
  47448. if ( parameters.fog )
  47449. _programLayers.enable( 0 );
  47450. if ( parameters.useFog )
  47451. _programLayers.enable( 1 );
  47452. if ( parameters.flatShading )
  47453. _programLayers.enable( 2 );
  47454. if ( parameters.logarithmicDepthBuffer )
  47455. _programLayers.enable( 3 );
  47456. if ( parameters.reversedDepthBuffer )
  47457. _programLayers.enable( 4 );
  47458. if ( parameters.skinning )
  47459. _programLayers.enable( 5 );
  47460. if ( parameters.morphTargets )
  47461. _programLayers.enable( 6 );
  47462. if ( parameters.morphNormals )
  47463. _programLayers.enable( 7 );
  47464. if ( parameters.morphColors )
  47465. _programLayers.enable( 8 );
  47466. if ( parameters.premultipliedAlpha )
  47467. _programLayers.enable( 9 );
  47468. if ( parameters.shadowMapEnabled )
  47469. _programLayers.enable( 10 );
  47470. if ( parameters.doubleSided )
  47471. _programLayers.enable( 11 );
  47472. if ( parameters.flipSided )
  47473. _programLayers.enable( 12 );
  47474. if ( parameters.useDepthPacking )
  47475. _programLayers.enable( 13 );
  47476. if ( parameters.dithering )
  47477. _programLayers.enable( 14 );
  47478. if ( parameters.transmission )
  47479. _programLayers.enable( 15 );
  47480. if ( parameters.sheen )
  47481. _programLayers.enable( 16 );
  47482. if ( parameters.opaque )
  47483. _programLayers.enable( 17 );
  47484. if ( parameters.pointsUvs )
  47485. _programLayers.enable( 18 );
  47486. if ( parameters.decodeVideoTexture )
  47487. _programLayers.enable( 19 );
  47488. if ( parameters.decodeVideoTextureEmissive )
  47489. _programLayers.enable( 20 );
  47490. if ( parameters.alphaToCoverage )
  47491. _programLayers.enable( 21 );
  47492. array.push( _programLayers.mask );
  47493. }
  47494. function getUniforms( material ) {
  47495. const shaderID = shaderIDs[ material.type ];
  47496. let uniforms;
  47497. if ( shaderID ) {
  47498. const shader = ShaderLib[ shaderID ];
  47499. uniforms = UniformsUtils.clone( shader.uniforms );
  47500. } else {
  47501. uniforms = material.uniforms;
  47502. }
  47503. return uniforms;
  47504. }
  47505. function acquireProgram( parameters, cacheKey ) {
  47506. let program;
  47507. // Check if code has been already compiled
  47508. for ( let p = 0, pl = programs.length; p < pl; p ++ ) {
  47509. const preexistingProgram = programs[ p ];
  47510. if ( preexistingProgram.cacheKey === cacheKey ) {
  47511. program = preexistingProgram;
  47512. ++ program.usedTimes;
  47513. break;
  47514. }
  47515. }
  47516. if ( program === undefined ) {
  47517. program = new WebGLProgram( renderer, cacheKey, parameters, bindingStates );
  47518. programs.push( program );
  47519. }
  47520. return program;
  47521. }
  47522. function releaseProgram( program ) {
  47523. if ( -- program.usedTimes === 0 ) {
  47524. // Remove from unordered set
  47525. const i = programs.indexOf( program );
  47526. programs[ i ] = programs[ programs.length - 1 ];
  47527. programs.pop();
  47528. // Free WebGL resources
  47529. program.destroy();
  47530. }
  47531. }
  47532. function releaseShaderCache( material ) {
  47533. _customShaders.remove( material );
  47534. }
  47535. function dispose() {
  47536. _customShaders.dispose();
  47537. }
  47538. return {
  47539. getParameters: getParameters,
  47540. getProgramCacheKey: getProgramCacheKey,
  47541. getUniforms: getUniforms,
  47542. acquireProgram: acquireProgram,
  47543. releaseProgram: releaseProgram,
  47544. releaseShaderCache: releaseShaderCache,
  47545. // Exposed for resource monitoring & error feedback via renderer.info:
  47546. programs: programs,
  47547. dispose: dispose
  47548. };
  47549. }
  47550. function WebGLProperties() {
  47551. let properties = new WeakMap();
  47552. function has( object ) {
  47553. return properties.has( object );
  47554. }
  47555. function get( object ) {
  47556. let map = properties.get( object );
  47557. if ( map === undefined ) {
  47558. map = {};
  47559. properties.set( object, map );
  47560. }
  47561. return map;
  47562. }
  47563. function remove( object ) {
  47564. properties.delete( object );
  47565. }
  47566. function update( object, key, value ) {
  47567. properties.get( object )[ key ] = value;
  47568. }
  47569. function dispose() {
  47570. properties = new WeakMap();
  47571. }
  47572. return {
  47573. has: has,
  47574. get: get,
  47575. remove: remove,
  47576. update: update,
  47577. dispose: dispose
  47578. };
  47579. }
  47580. function painterSortStable( a, b ) {
  47581. if ( a.groupOrder !== b.groupOrder ) {
  47582. return a.groupOrder - b.groupOrder;
  47583. } else if ( a.renderOrder !== b.renderOrder ) {
  47584. return a.renderOrder - b.renderOrder;
  47585. } else if ( a.material.id !== b.material.id ) {
  47586. return a.material.id - b.material.id;
  47587. } else if ( a.z !== b.z ) {
  47588. return a.z - b.z;
  47589. } else {
  47590. return a.id - b.id;
  47591. }
  47592. }
  47593. function reversePainterSortStable( a, b ) {
  47594. if ( a.groupOrder !== b.groupOrder ) {
  47595. return a.groupOrder - b.groupOrder;
  47596. } else if ( a.renderOrder !== b.renderOrder ) {
  47597. return a.renderOrder - b.renderOrder;
  47598. } else if ( a.z !== b.z ) {
  47599. return b.z - a.z;
  47600. } else {
  47601. return a.id - b.id;
  47602. }
  47603. }
  47604. function WebGLRenderList() {
  47605. const renderItems = [];
  47606. let renderItemsIndex = 0;
  47607. const opaque = [];
  47608. const transmissive = [];
  47609. const transparent = [];
  47610. function init() {
  47611. renderItemsIndex = 0;
  47612. opaque.length = 0;
  47613. transmissive.length = 0;
  47614. transparent.length = 0;
  47615. }
  47616. function getNextRenderItem( object, geometry, material, groupOrder, z, group ) {
  47617. let renderItem = renderItems[ renderItemsIndex ];
  47618. if ( renderItem === undefined ) {
  47619. renderItem = {
  47620. id: object.id,
  47621. object: object,
  47622. geometry: geometry,
  47623. material: material,
  47624. groupOrder: groupOrder,
  47625. renderOrder: object.renderOrder,
  47626. z: z,
  47627. group: group
  47628. };
  47629. renderItems[ renderItemsIndex ] = renderItem;
  47630. } else {
  47631. renderItem.id = object.id;
  47632. renderItem.object = object;
  47633. renderItem.geometry = geometry;
  47634. renderItem.material = material;
  47635. renderItem.groupOrder = groupOrder;
  47636. renderItem.renderOrder = object.renderOrder;
  47637. renderItem.z = z;
  47638. renderItem.group = group;
  47639. }
  47640. renderItemsIndex ++;
  47641. return renderItem;
  47642. }
  47643. function push( object, geometry, material, groupOrder, z, group ) {
  47644. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47645. if ( material.transmission > 0.0 ) {
  47646. transmissive.push( renderItem );
  47647. } else if ( material.transparent === true ) {
  47648. transparent.push( renderItem );
  47649. } else {
  47650. opaque.push( renderItem );
  47651. }
  47652. }
  47653. function unshift( object, geometry, material, groupOrder, z, group ) {
  47654. const renderItem = getNextRenderItem( object, geometry, material, groupOrder, z, group );
  47655. if ( material.transmission > 0.0 ) {
  47656. transmissive.unshift( renderItem );
  47657. } else if ( material.transparent === true ) {
  47658. transparent.unshift( renderItem );
  47659. } else {
  47660. opaque.unshift( renderItem );
  47661. }
  47662. }
  47663. function sort( customOpaqueSort, customTransparentSort ) {
  47664. if ( opaque.length > 1 ) opaque.sort( customOpaqueSort || painterSortStable );
  47665. if ( transmissive.length > 1 ) transmissive.sort( customTransparentSort || reversePainterSortStable );
  47666. if ( transparent.length > 1 ) transparent.sort( customTransparentSort || reversePainterSortStable );
  47667. }
  47668. function finish() {
  47669. // Clear references from inactive renderItems in the list
  47670. for ( let i = renderItemsIndex, il = renderItems.length; i < il; i ++ ) {
  47671. const renderItem = renderItems[ i ];
  47672. if ( renderItem.id === null ) break;
  47673. renderItem.id = null;
  47674. renderItem.object = null;
  47675. renderItem.geometry = null;
  47676. renderItem.material = null;
  47677. renderItem.group = null;
  47678. }
  47679. }
  47680. return {
  47681. opaque: opaque,
  47682. transmissive: transmissive,
  47683. transparent: transparent,
  47684. init: init,
  47685. push: push,
  47686. unshift: unshift,
  47687. finish: finish,
  47688. sort: sort
  47689. };
  47690. }
  47691. function WebGLRenderLists() {
  47692. let lists = new WeakMap();
  47693. function get( scene, renderCallDepth ) {
  47694. const listArray = lists.get( scene );
  47695. let list;
  47696. if ( listArray === undefined ) {
  47697. list = new WebGLRenderList();
  47698. lists.set( scene, [ list ] );
  47699. } else {
  47700. if ( renderCallDepth >= listArray.length ) {
  47701. list = new WebGLRenderList();
  47702. listArray.push( list );
  47703. } else {
  47704. list = listArray[ renderCallDepth ];
  47705. }
  47706. }
  47707. return list;
  47708. }
  47709. function dispose() {
  47710. lists = new WeakMap();
  47711. }
  47712. return {
  47713. get: get,
  47714. dispose: dispose
  47715. };
  47716. }
  47717. function UniformsCache() {
  47718. const lights = {};
  47719. return {
  47720. get: function ( light ) {
  47721. if ( lights[ light.id ] !== undefined ) {
  47722. return lights[ light.id ];
  47723. }
  47724. let uniforms;
  47725. switch ( light.type ) {
  47726. case 'DirectionalLight':
  47727. uniforms = {
  47728. direction: new Vector3(),
  47729. color: new Color()
  47730. };
  47731. break;
  47732. case 'SpotLight':
  47733. uniforms = {
  47734. position: new Vector3(),
  47735. direction: new Vector3(),
  47736. color: new Color(),
  47737. distance: 0,
  47738. coneCos: 0,
  47739. penumbraCos: 0,
  47740. decay: 0
  47741. };
  47742. break;
  47743. case 'PointLight':
  47744. uniforms = {
  47745. position: new Vector3(),
  47746. color: new Color(),
  47747. distance: 0,
  47748. decay: 0
  47749. };
  47750. break;
  47751. case 'HemisphereLight':
  47752. uniforms = {
  47753. direction: new Vector3(),
  47754. skyColor: new Color(),
  47755. groundColor: new Color()
  47756. };
  47757. break;
  47758. case 'RectAreaLight':
  47759. uniforms = {
  47760. color: new Color(),
  47761. position: new Vector3(),
  47762. halfWidth: new Vector3(),
  47763. halfHeight: new Vector3()
  47764. };
  47765. break;
  47766. }
  47767. lights[ light.id ] = uniforms;
  47768. return uniforms;
  47769. }
  47770. };
  47771. }
  47772. function ShadowUniformsCache() {
  47773. const lights = {};
  47774. return {
  47775. get: function ( light ) {
  47776. if ( lights[ light.id ] !== undefined ) {
  47777. return lights[ light.id ];
  47778. }
  47779. let uniforms;
  47780. switch ( light.type ) {
  47781. case 'DirectionalLight':
  47782. uniforms = {
  47783. shadowIntensity: 1,
  47784. shadowBias: 0,
  47785. shadowNormalBias: 0,
  47786. shadowRadius: 1,
  47787. shadowMapSize: new Vector2()
  47788. };
  47789. break;
  47790. case 'SpotLight':
  47791. uniforms = {
  47792. shadowIntensity: 1,
  47793. shadowBias: 0,
  47794. shadowNormalBias: 0,
  47795. shadowRadius: 1,
  47796. shadowMapSize: new Vector2()
  47797. };
  47798. break;
  47799. case 'PointLight':
  47800. uniforms = {
  47801. shadowIntensity: 1,
  47802. shadowBias: 0,
  47803. shadowNormalBias: 0,
  47804. shadowRadius: 1,
  47805. shadowMapSize: new Vector2(),
  47806. shadowCameraNear: 1,
  47807. shadowCameraFar: 1000
  47808. };
  47809. break;
  47810. // TODO (abelnation): set RectAreaLight shadow uniforms
  47811. }
  47812. lights[ light.id ] = uniforms;
  47813. return uniforms;
  47814. }
  47815. };
  47816. }
  47817. let nextVersion = 0;
  47818. function shadowCastingAndTexturingLightsFirst( lightA, lightB ) {
  47819. return ( lightB.castShadow ? 2 : 0 ) - ( lightA.castShadow ? 2 : 0 ) + ( lightB.map ? 1 : 0 ) - ( lightA.map ? 1 : 0 );
  47820. }
  47821. function WebGLLights( extensions ) {
  47822. const cache = new UniformsCache();
  47823. const shadowCache = ShadowUniformsCache();
  47824. const state = {
  47825. version: 0,
  47826. hash: {
  47827. directionalLength: -1,
  47828. pointLength: -1,
  47829. spotLength: -1,
  47830. rectAreaLength: -1,
  47831. hemiLength: -1,
  47832. numDirectionalShadows: -1,
  47833. numPointShadows: -1,
  47834. numSpotShadows: -1,
  47835. numSpotMaps: -1,
  47836. numLightProbes: -1
  47837. },
  47838. ambient: [ 0, 0, 0 ],
  47839. probe: [],
  47840. directional: [],
  47841. directionalShadow: [],
  47842. directionalShadowMap: [],
  47843. directionalShadowMatrix: [],
  47844. spot: [],
  47845. spotLightMap: [],
  47846. spotShadow: [],
  47847. spotShadowMap: [],
  47848. spotLightMatrix: [],
  47849. rectArea: [],
  47850. rectAreaLTC1: null,
  47851. rectAreaLTC2: null,
  47852. point: [],
  47853. pointShadow: [],
  47854. pointShadowMap: [],
  47855. pointShadowMatrix: [],
  47856. hemi: [],
  47857. numSpotLightShadowsWithMaps: 0,
  47858. numLightProbes: 0
  47859. };
  47860. for ( let i = 0; i < 9; i ++ ) state.probe.push( new Vector3() );
  47861. const vector3 = new Vector3();
  47862. const matrix4 = new Matrix4();
  47863. const matrix42 = new Matrix4();
  47864. function setup( lights ) {
  47865. let r = 0, g = 0, b = 0;
  47866. for ( let i = 0; i < 9; i ++ ) state.probe[ i ].set( 0, 0, 0 );
  47867. let directionalLength = 0;
  47868. let pointLength = 0;
  47869. let spotLength = 0;
  47870. let rectAreaLength = 0;
  47871. let hemiLength = 0;
  47872. let numDirectionalShadows = 0;
  47873. let numPointShadows = 0;
  47874. let numSpotShadows = 0;
  47875. let numSpotMaps = 0;
  47876. let numSpotShadowsWithMaps = 0;
  47877. let numLightProbes = 0;
  47878. // ordering : [shadow casting + map texturing, map texturing, shadow casting, none ]
  47879. lights.sort( shadowCastingAndTexturingLightsFirst );
  47880. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  47881. const light = lights[ i ];
  47882. const color = light.color;
  47883. const intensity = light.intensity;
  47884. const distance = light.distance;
  47885. const shadowMap = ( light.shadow && light.shadow.map ) ? ( light.shadow.map.depthTexture || light.shadow.map.texture ) : null;
  47886. if ( light.isAmbientLight ) {
  47887. r += color.r * intensity;
  47888. g += color.g * intensity;
  47889. b += color.b * intensity;
  47890. } else if ( light.isLightProbe ) {
  47891. for ( let j = 0; j < 9; j ++ ) {
  47892. state.probe[ j ].addScaledVector( light.sh.coefficients[ j ], intensity );
  47893. }
  47894. numLightProbes ++;
  47895. } else if ( light.isDirectionalLight ) {
  47896. const uniforms = cache.get( light );
  47897. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47898. if ( light.castShadow ) {
  47899. const shadow = light.shadow;
  47900. const shadowUniforms = shadowCache.get( light );
  47901. shadowUniforms.shadowIntensity = shadow.intensity;
  47902. shadowUniforms.shadowBias = shadow.bias;
  47903. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47904. shadowUniforms.shadowRadius = shadow.radius;
  47905. shadowUniforms.shadowMapSize = shadow.mapSize;
  47906. state.directionalShadow[ directionalLength ] = shadowUniforms;
  47907. state.directionalShadowMap[ directionalLength ] = shadowMap;
  47908. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  47909. numDirectionalShadows ++;
  47910. }
  47911. state.directional[ directionalLength ] = uniforms;
  47912. directionalLength ++;
  47913. } else if ( light.isSpotLight ) {
  47914. const uniforms = cache.get( light );
  47915. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  47916. uniforms.color.copy( color ).multiplyScalar( intensity );
  47917. uniforms.distance = distance;
  47918. uniforms.coneCos = Math.cos( light.angle );
  47919. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  47920. uniforms.decay = light.decay;
  47921. state.spot[ spotLength ] = uniforms;
  47922. const shadow = light.shadow;
  47923. if ( light.map ) {
  47924. state.spotLightMap[ numSpotMaps ] = light.map;
  47925. numSpotMaps ++;
  47926. // make sure the lightMatrix is up to date
  47927. // TODO : do it if required only
  47928. shadow.updateMatrices( light );
  47929. if ( light.castShadow ) numSpotShadowsWithMaps ++;
  47930. }
  47931. state.spotLightMatrix[ spotLength ] = shadow.matrix;
  47932. if ( light.castShadow ) {
  47933. const shadowUniforms = shadowCache.get( light );
  47934. shadowUniforms.shadowIntensity = shadow.intensity;
  47935. shadowUniforms.shadowBias = shadow.bias;
  47936. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47937. shadowUniforms.shadowRadius = shadow.radius;
  47938. shadowUniforms.shadowMapSize = shadow.mapSize;
  47939. state.spotShadow[ spotLength ] = shadowUniforms;
  47940. state.spotShadowMap[ spotLength ] = shadowMap;
  47941. numSpotShadows ++;
  47942. }
  47943. spotLength ++;
  47944. } else if ( light.isRectAreaLight ) {
  47945. const uniforms = cache.get( light );
  47946. uniforms.color.copy( color ).multiplyScalar( intensity );
  47947. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  47948. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  47949. state.rectArea[ rectAreaLength ] = uniforms;
  47950. rectAreaLength ++;
  47951. } else if ( light.isPointLight ) {
  47952. const uniforms = cache.get( light );
  47953. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  47954. uniforms.distance = light.distance;
  47955. uniforms.decay = light.decay;
  47956. if ( light.castShadow ) {
  47957. const shadow = light.shadow;
  47958. const shadowUniforms = shadowCache.get( light );
  47959. shadowUniforms.shadowIntensity = shadow.intensity;
  47960. shadowUniforms.shadowBias = shadow.bias;
  47961. shadowUniforms.shadowNormalBias = shadow.normalBias;
  47962. shadowUniforms.shadowRadius = shadow.radius;
  47963. shadowUniforms.shadowMapSize = shadow.mapSize;
  47964. shadowUniforms.shadowCameraNear = shadow.camera.near;
  47965. shadowUniforms.shadowCameraFar = shadow.camera.far;
  47966. state.pointShadow[ pointLength ] = shadowUniforms;
  47967. state.pointShadowMap[ pointLength ] = shadowMap;
  47968. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  47969. numPointShadows ++;
  47970. }
  47971. state.point[ pointLength ] = uniforms;
  47972. pointLength ++;
  47973. } else if ( light.isHemisphereLight ) {
  47974. const uniforms = cache.get( light );
  47975. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  47976. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  47977. state.hemi[ hemiLength ] = uniforms;
  47978. hemiLength ++;
  47979. }
  47980. }
  47981. if ( rectAreaLength > 0 ) {
  47982. if ( extensions.has( 'OES_texture_float_linear' ) === true ) {
  47983. state.rectAreaLTC1 = UniformsLib.LTC_FLOAT_1;
  47984. state.rectAreaLTC2 = UniformsLib.LTC_FLOAT_2;
  47985. } else {
  47986. state.rectAreaLTC1 = UniformsLib.LTC_HALF_1;
  47987. state.rectAreaLTC2 = UniformsLib.LTC_HALF_2;
  47988. }
  47989. }
  47990. state.ambient[ 0 ] = r;
  47991. state.ambient[ 1 ] = g;
  47992. state.ambient[ 2 ] = b;
  47993. const hash = state.hash;
  47994. if ( hash.directionalLength !== directionalLength ||
  47995. hash.pointLength !== pointLength ||
  47996. hash.spotLength !== spotLength ||
  47997. hash.rectAreaLength !== rectAreaLength ||
  47998. hash.hemiLength !== hemiLength ||
  47999. hash.numDirectionalShadows !== numDirectionalShadows ||
  48000. hash.numPointShadows !== numPointShadows ||
  48001. hash.numSpotShadows !== numSpotShadows ||
  48002. hash.numSpotMaps !== numSpotMaps ||
  48003. hash.numLightProbes !== numLightProbes ) {
  48004. state.directional.length = directionalLength;
  48005. state.spot.length = spotLength;
  48006. state.rectArea.length = rectAreaLength;
  48007. state.point.length = pointLength;
  48008. state.hemi.length = hemiLength;
  48009. state.directionalShadow.length = numDirectionalShadows;
  48010. state.directionalShadowMap.length = numDirectionalShadows;
  48011. state.pointShadow.length = numPointShadows;
  48012. state.pointShadowMap.length = numPointShadows;
  48013. state.spotShadow.length = numSpotShadows;
  48014. state.spotShadowMap.length = numSpotShadows;
  48015. state.directionalShadowMatrix.length = numDirectionalShadows;
  48016. state.pointShadowMatrix.length = numPointShadows;
  48017. state.spotLightMatrix.length = numSpotShadows + numSpotMaps - numSpotShadowsWithMaps;
  48018. state.spotLightMap.length = numSpotMaps;
  48019. state.numSpotLightShadowsWithMaps = numSpotShadowsWithMaps;
  48020. state.numLightProbes = numLightProbes;
  48021. hash.directionalLength = directionalLength;
  48022. hash.pointLength = pointLength;
  48023. hash.spotLength = spotLength;
  48024. hash.rectAreaLength = rectAreaLength;
  48025. hash.hemiLength = hemiLength;
  48026. hash.numDirectionalShadows = numDirectionalShadows;
  48027. hash.numPointShadows = numPointShadows;
  48028. hash.numSpotShadows = numSpotShadows;
  48029. hash.numSpotMaps = numSpotMaps;
  48030. hash.numLightProbes = numLightProbes;
  48031. state.version = nextVersion ++;
  48032. }
  48033. }
  48034. function setupView( lights, camera ) {
  48035. let directionalLength = 0;
  48036. let pointLength = 0;
  48037. let spotLength = 0;
  48038. let rectAreaLength = 0;
  48039. let hemiLength = 0;
  48040. const viewMatrix = camera.matrixWorldInverse;
  48041. for ( let i = 0, l = lights.length; i < l; i ++ ) {
  48042. const light = lights[ i ];
  48043. if ( light.isDirectionalLight ) {
  48044. const uniforms = state.directional[ directionalLength ];
  48045. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48046. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48047. uniforms.direction.sub( vector3 );
  48048. uniforms.direction.transformDirection( viewMatrix );
  48049. directionalLength ++;
  48050. } else if ( light.isSpotLight ) {
  48051. const uniforms = state.spot[ spotLength ];
  48052. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48053. uniforms.position.applyMatrix4( viewMatrix );
  48054. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48055. vector3.setFromMatrixPosition( light.target.matrixWorld );
  48056. uniforms.direction.sub( vector3 );
  48057. uniforms.direction.transformDirection( viewMatrix );
  48058. spotLength ++;
  48059. } else if ( light.isRectAreaLight ) {
  48060. const uniforms = state.rectArea[ rectAreaLength ];
  48061. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48062. uniforms.position.applyMatrix4( viewMatrix );
  48063. // extract local rotation of light to derive width/height half vectors
  48064. matrix42.identity();
  48065. matrix4.copy( light.matrixWorld );
  48066. matrix4.premultiply( viewMatrix );
  48067. matrix42.extractRotation( matrix4 );
  48068. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  48069. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  48070. uniforms.halfWidth.applyMatrix4( matrix42 );
  48071. uniforms.halfHeight.applyMatrix4( matrix42 );
  48072. rectAreaLength ++;
  48073. } else if ( light.isPointLight ) {
  48074. const uniforms = state.point[ pointLength ];
  48075. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  48076. uniforms.position.applyMatrix4( viewMatrix );
  48077. pointLength ++;
  48078. } else if ( light.isHemisphereLight ) {
  48079. const uniforms = state.hemi[ hemiLength ];
  48080. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  48081. uniforms.direction.transformDirection( viewMatrix );
  48082. hemiLength ++;
  48083. }
  48084. }
  48085. }
  48086. return {
  48087. setup: setup,
  48088. setupView: setupView,
  48089. state: state
  48090. };
  48091. }
  48092. function WebGLRenderState( extensions ) {
  48093. const lights = new WebGLLights( extensions );
  48094. const lightsArray = [];
  48095. const shadowsArray = [];
  48096. function init( camera ) {
  48097. state.camera = camera;
  48098. lightsArray.length = 0;
  48099. shadowsArray.length = 0;
  48100. }
  48101. function pushLight( light ) {
  48102. lightsArray.push( light );
  48103. }
  48104. function pushShadow( shadowLight ) {
  48105. shadowsArray.push( shadowLight );
  48106. }
  48107. function setupLights() {
  48108. lights.setup( lightsArray );
  48109. }
  48110. function setupLightsView( camera ) {
  48111. lights.setupView( lightsArray, camera );
  48112. }
  48113. const state = {
  48114. lightsArray: lightsArray,
  48115. shadowsArray: shadowsArray,
  48116. camera: null,
  48117. lights: lights,
  48118. transmissionRenderTarget: {}
  48119. };
  48120. return {
  48121. init: init,
  48122. state: state,
  48123. setupLights: setupLights,
  48124. setupLightsView: setupLightsView,
  48125. pushLight: pushLight,
  48126. pushShadow: pushShadow
  48127. };
  48128. }
  48129. function WebGLRenderStates( extensions ) {
  48130. let renderStates = new WeakMap();
  48131. function get( scene, renderCallDepth = 0 ) {
  48132. const renderStateArray = renderStates.get( scene );
  48133. let renderState;
  48134. if ( renderStateArray === undefined ) {
  48135. renderState = new WebGLRenderState( extensions );
  48136. renderStates.set( scene, [ renderState ] );
  48137. } else {
  48138. if ( renderCallDepth >= renderStateArray.length ) {
  48139. renderState = new WebGLRenderState( extensions );
  48140. renderStateArray.push( renderState );
  48141. } else {
  48142. renderState = renderStateArray[ renderCallDepth ];
  48143. }
  48144. }
  48145. return renderState;
  48146. }
  48147. function dispose() {
  48148. renderStates = new WeakMap();
  48149. }
  48150. return {
  48151. get: get,
  48152. dispose: dispose
  48153. };
  48154. }
  48155. const vertex = "void main() {\n\tgl_Position = vec4( position, 1.0 );\n}";
  48156. 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( squared_mean - mean * mean );\n\tgl_FragColor = vec4( mean, std_dev, 0.0, 1.0 );\n}";
  48157. function WebGLShadowMap( renderer, objects, capabilities ) {
  48158. let _frustum = new Frustum();
  48159. const _shadowMapSize = new Vector2(),
  48160. _viewportSize = new Vector2(),
  48161. _viewport = new Vector4(),
  48162. _depthMaterial = new MeshDepthMaterial(),
  48163. _depthMaterialVSM = new MeshDepthMaterial( { depthPacking: IdentityDepthPacking } ),
  48164. _distanceMaterial = new MeshDistanceMaterial(),
  48165. _materialCache = {},
  48166. _maxTextureSize = capabilities.maxTextureSize;
  48167. const shadowSide = { [ FrontSide ]: BackSide, [ BackSide ]: FrontSide, [ DoubleSide ]: DoubleSide };
  48168. const shadowMaterialVertical = new ShaderMaterial( {
  48169. defines: {
  48170. VSM_SAMPLES: 8
  48171. },
  48172. uniforms: {
  48173. shadow_pass: { value: null },
  48174. resolution: { value: new Vector2() },
  48175. radius: { value: 4.0 }
  48176. },
  48177. vertexShader: vertex,
  48178. fragmentShader: fragment
  48179. } );
  48180. const shadowMaterialHorizontal = shadowMaterialVertical.clone();
  48181. shadowMaterialHorizontal.defines.HORIZONTAL_PASS = 1;
  48182. const fullScreenTri = new BufferGeometry();
  48183. fullScreenTri.setAttribute(
  48184. 'position',
  48185. new BufferAttribute(
  48186. new Float32Array( [ -1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5 ] ),
  48187. 3
  48188. )
  48189. );
  48190. const fullScreenMesh = new Mesh( fullScreenTri, shadowMaterialVertical );
  48191. const scope = this;
  48192. this.enabled = false;
  48193. this.autoUpdate = true;
  48194. this.needsUpdate = false;
  48195. this.type = PCFShadowMap;
  48196. let _previousType = this.type;
  48197. this.render = function ( lights, scene, camera ) {
  48198. if ( scope.enabled === false ) return;
  48199. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  48200. if ( lights.length === 0 ) return;
  48201. if ( lights.type === PCFSoftShadowMap ) {
  48202. warn( 'WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.' );
  48203. lights.type = PCFShadowMap;
  48204. }
  48205. const currentRenderTarget = renderer.getRenderTarget();
  48206. const activeCubeFace = renderer.getActiveCubeFace();
  48207. const activeMipmapLevel = renderer.getActiveMipmapLevel();
  48208. const _state = renderer.state;
  48209. // Set GL state for depth map.
  48210. _state.setBlending( NoBlending );
  48211. if ( _state.buffers.depth.getReversed() === true ) {
  48212. _state.buffers.color.setClear( 0, 0, 0, 0 );
  48213. } else {
  48214. _state.buffers.color.setClear( 1, 1, 1, 1 );
  48215. }
  48216. _state.buffers.depth.setTest( true );
  48217. _state.setScissorTest( false );
  48218. // check for shadow map type changes
  48219. const typeChanged = _previousType !== this.type;
  48220. // When shadow map type changes, materials need recompilation because sampler types change
  48221. // (sampler2DShadow for PCF vs sampler2D for Basic)
  48222. if ( typeChanged ) {
  48223. scene.traverse( function ( object ) {
  48224. if ( object.material ) {
  48225. if ( Array.isArray( object.material ) ) {
  48226. object.material.forEach( mat => mat.needsUpdate = true );
  48227. } else {
  48228. object.material.needsUpdate = true;
  48229. }
  48230. }
  48231. } );
  48232. }
  48233. // render depth map
  48234. for ( let i = 0, il = lights.length; i < il; i ++ ) {
  48235. const light = lights[ i ];
  48236. const shadow = light.shadow;
  48237. if ( shadow === undefined ) {
  48238. warn( 'WebGLShadowMap:', light, 'has no shadow.' );
  48239. continue;
  48240. }
  48241. if ( shadow.autoUpdate === false && shadow.needsUpdate === false ) continue;
  48242. _shadowMapSize.copy( shadow.mapSize );
  48243. const shadowFrameExtents = shadow.getFrameExtents();
  48244. _shadowMapSize.multiply( shadowFrameExtents );
  48245. _viewportSize.copy( shadow.mapSize );
  48246. if ( _shadowMapSize.x > _maxTextureSize || _shadowMapSize.y > _maxTextureSize ) {
  48247. if ( _shadowMapSize.x > _maxTextureSize ) {
  48248. _viewportSize.x = Math.floor( _maxTextureSize / shadowFrameExtents.x );
  48249. _shadowMapSize.x = _viewportSize.x * shadowFrameExtents.x;
  48250. shadow.mapSize.x = _viewportSize.x;
  48251. }
  48252. if ( _shadowMapSize.y > _maxTextureSize ) {
  48253. _viewportSize.y = Math.floor( _maxTextureSize / shadowFrameExtents.y );
  48254. _shadowMapSize.y = _viewportSize.y * shadowFrameExtents.y;
  48255. shadow.mapSize.y = _viewportSize.y;
  48256. }
  48257. }
  48258. if ( shadow.map === null || typeChanged === true ) {
  48259. if ( shadow.map !== null ) {
  48260. if ( shadow.map.depthTexture !== null ) {
  48261. shadow.map.depthTexture.dispose();
  48262. shadow.map.depthTexture = null;
  48263. }
  48264. shadow.map.dispose();
  48265. }
  48266. if ( this.type === VSMShadowMap ) {
  48267. if ( light.isPointLight ) {
  48268. warn( 'WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.' );
  48269. continue;
  48270. }
  48271. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48272. format: RGFormat,
  48273. type: HalfFloatType,
  48274. minFilter: LinearFilter,
  48275. magFilter: LinearFilter,
  48276. generateMipmaps: false
  48277. } );
  48278. shadow.map.texture.name = light.name + '.shadowMap';
  48279. } else {
  48280. if ( light.isPointLight ) {
  48281. shadow.map = new WebGLCubeRenderTarget( _shadowMapSize.x );
  48282. shadow.map.depthTexture = new CubeDepthTexture( _shadowMapSize.x, UnsignedIntType );
  48283. } else {
  48284. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y );
  48285. shadow.map.depthTexture = new DepthTexture( _shadowMapSize.x, _shadowMapSize.y, UnsignedIntType );
  48286. }
  48287. shadow.map.depthTexture.name = light.name + '.shadowMap';
  48288. shadow.map.depthTexture.format = DepthFormat;
  48289. const reversedDepthBuffer = renderer.state.buffers.depth.getReversed();
  48290. if ( this.type === PCFShadowMap ) {
  48291. shadow.map.depthTexture.compareFunction = reversedDepthBuffer ? GreaterEqualCompare : LessEqualCompare;
  48292. shadow.map.depthTexture.minFilter = LinearFilter;
  48293. shadow.map.depthTexture.magFilter = LinearFilter;
  48294. } else {
  48295. shadow.map.depthTexture.compareFunction = null;
  48296. shadow.map.depthTexture.minFilter = NearestFilter;
  48297. shadow.map.depthTexture.magFilter = NearestFilter;
  48298. }
  48299. }
  48300. shadow.camera.updateProjectionMatrix();
  48301. }
  48302. // For cube render targets (PointLights), render all 6 faces. Otherwise, render once.
  48303. const faceCount = shadow.map.isWebGLCubeRenderTarget ? 6 : 1;
  48304. for ( let face = 0; face < faceCount; face ++ ) {
  48305. // For cube render targets, render to each face separately
  48306. if ( shadow.map.isWebGLCubeRenderTarget ) {
  48307. renderer.setRenderTarget( shadow.map, face );
  48308. renderer.clear();
  48309. } else {
  48310. // For 2D render targets, use viewports
  48311. if ( face === 0 ) {
  48312. renderer.setRenderTarget( shadow.map );
  48313. renderer.clear();
  48314. }
  48315. const viewport = shadow.getViewport( face );
  48316. _viewport.set(
  48317. _viewportSize.x * viewport.x,
  48318. _viewportSize.y * viewport.y,
  48319. _viewportSize.x * viewport.z,
  48320. _viewportSize.y * viewport.w
  48321. );
  48322. _state.viewport( _viewport );
  48323. }
  48324. shadow.updateMatrices( light, face );
  48325. _frustum = shadow.getFrustum();
  48326. renderObject( scene, camera, shadow.camera, light, this.type );
  48327. }
  48328. // do blur pass for VSM
  48329. if ( shadow.isPointLightShadow !== true && this.type === VSMShadowMap ) {
  48330. VSMPass( shadow, camera );
  48331. }
  48332. shadow.needsUpdate = false;
  48333. }
  48334. _previousType = this.type;
  48335. scope.needsUpdate = false;
  48336. renderer.setRenderTarget( currentRenderTarget, activeCubeFace, activeMipmapLevel );
  48337. };
  48338. function VSMPass( shadow, camera ) {
  48339. const geometry = objects.update( fullScreenMesh );
  48340. if ( shadowMaterialVertical.defines.VSM_SAMPLES !== shadow.blurSamples ) {
  48341. shadowMaterialVertical.defines.VSM_SAMPLES = shadow.blurSamples;
  48342. shadowMaterialHorizontal.defines.VSM_SAMPLES = shadow.blurSamples;
  48343. shadowMaterialVertical.needsUpdate = true;
  48344. shadowMaterialHorizontal.needsUpdate = true;
  48345. }
  48346. if ( shadow.mapPass === null ) {
  48347. shadow.mapPass = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, {
  48348. format: RGFormat,
  48349. type: HalfFloatType
  48350. } );
  48351. }
  48352. // vertical pass
  48353. shadowMaterialVertical.uniforms.shadow_pass.value = shadow.map.texture;
  48354. shadowMaterialVertical.uniforms.resolution.value = shadow.mapSize;
  48355. shadowMaterialVertical.uniforms.radius.value = shadow.radius;
  48356. renderer.setRenderTarget( shadow.mapPass );
  48357. renderer.clear();
  48358. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialVertical, fullScreenMesh, null );
  48359. // horizontal pass
  48360. shadowMaterialHorizontal.uniforms.shadow_pass.value = shadow.mapPass.texture;
  48361. shadowMaterialHorizontal.uniforms.resolution.value = shadow.mapSize;
  48362. shadowMaterialHorizontal.uniforms.radius.value = shadow.radius;
  48363. renderer.setRenderTarget( shadow.map );
  48364. renderer.clear();
  48365. renderer.renderBufferDirect( camera, null, geometry, shadowMaterialHorizontal, fullScreenMesh, null );
  48366. }
  48367. function getDepthMaterial( object, material, light, type ) {
  48368. let result = null;
  48369. const customMaterial = ( light.isPointLight === true ) ? object.customDistanceMaterial : object.customDepthMaterial;
  48370. if ( customMaterial !== undefined ) {
  48371. result = customMaterial;
  48372. } else {
  48373. if ( type === VSMShadowMap ) {
  48374. result = _depthMaterialVSM;
  48375. } else {
  48376. result = ( light.isPointLight === true ) ? _distanceMaterial : _depthMaterial;
  48377. }
  48378. if ( ( renderer.localClippingEnabled && material.clipShadows === true && Array.isArray( material.clippingPlanes ) && material.clippingPlanes.length !== 0 ) ||
  48379. ( material.displacementMap && material.displacementScale !== 0 ) ||
  48380. ( material.alphaMap && material.alphaTest > 0 ) ||
  48381. ( material.map && material.alphaTest > 0 ) ||
  48382. ( material.alphaToCoverage === true ) ) {
  48383. // in this case we need a unique material instance reflecting the
  48384. // appropriate state
  48385. const keyA = result.uuid, keyB = material.uuid;
  48386. let materialsForVariant = _materialCache[ keyA ];
  48387. if ( materialsForVariant === undefined ) {
  48388. materialsForVariant = {};
  48389. _materialCache[ keyA ] = materialsForVariant;
  48390. }
  48391. let cachedMaterial = materialsForVariant[ keyB ];
  48392. if ( cachedMaterial === undefined ) {
  48393. cachedMaterial = result.clone();
  48394. materialsForVariant[ keyB ] = cachedMaterial;
  48395. material.addEventListener( 'dispose', onMaterialDispose );
  48396. }
  48397. result = cachedMaterial;
  48398. }
  48399. }
  48400. result.visible = material.visible;
  48401. result.wireframe = material.wireframe;
  48402. if ( type === VSMShadowMap ) {
  48403. result.side = ( material.shadowSide !== null ) ? material.shadowSide : material.side;
  48404. } else {
  48405. result.side = ( material.shadowSide !== null ) ? material.shadowSide : shadowSide[ material.side ];
  48406. }
  48407. result.alphaMap = material.alphaMap;
  48408. result.alphaTest = ( material.alphaToCoverage === true ) ? 0.5 : material.alphaTest; // approximate alphaToCoverage by using a fixed alphaTest value
  48409. result.map = material.map;
  48410. result.clipShadows = material.clipShadows;
  48411. result.clippingPlanes = material.clippingPlanes;
  48412. result.clipIntersection = material.clipIntersection;
  48413. result.displacementMap = material.displacementMap;
  48414. result.displacementScale = material.displacementScale;
  48415. result.displacementBias = material.displacementBias;
  48416. result.wireframeLinewidth = material.wireframeLinewidth;
  48417. result.linewidth = material.linewidth;
  48418. if ( light.isPointLight === true && result.isMeshDistanceMaterial === true ) {
  48419. const materialProperties = renderer.properties.get( result );
  48420. materialProperties.light = light;
  48421. }
  48422. return result;
  48423. }
  48424. function renderObject( object, camera, shadowCamera, light, type ) {
  48425. if ( object.visible === false ) return;
  48426. const visible = object.layers.test( camera.layers );
  48427. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  48428. if ( ( object.castShadow || ( object.receiveShadow && type === VSMShadowMap ) ) && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  48429. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  48430. const geometry = objects.update( object );
  48431. const material = object.material;
  48432. if ( Array.isArray( material ) ) {
  48433. const groups = geometry.groups;
  48434. for ( let k = 0, kl = groups.length; k < kl; k ++ ) {
  48435. const group = groups[ k ];
  48436. const groupMaterial = material[ group.materialIndex ];
  48437. if ( groupMaterial && groupMaterial.visible ) {
  48438. const depthMaterial = getDepthMaterial( object, groupMaterial, light, type );
  48439. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48440. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  48441. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, group );
  48442. }
  48443. }
  48444. } else if ( material.visible ) {
  48445. const depthMaterial = getDepthMaterial( object, material, light, type );
  48446. object.onBeforeShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48447. renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  48448. object.onAfterShadow( renderer, object, camera, shadowCamera, geometry, depthMaterial, null );
  48449. }
  48450. }
  48451. }
  48452. const children = object.children;
  48453. for ( let i = 0, l = children.length; i < l; i ++ ) {
  48454. renderObject( children[ i ], camera, shadowCamera, light, type );
  48455. }
  48456. }
  48457. function onMaterialDispose( event ) {
  48458. const material = event.target;
  48459. material.removeEventListener( 'dispose', onMaterialDispose );
  48460. // make sure to remove the unique distance/depth materials used for shadow map rendering
  48461. for ( const id in _materialCache ) {
  48462. const cache = _materialCache[ id ];
  48463. const uuid = event.target.uuid;
  48464. if ( uuid in cache ) {
  48465. const shadowMaterial = cache[ uuid ];
  48466. shadowMaterial.dispose();
  48467. delete cache[ uuid ];
  48468. }
  48469. }
  48470. }
  48471. }
  48472. const reversedFuncs = {
  48473. [ NeverDepth ]: AlwaysDepth,
  48474. [ LessDepth ]: GreaterDepth,
  48475. [ EqualDepth ]: NotEqualDepth,
  48476. [ LessEqualDepth ]: GreaterEqualDepth,
  48477. [ AlwaysDepth ]: NeverDepth,
  48478. [ GreaterDepth ]: LessDepth,
  48479. [ NotEqualDepth ]: EqualDepth,
  48480. [ GreaterEqualDepth ]: LessEqualDepth,
  48481. };
  48482. function WebGLState( gl, extensions ) {
  48483. function ColorBuffer() {
  48484. let locked = false;
  48485. const color = new Vector4();
  48486. let currentColorMask = null;
  48487. const currentColorClear = new Vector4( 0, 0, 0, 0 );
  48488. return {
  48489. setMask: function ( colorMask ) {
  48490. if ( currentColorMask !== colorMask && ! locked ) {
  48491. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  48492. currentColorMask = colorMask;
  48493. }
  48494. },
  48495. setLocked: function ( lock ) {
  48496. locked = lock;
  48497. },
  48498. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  48499. if ( premultipliedAlpha === true ) {
  48500. r *= a; g *= a; b *= a;
  48501. }
  48502. color.set( r, g, b, a );
  48503. if ( currentColorClear.equals( color ) === false ) {
  48504. gl.clearColor( r, g, b, a );
  48505. currentColorClear.copy( color );
  48506. }
  48507. },
  48508. reset: function () {
  48509. locked = false;
  48510. currentColorMask = null;
  48511. currentColorClear.set( -1, 0, 0, 0 ); // set to invalid state
  48512. }
  48513. };
  48514. }
  48515. function DepthBuffer() {
  48516. let locked = false;
  48517. let currentReversed = false;
  48518. let currentDepthMask = null;
  48519. let currentDepthFunc = null;
  48520. let currentDepthClear = null;
  48521. return {
  48522. setReversed: function ( reversed ) {
  48523. if ( currentReversed !== reversed ) {
  48524. const ext = extensions.get( 'EXT_clip_control' );
  48525. if ( reversed ) {
  48526. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.ZERO_TO_ONE_EXT );
  48527. } else {
  48528. ext.clipControlEXT( ext.LOWER_LEFT_EXT, ext.NEGATIVE_ONE_TO_ONE_EXT );
  48529. }
  48530. currentReversed = reversed;
  48531. const oldDepth = currentDepthClear;
  48532. currentDepthClear = null;
  48533. this.setClear( oldDepth );
  48534. }
  48535. },
  48536. getReversed: function () {
  48537. return currentReversed;
  48538. },
  48539. setTest: function ( depthTest ) {
  48540. if ( depthTest ) {
  48541. enable( gl.DEPTH_TEST );
  48542. } else {
  48543. disable( gl.DEPTH_TEST );
  48544. }
  48545. },
  48546. setMask: function ( depthMask ) {
  48547. if ( currentDepthMask !== depthMask && ! locked ) {
  48548. gl.depthMask( depthMask );
  48549. currentDepthMask = depthMask;
  48550. }
  48551. },
  48552. setFunc: function ( depthFunc ) {
  48553. if ( currentReversed ) depthFunc = reversedFuncs[ depthFunc ];
  48554. if ( currentDepthFunc !== depthFunc ) {
  48555. switch ( depthFunc ) {
  48556. case NeverDepth:
  48557. gl.depthFunc( gl.NEVER );
  48558. break;
  48559. case AlwaysDepth:
  48560. gl.depthFunc( gl.ALWAYS );
  48561. break;
  48562. case LessDepth:
  48563. gl.depthFunc( gl.LESS );
  48564. break;
  48565. case LessEqualDepth:
  48566. gl.depthFunc( gl.LEQUAL );
  48567. break;
  48568. case EqualDepth:
  48569. gl.depthFunc( gl.EQUAL );
  48570. break;
  48571. case GreaterEqualDepth:
  48572. gl.depthFunc( gl.GEQUAL );
  48573. break;
  48574. case GreaterDepth:
  48575. gl.depthFunc( gl.GREATER );
  48576. break;
  48577. case NotEqualDepth:
  48578. gl.depthFunc( gl.NOTEQUAL );
  48579. break;
  48580. default:
  48581. gl.depthFunc( gl.LEQUAL );
  48582. }
  48583. currentDepthFunc = depthFunc;
  48584. }
  48585. },
  48586. setLocked: function ( lock ) {
  48587. locked = lock;
  48588. },
  48589. setClear: function ( depth ) {
  48590. if ( currentDepthClear !== depth ) {
  48591. if ( currentReversed ) {
  48592. depth = 1 - depth;
  48593. }
  48594. gl.clearDepth( depth );
  48595. currentDepthClear = depth;
  48596. }
  48597. },
  48598. reset: function () {
  48599. locked = false;
  48600. currentDepthMask = null;
  48601. currentDepthFunc = null;
  48602. currentDepthClear = null;
  48603. currentReversed = false;
  48604. }
  48605. };
  48606. }
  48607. function StencilBuffer() {
  48608. let locked = false;
  48609. let currentStencilMask = null;
  48610. let currentStencilFunc = null;
  48611. let currentStencilRef = null;
  48612. let currentStencilFuncMask = null;
  48613. let currentStencilFail = null;
  48614. let currentStencilZFail = null;
  48615. let currentStencilZPass = null;
  48616. let currentStencilClear = null;
  48617. return {
  48618. setTest: function ( stencilTest ) {
  48619. if ( ! locked ) {
  48620. if ( stencilTest ) {
  48621. enable( gl.STENCIL_TEST );
  48622. } else {
  48623. disable( gl.STENCIL_TEST );
  48624. }
  48625. }
  48626. },
  48627. setMask: function ( stencilMask ) {
  48628. if ( currentStencilMask !== stencilMask && ! locked ) {
  48629. gl.stencilMask( stencilMask );
  48630. currentStencilMask = stencilMask;
  48631. }
  48632. },
  48633. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  48634. if ( currentStencilFunc !== stencilFunc ||
  48635. currentStencilRef !== stencilRef ||
  48636. currentStencilFuncMask !== stencilMask ) {
  48637. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  48638. currentStencilFunc = stencilFunc;
  48639. currentStencilRef = stencilRef;
  48640. currentStencilFuncMask = stencilMask;
  48641. }
  48642. },
  48643. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  48644. if ( currentStencilFail !== stencilFail ||
  48645. currentStencilZFail !== stencilZFail ||
  48646. currentStencilZPass !== stencilZPass ) {
  48647. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  48648. currentStencilFail = stencilFail;
  48649. currentStencilZFail = stencilZFail;
  48650. currentStencilZPass = stencilZPass;
  48651. }
  48652. },
  48653. setLocked: function ( lock ) {
  48654. locked = lock;
  48655. },
  48656. setClear: function ( stencil ) {
  48657. if ( currentStencilClear !== stencil ) {
  48658. gl.clearStencil( stencil );
  48659. currentStencilClear = stencil;
  48660. }
  48661. },
  48662. reset: function () {
  48663. locked = false;
  48664. currentStencilMask = null;
  48665. currentStencilFunc = null;
  48666. currentStencilRef = null;
  48667. currentStencilFuncMask = null;
  48668. currentStencilFail = null;
  48669. currentStencilZFail = null;
  48670. currentStencilZPass = null;
  48671. currentStencilClear = null;
  48672. }
  48673. };
  48674. }
  48675. //
  48676. const colorBuffer = new ColorBuffer();
  48677. const depthBuffer = new DepthBuffer();
  48678. const stencilBuffer = new StencilBuffer();
  48679. const uboBindings = new WeakMap();
  48680. const uboProgramMap = new WeakMap();
  48681. let enabledCapabilities = {};
  48682. let currentBoundFramebuffers = {};
  48683. let currentDrawbuffers = new WeakMap();
  48684. let defaultDrawbuffers = [];
  48685. let currentProgram = null;
  48686. let currentBlendingEnabled = false;
  48687. let currentBlending = null;
  48688. let currentBlendEquation = null;
  48689. let currentBlendSrc = null;
  48690. let currentBlendDst = null;
  48691. let currentBlendEquationAlpha = null;
  48692. let currentBlendSrcAlpha = null;
  48693. let currentBlendDstAlpha = null;
  48694. let currentBlendColor = new Color( 0, 0, 0 );
  48695. let currentBlendAlpha = 0;
  48696. let currentPremultipledAlpha = false;
  48697. let currentFlipSided = null;
  48698. let currentCullFace = null;
  48699. let currentLineWidth = null;
  48700. let currentPolygonOffsetFactor = null;
  48701. let currentPolygonOffsetUnits = null;
  48702. const maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  48703. let lineWidthAvailable = false;
  48704. let version = 0;
  48705. const glVersion = gl.getParameter( gl.VERSION );
  48706. if ( glVersion.indexOf( 'WebGL' ) !== -1 ) {
  48707. version = parseFloat( /^WebGL (\d)/.exec( glVersion )[ 1 ] );
  48708. lineWidthAvailable = ( version >= 1.0 );
  48709. } else if ( glVersion.indexOf( 'OpenGL ES' ) !== -1 ) {
  48710. version = parseFloat( /^OpenGL ES (\d)/.exec( glVersion )[ 1 ] );
  48711. lineWidthAvailable = ( version >= 2.0 );
  48712. }
  48713. let currentTextureSlot = null;
  48714. let currentBoundTextures = {};
  48715. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  48716. const viewportParam = gl.getParameter( gl.VIEWPORT );
  48717. const currentScissor = new Vector4().fromArray( scissorParam );
  48718. const currentViewport = new Vector4().fromArray( viewportParam );
  48719. function createTexture( type, target, count, dimensions ) {
  48720. const data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  48721. const texture = gl.createTexture();
  48722. gl.bindTexture( type, texture );
  48723. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  48724. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  48725. for ( let i = 0; i < count; i ++ ) {
  48726. if ( type === gl.TEXTURE_3D || type === gl.TEXTURE_2D_ARRAY ) {
  48727. gl.texImage3D( target, 0, gl.RGBA, 1, 1, dimensions, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48728. } else {
  48729. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  48730. }
  48731. }
  48732. return texture;
  48733. }
  48734. const emptyTextures = {};
  48735. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  48736. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  48737. emptyTextures[ gl.TEXTURE_2D_ARRAY ] = createTexture( gl.TEXTURE_2D_ARRAY, gl.TEXTURE_2D_ARRAY, 1, 1 );
  48738. emptyTextures[ gl.TEXTURE_3D ] = createTexture( gl.TEXTURE_3D, gl.TEXTURE_3D, 1, 1 );
  48739. // init
  48740. colorBuffer.setClear( 0, 0, 0, 1 );
  48741. depthBuffer.setClear( 1 );
  48742. stencilBuffer.setClear( 0 );
  48743. enable( gl.DEPTH_TEST );
  48744. depthBuffer.setFunc( LessEqualDepth );
  48745. setFlipSided( false );
  48746. setCullFace( CullFaceBack );
  48747. enable( gl.CULL_FACE );
  48748. setBlending( NoBlending );
  48749. //
  48750. function enable( id ) {
  48751. if ( enabledCapabilities[ id ] !== true ) {
  48752. gl.enable( id );
  48753. enabledCapabilities[ id ] = true;
  48754. }
  48755. }
  48756. function disable( id ) {
  48757. if ( enabledCapabilities[ id ] !== false ) {
  48758. gl.disable( id );
  48759. enabledCapabilities[ id ] = false;
  48760. }
  48761. }
  48762. function bindFramebuffer( target, framebuffer ) {
  48763. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  48764. gl.bindFramebuffer( target, framebuffer );
  48765. currentBoundFramebuffers[ target ] = framebuffer;
  48766. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  48767. if ( target === gl.DRAW_FRAMEBUFFER ) {
  48768. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  48769. }
  48770. if ( target === gl.FRAMEBUFFER ) {
  48771. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  48772. }
  48773. return true;
  48774. }
  48775. return false;
  48776. }
  48777. function drawBuffers( renderTarget, framebuffer ) {
  48778. let drawBuffers = defaultDrawbuffers;
  48779. let needsUpdate = false;
  48780. if ( renderTarget ) {
  48781. drawBuffers = currentDrawbuffers.get( framebuffer );
  48782. if ( drawBuffers === undefined ) {
  48783. drawBuffers = [];
  48784. currentDrawbuffers.set( framebuffer, drawBuffers );
  48785. }
  48786. const textures = renderTarget.textures;
  48787. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  48788. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  48789. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  48790. }
  48791. drawBuffers.length = textures.length;
  48792. needsUpdate = true;
  48793. }
  48794. } else {
  48795. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  48796. drawBuffers[ 0 ] = gl.BACK;
  48797. needsUpdate = true;
  48798. }
  48799. }
  48800. if ( needsUpdate ) {
  48801. gl.drawBuffers( drawBuffers );
  48802. }
  48803. }
  48804. function useProgram( program ) {
  48805. if ( currentProgram !== program ) {
  48806. gl.useProgram( program );
  48807. currentProgram = program;
  48808. return true;
  48809. }
  48810. return false;
  48811. }
  48812. const equationToGL = {
  48813. [ AddEquation ]: gl.FUNC_ADD,
  48814. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  48815. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  48816. };
  48817. equationToGL[ MinEquation ] = gl.MIN;
  48818. equationToGL[ MaxEquation ] = gl.MAX;
  48819. const factorToGL = {
  48820. [ ZeroFactor ]: gl.ZERO,
  48821. [ OneFactor ]: gl.ONE,
  48822. [ SrcColorFactor ]: gl.SRC_COLOR,
  48823. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  48824. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  48825. [ DstColorFactor ]: gl.DST_COLOR,
  48826. [ DstAlphaFactor ]: gl.DST_ALPHA,
  48827. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  48828. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  48829. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  48830. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA,
  48831. [ ConstantColorFactor ]: gl.CONSTANT_COLOR,
  48832. [ OneMinusConstantColorFactor ]: gl.ONE_MINUS_CONSTANT_COLOR,
  48833. [ ConstantAlphaFactor ]: gl.CONSTANT_ALPHA,
  48834. [ OneMinusConstantAlphaFactor ]: gl.ONE_MINUS_CONSTANT_ALPHA
  48835. };
  48836. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, blendColor, blendAlpha, premultipliedAlpha ) {
  48837. if ( blending === NoBlending ) {
  48838. if ( currentBlendingEnabled === true ) {
  48839. disable( gl.BLEND );
  48840. currentBlendingEnabled = false;
  48841. }
  48842. return;
  48843. }
  48844. if ( currentBlendingEnabled === false ) {
  48845. enable( gl.BLEND );
  48846. currentBlendingEnabled = true;
  48847. }
  48848. if ( blending !== CustomBlending ) {
  48849. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  48850. if ( currentBlendEquation !== AddEquation || currentBlendEquationAlpha !== AddEquation ) {
  48851. gl.blendEquation( gl.FUNC_ADD );
  48852. currentBlendEquation = AddEquation;
  48853. currentBlendEquationAlpha = AddEquation;
  48854. }
  48855. if ( premultipliedAlpha ) {
  48856. switch ( blending ) {
  48857. case NormalBlending:
  48858. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48859. break;
  48860. case AdditiveBlending:
  48861. gl.blendFunc( gl.ONE, gl.ONE );
  48862. break;
  48863. case SubtractiveBlending:
  48864. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  48865. break;
  48866. case MultiplyBlending:
  48867. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  48868. break;
  48869. default:
  48870. error( 'WebGLState: Invalid blending: ', blending );
  48871. break;
  48872. }
  48873. } else {
  48874. switch ( blending ) {
  48875. case NormalBlending:
  48876. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  48877. break;
  48878. case AdditiveBlending:
  48879. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  48880. break;
  48881. case SubtractiveBlending:
  48882. error( 'WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  48883. break;
  48884. case MultiplyBlending:
  48885. error( 'WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  48886. break;
  48887. default:
  48888. error( 'WebGLState: Invalid blending: ', blending );
  48889. break;
  48890. }
  48891. }
  48892. currentBlendSrc = null;
  48893. currentBlendDst = null;
  48894. currentBlendSrcAlpha = null;
  48895. currentBlendDstAlpha = null;
  48896. currentBlendColor.set( 0, 0, 0 );
  48897. currentBlendAlpha = 0;
  48898. currentBlending = blending;
  48899. currentPremultipledAlpha = premultipliedAlpha;
  48900. }
  48901. return;
  48902. }
  48903. // custom blending
  48904. blendEquationAlpha = blendEquationAlpha || blendEquation;
  48905. blendSrcAlpha = blendSrcAlpha || blendSrc;
  48906. blendDstAlpha = blendDstAlpha || blendDst;
  48907. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  48908. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  48909. currentBlendEquation = blendEquation;
  48910. currentBlendEquationAlpha = blendEquationAlpha;
  48911. }
  48912. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  48913. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  48914. currentBlendSrc = blendSrc;
  48915. currentBlendDst = blendDst;
  48916. currentBlendSrcAlpha = blendSrcAlpha;
  48917. currentBlendDstAlpha = blendDstAlpha;
  48918. }
  48919. if ( blendColor.equals( currentBlendColor ) === false || blendAlpha !== currentBlendAlpha ) {
  48920. gl.blendColor( blendColor.r, blendColor.g, blendColor.b, blendAlpha );
  48921. currentBlendColor.copy( blendColor );
  48922. currentBlendAlpha = blendAlpha;
  48923. }
  48924. currentBlending = blending;
  48925. currentPremultipledAlpha = false;
  48926. }
  48927. function setMaterial( material, frontFaceCW ) {
  48928. material.side === DoubleSide
  48929. ? disable( gl.CULL_FACE )
  48930. : enable( gl.CULL_FACE );
  48931. let flipSided = ( material.side === BackSide );
  48932. if ( frontFaceCW ) flipSided = ! flipSided;
  48933. setFlipSided( flipSided );
  48934. ( material.blending === NormalBlending && material.transparent === false )
  48935. ? setBlending( NoBlending )
  48936. : setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.blendColor, material.blendAlpha, material.premultipliedAlpha );
  48937. depthBuffer.setFunc( material.depthFunc );
  48938. depthBuffer.setTest( material.depthTest );
  48939. depthBuffer.setMask( material.depthWrite );
  48940. colorBuffer.setMask( material.colorWrite );
  48941. const stencilWrite = material.stencilWrite;
  48942. stencilBuffer.setTest( stencilWrite );
  48943. if ( stencilWrite ) {
  48944. stencilBuffer.setMask( material.stencilWriteMask );
  48945. stencilBuffer.setFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  48946. stencilBuffer.setOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  48947. }
  48948. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  48949. material.alphaToCoverage === true
  48950. ? enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  48951. : disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  48952. }
  48953. //
  48954. function setFlipSided( flipSided ) {
  48955. if ( currentFlipSided !== flipSided ) {
  48956. if ( flipSided ) {
  48957. gl.frontFace( gl.CW );
  48958. } else {
  48959. gl.frontFace( gl.CCW );
  48960. }
  48961. currentFlipSided = flipSided;
  48962. }
  48963. }
  48964. function setCullFace( cullFace ) {
  48965. if ( cullFace !== CullFaceNone ) {
  48966. enable( gl.CULL_FACE );
  48967. if ( cullFace !== currentCullFace ) {
  48968. if ( cullFace === CullFaceBack ) {
  48969. gl.cullFace( gl.BACK );
  48970. } else if ( cullFace === CullFaceFront ) {
  48971. gl.cullFace( gl.FRONT );
  48972. } else {
  48973. gl.cullFace( gl.FRONT_AND_BACK );
  48974. }
  48975. }
  48976. } else {
  48977. disable( gl.CULL_FACE );
  48978. }
  48979. currentCullFace = cullFace;
  48980. }
  48981. function setLineWidth( width ) {
  48982. if ( width !== currentLineWidth ) {
  48983. if ( lineWidthAvailable ) gl.lineWidth( width );
  48984. currentLineWidth = width;
  48985. }
  48986. }
  48987. function setPolygonOffset( polygonOffset, factor, units ) {
  48988. if ( polygonOffset ) {
  48989. enable( gl.POLYGON_OFFSET_FILL );
  48990. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  48991. gl.polygonOffset( factor, units );
  48992. currentPolygonOffsetFactor = factor;
  48993. currentPolygonOffsetUnits = units;
  48994. }
  48995. } else {
  48996. disable( gl.POLYGON_OFFSET_FILL );
  48997. }
  48998. }
  48999. function setScissorTest( scissorTest ) {
  49000. if ( scissorTest ) {
  49001. enable( gl.SCISSOR_TEST );
  49002. } else {
  49003. disable( gl.SCISSOR_TEST );
  49004. }
  49005. }
  49006. // texture
  49007. function activeTexture( webglSlot ) {
  49008. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49009. if ( currentTextureSlot !== webglSlot ) {
  49010. gl.activeTexture( webglSlot );
  49011. currentTextureSlot = webglSlot;
  49012. }
  49013. }
  49014. function bindTexture( webglType, webglTexture, webglSlot ) {
  49015. if ( webglSlot === undefined ) {
  49016. if ( currentTextureSlot === null ) {
  49017. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  49018. } else {
  49019. webglSlot = currentTextureSlot;
  49020. }
  49021. }
  49022. let boundTexture = currentBoundTextures[ webglSlot ];
  49023. if ( boundTexture === undefined ) {
  49024. boundTexture = { type: undefined, texture: undefined };
  49025. currentBoundTextures[ webglSlot ] = boundTexture;
  49026. }
  49027. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  49028. if ( currentTextureSlot !== webglSlot ) {
  49029. gl.activeTexture( webglSlot );
  49030. currentTextureSlot = webglSlot;
  49031. }
  49032. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  49033. boundTexture.type = webglType;
  49034. boundTexture.texture = webglTexture;
  49035. }
  49036. }
  49037. function unbindTexture() {
  49038. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  49039. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  49040. gl.bindTexture( boundTexture.type, null );
  49041. boundTexture.type = undefined;
  49042. boundTexture.texture = undefined;
  49043. }
  49044. }
  49045. function compressedTexImage2D() {
  49046. try {
  49047. gl.compressedTexImage2D( ...arguments );
  49048. } catch ( e ) {
  49049. error( 'WebGLState:', e );
  49050. }
  49051. }
  49052. function compressedTexImage3D() {
  49053. try {
  49054. gl.compressedTexImage3D( ...arguments );
  49055. } catch ( e ) {
  49056. error( 'WebGLState:', e );
  49057. }
  49058. }
  49059. function texSubImage2D() {
  49060. try {
  49061. gl.texSubImage2D( ...arguments );
  49062. } catch ( e ) {
  49063. error( 'WebGLState:', e );
  49064. }
  49065. }
  49066. function texSubImage3D() {
  49067. try {
  49068. gl.texSubImage3D( ...arguments );
  49069. } catch ( e ) {
  49070. error( 'WebGLState:', e );
  49071. }
  49072. }
  49073. function compressedTexSubImage2D() {
  49074. try {
  49075. gl.compressedTexSubImage2D( ...arguments );
  49076. } catch ( e ) {
  49077. error( 'WebGLState:', e );
  49078. }
  49079. }
  49080. function compressedTexSubImage3D() {
  49081. try {
  49082. gl.compressedTexSubImage3D( ...arguments );
  49083. } catch ( e ) {
  49084. error( 'WebGLState:', e );
  49085. }
  49086. }
  49087. function texStorage2D() {
  49088. try {
  49089. gl.texStorage2D( ...arguments );
  49090. } catch ( e ) {
  49091. error( 'WebGLState:', e );
  49092. }
  49093. }
  49094. function texStorage3D() {
  49095. try {
  49096. gl.texStorage3D( ...arguments );
  49097. } catch ( e ) {
  49098. error( 'WebGLState:', e );
  49099. }
  49100. }
  49101. function texImage2D() {
  49102. try {
  49103. gl.texImage2D( ...arguments );
  49104. } catch ( e ) {
  49105. error( 'WebGLState:', e );
  49106. }
  49107. }
  49108. function texImage3D() {
  49109. try {
  49110. gl.texImage3D( ...arguments );
  49111. } catch ( e ) {
  49112. error( 'WebGLState:', e );
  49113. }
  49114. }
  49115. //
  49116. function scissor( scissor ) {
  49117. if ( currentScissor.equals( scissor ) === false ) {
  49118. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  49119. currentScissor.copy( scissor );
  49120. }
  49121. }
  49122. function viewport( viewport ) {
  49123. if ( currentViewport.equals( viewport ) === false ) {
  49124. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  49125. currentViewport.copy( viewport );
  49126. }
  49127. }
  49128. function updateUBOMapping( uniformsGroup, program ) {
  49129. let mapping = uboProgramMap.get( program );
  49130. if ( mapping === undefined ) {
  49131. mapping = new WeakMap();
  49132. uboProgramMap.set( program, mapping );
  49133. }
  49134. let blockIndex = mapping.get( uniformsGroup );
  49135. if ( blockIndex === undefined ) {
  49136. blockIndex = gl.getUniformBlockIndex( program, uniformsGroup.name );
  49137. mapping.set( uniformsGroup, blockIndex );
  49138. }
  49139. }
  49140. function uniformBlockBinding( uniformsGroup, program ) {
  49141. const mapping = uboProgramMap.get( program );
  49142. const blockIndex = mapping.get( uniformsGroup );
  49143. if ( uboBindings.get( program ) !== blockIndex ) {
  49144. // bind shader specific block index to global block point
  49145. gl.uniformBlockBinding( program, blockIndex, uniformsGroup.__bindingPointIndex );
  49146. uboBindings.set( program, blockIndex );
  49147. }
  49148. }
  49149. //
  49150. function reset() {
  49151. // reset state
  49152. gl.disable( gl.BLEND );
  49153. gl.disable( gl.CULL_FACE );
  49154. gl.disable( gl.DEPTH_TEST );
  49155. gl.disable( gl.POLYGON_OFFSET_FILL );
  49156. gl.disable( gl.SCISSOR_TEST );
  49157. gl.disable( gl.STENCIL_TEST );
  49158. gl.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  49159. gl.blendEquation( gl.FUNC_ADD );
  49160. gl.blendFunc( gl.ONE, gl.ZERO );
  49161. gl.blendFuncSeparate( gl.ONE, gl.ZERO, gl.ONE, gl.ZERO );
  49162. gl.blendColor( 0, 0, 0, 0 );
  49163. gl.colorMask( true, true, true, true );
  49164. gl.clearColor( 0, 0, 0, 0 );
  49165. gl.depthMask( true );
  49166. gl.depthFunc( gl.LESS );
  49167. depthBuffer.setReversed( false );
  49168. gl.clearDepth( 1 );
  49169. gl.stencilMask( 0xffffffff );
  49170. gl.stencilFunc( gl.ALWAYS, 0, 0xffffffff );
  49171. gl.stencilOp( gl.KEEP, gl.KEEP, gl.KEEP );
  49172. gl.clearStencil( 0 );
  49173. gl.cullFace( gl.BACK );
  49174. gl.frontFace( gl.CCW );
  49175. gl.polygonOffset( 0, 0 );
  49176. gl.activeTexture( gl.TEXTURE0 );
  49177. gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  49178. gl.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  49179. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  49180. gl.useProgram( null );
  49181. gl.lineWidth( 1 );
  49182. gl.scissor( 0, 0, gl.canvas.width, gl.canvas.height );
  49183. gl.viewport( 0, 0, gl.canvas.width, gl.canvas.height );
  49184. // reset internals
  49185. enabledCapabilities = {};
  49186. currentTextureSlot = null;
  49187. currentBoundTextures = {};
  49188. currentBoundFramebuffers = {};
  49189. currentDrawbuffers = new WeakMap();
  49190. defaultDrawbuffers = [];
  49191. currentProgram = null;
  49192. currentBlendingEnabled = false;
  49193. currentBlending = null;
  49194. currentBlendEquation = null;
  49195. currentBlendSrc = null;
  49196. currentBlendDst = null;
  49197. currentBlendEquationAlpha = null;
  49198. currentBlendSrcAlpha = null;
  49199. currentBlendDstAlpha = null;
  49200. currentBlendColor = new Color( 0, 0, 0 );
  49201. currentBlendAlpha = 0;
  49202. currentPremultipledAlpha = false;
  49203. currentFlipSided = null;
  49204. currentCullFace = null;
  49205. currentLineWidth = null;
  49206. currentPolygonOffsetFactor = null;
  49207. currentPolygonOffsetUnits = null;
  49208. currentScissor.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49209. currentViewport.set( 0, 0, gl.canvas.width, gl.canvas.height );
  49210. colorBuffer.reset();
  49211. depthBuffer.reset();
  49212. stencilBuffer.reset();
  49213. }
  49214. return {
  49215. buffers: {
  49216. color: colorBuffer,
  49217. depth: depthBuffer,
  49218. stencil: stencilBuffer
  49219. },
  49220. enable: enable,
  49221. disable: disable,
  49222. bindFramebuffer: bindFramebuffer,
  49223. drawBuffers: drawBuffers,
  49224. useProgram: useProgram,
  49225. setBlending: setBlending,
  49226. setMaterial: setMaterial,
  49227. setFlipSided: setFlipSided,
  49228. setCullFace: setCullFace,
  49229. setLineWidth: setLineWidth,
  49230. setPolygonOffset: setPolygonOffset,
  49231. setScissorTest: setScissorTest,
  49232. activeTexture: activeTexture,
  49233. bindTexture: bindTexture,
  49234. unbindTexture: unbindTexture,
  49235. compressedTexImage2D: compressedTexImage2D,
  49236. compressedTexImage3D: compressedTexImage3D,
  49237. texImage2D: texImage2D,
  49238. texImage3D: texImage3D,
  49239. updateUBOMapping: updateUBOMapping,
  49240. uniformBlockBinding: uniformBlockBinding,
  49241. texStorage2D: texStorage2D,
  49242. texStorage3D: texStorage3D,
  49243. texSubImage2D: texSubImage2D,
  49244. texSubImage3D: texSubImage3D,
  49245. compressedTexSubImage2D: compressedTexSubImage2D,
  49246. compressedTexSubImage3D: compressedTexSubImage3D,
  49247. scissor: scissor,
  49248. viewport: viewport,
  49249. reset: reset
  49250. };
  49251. }
  49252. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info ) {
  49253. const multisampledRTTExt = extensions.has( 'WEBGL_multisampled_render_to_texture' ) ? extensions.get( 'WEBGL_multisampled_render_to_texture' ) : null;
  49254. const supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  49255. const _imageDimensions = new Vector2();
  49256. const _videoTextures = new WeakMap();
  49257. let _canvas;
  49258. const _sources = new WeakMap(); // maps WebglTexture objects to instances of Source
  49259. // cordova iOS (as of 5.0) still uses UIWebView, which provides OffscreenCanvas,
  49260. // also OffscreenCanvas.getContext("webgl"), but not OffscreenCanvas.getContext("2d")!
  49261. // Some implementations may only implement OffscreenCanvas partially (e.g. lacking 2d).
  49262. let useOffscreenCanvas = false;
  49263. try {
  49264. useOffscreenCanvas = typeof OffscreenCanvas !== 'undefined'
  49265. // eslint-disable-next-line compat/compat
  49266. && ( new OffscreenCanvas( 1, 1 ).getContext( '2d' ) ) !== null;
  49267. } catch ( err ) {
  49268. // Ignore any errors
  49269. }
  49270. function createCanvas( width, height ) {
  49271. // Use OffscreenCanvas when available. Specially needed in web workers
  49272. return useOffscreenCanvas ?
  49273. // eslint-disable-next-line compat/compat
  49274. new OffscreenCanvas( width, height ) : createElementNS( 'canvas' );
  49275. }
  49276. function resizeImage( image, needsNewCanvas, maxSize ) {
  49277. let scale = 1;
  49278. const dimensions = getDimensions( image );
  49279. // handle case if texture exceeds max size
  49280. if ( dimensions.width > maxSize || dimensions.height > maxSize ) {
  49281. scale = maxSize / Math.max( dimensions.width, dimensions.height );
  49282. }
  49283. // only perform resize if necessary
  49284. if ( scale < 1 ) {
  49285. // only perform resize for certain image types
  49286. if ( ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) ||
  49287. ( typeof HTMLCanvasElement !== 'undefined' && image instanceof HTMLCanvasElement ) ||
  49288. ( typeof ImageBitmap !== 'undefined' && image instanceof ImageBitmap ) ||
  49289. ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) ) {
  49290. const width = Math.floor( scale * dimensions.width );
  49291. const height = Math.floor( scale * dimensions.height );
  49292. if ( _canvas === undefined ) _canvas = createCanvas( width, height );
  49293. // cube textures can't reuse the same canvas
  49294. const canvas = needsNewCanvas ? createCanvas( width, height ) : _canvas;
  49295. canvas.width = width;
  49296. canvas.height = height;
  49297. const context = canvas.getContext( '2d' );
  49298. context.drawImage( image, 0, 0, width, height );
  49299. warn( 'WebGLRenderer: Texture has been resized from (' + dimensions.width + 'x' + dimensions.height + ') to (' + width + 'x' + height + ').' );
  49300. return canvas;
  49301. } else {
  49302. if ( 'data' in image ) {
  49303. warn( 'WebGLRenderer: Image in DataTexture is too big (' + dimensions.width + 'x' + dimensions.height + ').' );
  49304. }
  49305. return image;
  49306. }
  49307. }
  49308. return image;
  49309. }
  49310. function textureNeedsGenerateMipmaps( texture ) {
  49311. return texture.generateMipmaps;
  49312. }
  49313. function generateMipmap( target ) {
  49314. _gl.generateMipmap( target );
  49315. }
  49316. function getTargetType( texture ) {
  49317. if ( texture.isWebGLCubeRenderTarget ) return _gl.TEXTURE_CUBE_MAP;
  49318. if ( texture.isWebGL3DRenderTarget ) return _gl.TEXTURE_3D;
  49319. if ( texture.isWebGLArrayRenderTarget || texture.isCompressedArrayTexture ) return _gl.TEXTURE_2D_ARRAY;
  49320. return _gl.TEXTURE_2D;
  49321. }
  49322. function getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  49323. if ( internalFormatName !== null ) {
  49324. if ( _gl[ internalFormatName ] !== undefined ) return _gl[ internalFormatName ];
  49325. warn( 'WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  49326. }
  49327. let internalFormat = glFormat;
  49328. if ( glFormat === _gl.RED ) {
  49329. if ( glType === _gl.FLOAT ) internalFormat = _gl.R32F;
  49330. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.R16F;
  49331. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8;
  49332. }
  49333. if ( glFormat === _gl.RED_INTEGER ) {
  49334. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.R8UI;
  49335. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.R16UI;
  49336. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.R32UI;
  49337. if ( glType === _gl.BYTE ) internalFormat = _gl.R8I;
  49338. if ( glType === _gl.SHORT ) internalFormat = _gl.R16I;
  49339. if ( glType === _gl.INT ) internalFormat = _gl.R32I;
  49340. }
  49341. if ( glFormat === _gl.RG ) {
  49342. if ( glType === _gl.FLOAT ) internalFormat = _gl.RG32F;
  49343. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RG16F;
  49344. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8;
  49345. }
  49346. if ( glFormat === _gl.RG_INTEGER ) {
  49347. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RG8UI;
  49348. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RG16UI;
  49349. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RG32UI;
  49350. if ( glType === _gl.BYTE ) internalFormat = _gl.RG8I;
  49351. if ( glType === _gl.SHORT ) internalFormat = _gl.RG16I;
  49352. if ( glType === _gl.INT ) internalFormat = _gl.RG32I;
  49353. }
  49354. if ( glFormat === _gl.RGB_INTEGER ) {
  49355. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGB8UI;
  49356. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGB16UI;
  49357. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGB32UI;
  49358. if ( glType === _gl.BYTE ) internalFormat = _gl.RGB8I;
  49359. if ( glType === _gl.SHORT ) internalFormat = _gl.RGB16I;
  49360. if ( glType === _gl.INT ) internalFormat = _gl.RGB32I;
  49361. }
  49362. if ( glFormat === _gl.RGBA_INTEGER ) {
  49363. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = _gl.RGBA8UI;
  49364. if ( glType === _gl.UNSIGNED_SHORT ) internalFormat = _gl.RGBA16UI;
  49365. if ( glType === _gl.UNSIGNED_INT ) internalFormat = _gl.RGBA32UI;
  49366. if ( glType === _gl.BYTE ) internalFormat = _gl.RGBA8I;
  49367. if ( glType === _gl.SHORT ) internalFormat = _gl.RGBA16I;
  49368. if ( glType === _gl.INT ) internalFormat = _gl.RGBA32I;
  49369. }
  49370. if ( glFormat === _gl.RGB ) {
  49371. if ( glType === _gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = _gl.RGB9_E5;
  49372. if ( glType === _gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = _gl.R11F_G11F_B10F;
  49373. }
  49374. if ( glFormat === _gl.RGBA ) {
  49375. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  49376. if ( glType === _gl.FLOAT ) internalFormat = _gl.RGBA32F;
  49377. if ( glType === _gl.HALF_FLOAT ) internalFormat = _gl.RGBA16F;
  49378. if ( glType === _gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? _gl.SRGB8_ALPHA8 : _gl.RGBA8;
  49379. if ( glType === _gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = _gl.RGBA4;
  49380. if ( glType === _gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = _gl.RGB5_A1;
  49381. }
  49382. if ( internalFormat === _gl.R16F || internalFormat === _gl.R32F ||
  49383. internalFormat === _gl.RG16F || internalFormat === _gl.RG32F ||
  49384. internalFormat === _gl.RGBA16F || internalFormat === _gl.RGBA32F ) {
  49385. extensions.get( 'EXT_color_buffer_float' );
  49386. }
  49387. return internalFormat;
  49388. }
  49389. function getInternalDepthFormat( useStencil, depthType ) {
  49390. let glInternalFormat;
  49391. if ( useStencil ) {
  49392. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49393. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49394. } else if ( depthType === FloatType ) {
  49395. glInternalFormat = _gl.DEPTH32F_STENCIL8;
  49396. } else if ( depthType === UnsignedShortType ) {
  49397. glInternalFormat = _gl.DEPTH24_STENCIL8;
  49398. warn( 'DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.' );
  49399. }
  49400. } else {
  49401. if ( depthType === null || depthType === UnsignedIntType || depthType === UnsignedInt248Type ) {
  49402. glInternalFormat = _gl.DEPTH_COMPONENT24;
  49403. } else if ( depthType === FloatType ) {
  49404. glInternalFormat = _gl.DEPTH_COMPONENT32F;
  49405. } else if ( depthType === UnsignedShortType ) {
  49406. glInternalFormat = _gl.DEPTH_COMPONENT16;
  49407. }
  49408. }
  49409. return glInternalFormat;
  49410. }
  49411. function getMipLevels( texture, image ) {
  49412. if ( textureNeedsGenerateMipmaps( texture ) === true || ( texture.isFramebufferTexture && texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) ) {
  49413. return Math.log2( Math.max( image.width, image.height ) ) + 1;
  49414. } else if ( texture.mipmaps !== undefined && texture.mipmaps.length > 0 ) {
  49415. // user-defined mipmaps
  49416. return texture.mipmaps.length;
  49417. } else if ( texture.isCompressedTexture && Array.isArray( texture.image ) ) {
  49418. return image.mipmaps.length;
  49419. } else {
  49420. // texture without mipmaps (only base level)
  49421. return 1;
  49422. }
  49423. }
  49424. //
  49425. function onTextureDispose( event ) {
  49426. const texture = event.target;
  49427. texture.removeEventListener( 'dispose', onTextureDispose );
  49428. deallocateTexture( texture );
  49429. if ( texture.isVideoTexture ) {
  49430. _videoTextures.delete( texture );
  49431. }
  49432. }
  49433. function onRenderTargetDispose( event ) {
  49434. const renderTarget = event.target;
  49435. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  49436. deallocateRenderTarget( renderTarget );
  49437. }
  49438. //
  49439. function deallocateTexture( texture ) {
  49440. const textureProperties = properties.get( texture );
  49441. if ( textureProperties.__webglInit === undefined ) return;
  49442. // check if it's necessary to remove the WebGLTexture object
  49443. const source = texture.source;
  49444. const webglTextures = _sources.get( source );
  49445. if ( webglTextures ) {
  49446. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49447. webglTexture.usedTimes --;
  49448. // the WebGLTexture object is not used anymore, remove it
  49449. if ( webglTexture.usedTimes === 0 ) {
  49450. deleteTexture( texture );
  49451. }
  49452. // remove the weak map entry if no WebGLTexture uses the source anymore
  49453. if ( Object.keys( webglTextures ).length === 0 ) {
  49454. _sources.delete( source );
  49455. }
  49456. }
  49457. properties.remove( texture );
  49458. }
  49459. function deleteTexture( texture ) {
  49460. const textureProperties = properties.get( texture );
  49461. _gl.deleteTexture( textureProperties.__webglTexture );
  49462. const source = texture.source;
  49463. const webglTextures = _sources.get( source );
  49464. delete webglTextures[ textureProperties.__cacheKey ];
  49465. info.memory.textures --;
  49466. }
  49467. function deallocateRenderTarget( renderTarget ) {
  49468. const renderTargetProperties = properties.get( renderTarget );
  49469. if ( renderTarget.depthTexture ) {
  49470. renderTarget.depthTexture.dispose();
  49471. properties.remove( renderTarget.depthTexture );
  49472. }
  49473. if ( renderTarget.isWebGLCubeRenderTarget ) {
  49474. for ( let i = 0; i < 6; i ++ ) {
  49475. if ( Array.isArray( renderTargetProperties.__webglFramebuffer[ i ] ) ) {
  49476. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer[ i ].length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ][ level ] );
  49477. } else {
  49478. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  49479. }
  49480. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  49481. }
  49482. } else {
  49483. if ( Array.isArray( renderTargetProperties.__webglFramebuffer ) ) {
  49484. for ( let level = 0; level < renderTargetProperties.__webglFramebuffer.length; level ++ ) _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ level ] );
  49485. } else {
  49486. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  49487. }
  49488. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  49489. if ( renderTargetProperties.__webglMultisampledFramebuffer ) _gl.deleteFramebuffer( renderTargetProperties.__webglMultisampledFramebuffer );
  49490. if ( renderTargetProperties.__webglColorRenderbuffer ) {
  49491. for ( let i = 0; i < renderTargetProperties.__webglColorRenderbuffer.length; i ++ ) {
  49492. if ( renderTargetProperties.__webglColorRenderbuffer[ i ] ) _gl.deleteRenderbuffer( renderTargetProperties.__webglColorRenderbuffer[ i ] );
  49493. }
  49494. }
  49495. if ( renderTargetProperties.__webglDepthRenderbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthRenderbuffer );
  49496. }
  49497. const textures = renderTarget.textures;
  49498. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  49499. const attachmentProperties = properties.get( textures[ i ] );
  49500. if ( attachmentProperties.__webglTexture ) {
  49501. _gl.deleteTexture( attachmentProperties.__webglTexture );
  49502. info.memory.textures --;
  49503. }
  49504. properties.remove( textures[ i ] );
  49505. }
  49506. properties.remove( renderTarget );
  49507. }
  49508. //
  49509. let textureUnits = 0;
  49510. function resetTextureUnits() {
  49511. textureUnits = 0;
  49512. }
  49513. function allocateTextureUnit() {
  49514. const textureUnit = textureUnits;
  49515. if ( textureUnit >= capabilities.maxTextures ) {
  49516. warn( 'WebGLTextures: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  49517. }
  49518. textureUnits += 1;
  49519. return textureUnit;
  49520. }
  49521. function getTextureCacheKey( texture ) {
  49522. const array = [];
  49523. array.push( texture.wrapS );
  49524. array.push( texture.wrapT );
  49525. array.push( texture.wrapR || 0 );
  49526. array.push( texture.magFilter );
  49527. array.push( texture.minFilter );
  49528. array.push( texture.anisotropy );
  49529. array.push( texture.internalFormat );
  49530. array.push( texture.format );
  49531. array.push( texture.type );
  49532. array.push( texture.generateMipmaps );
  49533. array.push( texture.premultiplyAlpha );
  49534. array.push( texture.flipY );
  49535. array.push( texture.unpackAlignment );
  49536. array.push( texture.colorSpace );
  49537. return array.join();
  49538. }
  49539. //
  49540. function setTexture2D( texture, slot ) {
  49541. const textureProperties = properties.get( texture );
  49542. if ( texture.isVideoTexture ) updateVideoTexture( texture );
  49543. if ( texture.isRenderTargetTexture === false && texture.isExternalTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49544. const image = texture.image;
  49545. if ( image === null ) {
  49546. warn( 'WebGLRenderer: Texture marked for update but no image data found.' );
  49547. } else if ( image.complete === false ) {
  49548. warn( 'WebGLRenderer: Texture marked for update but image is incomplete' );
  49549. } else {
  49550. uploadTexture( textureProperties, texture, slot );
  49551. return;
  49552. }
  49553. } else if ( texture.isExternalTexture ) {
  49554. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49555. }
  49556. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49557. }
  49558. function setTexture2DArray( texture, slot ) {
  49559. const textureProperties = properties.get( texture );
  49560. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49561. uploadTexture( textureProperties, texture, slot );
  49562. return;
  49563. } else if ( texture.isExternalTexture ) {
  49564. textureProperties.__webglTexture = texture.sourceTexture ? texture.sourceTexture : null;
  49565. }
  49566. state.bindTexture( _gl.TEXTURE_2D_ARRAY, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49567. }
  49568. function setTexture3D( texture, slot ) {
  49569. const textureProperties = properties.get( texture );
  49570. if ( texture.isRenderTargetTexture === false && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49571. uploadTexture( textureProperties, texture, slot );
  49572. return;
  49573. }
  49574. state.bindTexture( _gl.TEXTURE_3D, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49575. }
  49576. function setTextureCube( texture, slot ) {
  49577. const textureProperties = properties.get( texture );
  49578. if ( texture.isCubeDepthTexture !== true && texture.version > 0 && textureProperties.__version !== texture.version ) {
  49579. uploadCubeTexture( textureProperties, texture, slot );
  49580. return;
  49581. }
  49582. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49583. }
  49584. const wrappingToGL = {
  49585. [ RepeatWrapping ]: _gl.REPEAT,
  49586. [ ClampToEdgeWrapping ]: _gl.CLAMP_TO_EDGE,
  49587. [ MirroredRepeatWrapping ]: _gl.MIRRORED_REPEAT
  49588. };
  49589. const filterToGL = {
  49590. [ NearestFilter ]: _gl.NEAREST,
  49591. [ NearestMipmapNearestFilter ]: _gl.NEAREST_MIPMAP_NEAREST,
  49592. [ NearestMipmapLinearFilter ]: _gl.NEAREST_MIPMAP_LINEAR,
  49593. [ LinearFilter ]: _gl.LINEAR,
  49594. [ LinearMipmapNearestFilter ]: _gl.LINEAR_MIPMAP_NEAREST,
  49595. [ LinearMipmapLinearFilter ]: _gl.LINEAR_MIPMAP_LINEAR
  49596. };
  49597. const compareToGL = {
  49598. [ NeverCompare ]: _gl.NEVER,
  49599. [ AlwaysCompare ]: _gl.ALWAYS,
  49600. [ LessCompare ]: _gl.LESS,
  49601. [ LessEqualCompare ]: _gl.LEQUAL,
  49602. [ EqualCompare ]: _gl.EQUAL,
  49603. [ GreaterEqualCompare ]: _gl.GEQUAL,
  49604. [ GreaterCompare ]: _gl.GREATER,
  49605. [ NotEqualCompare ]: _gl.NOTEQUAL
  49606. };
  49607. function setTextureParameters( textureType, texture ) {
  49608. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false &&
  49609. ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  49610. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter ) ) {
  49611. warn( 'WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.' );
  49612. }
  49613. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  49614. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  49615. if ( textureType === _gl.TEXTURE_3D || textureType === _gl.TEXTURE_2D_ARRAY ) {
  49616. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  49617. }
  49618. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  49619. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterToGL[ texture.minFilter ] );
  49620. if ( texture.compareFunction ) {
  49621. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_MODE, _gl.COMPARE_REF_TO_TEXTURE );
  49622. _gl.texParameteri( textureType, _gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  49623. }
  49624. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  49625. if ( texture.magFilter === NearestFilter ) return;
  49626. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  49627. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension
  49628. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  49629. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  49630. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  49631. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  49632. }
  49633. }
  49634. }
  49635. function initTexture( textureProperties, texture ) {
  49636. let forceUpload = false;
  49637. if ( textureProperties.__webglInit === undefined ) {
  49638. textureProperties.__webglInit = true;
  49639. texture.addEventListener( 'dispose', onTextureDispose );
  49640. }
  49641. // create Source <-> WebGLTextures mapping if necessary
  49642. const source = texture.source;
  49643. let webglTextures = _sources.get( source );
  49644. if ( webglTextures === undefined ) {
  49645. webglTextures = {};
  49646. _sources.set( source, webglTextures );
  49647. }
  49648. // check if there is already a WebGLTexture object for the given texture parameters
  49649. const textureCacheKey = getTextureCacheKey( texture );
  49650. if ( textureCacheKey !== textureProperties.__cacheKey ) {
  49651. // if not, create a new instance of WebGLTexture
  49652. if ( webglTextures[ textureCacheKey ] === undefined ) {
  49653. // create new entry
  49654. webglTextures[ textureCacheKey ] = {
  49655. texture: _gl.createTexture(),
  49656. usedTimes: 0
  49657. };
  49658. info.memory.textures ++;
  49659. // when a new instance of WebGLTexture was created, a texture upload is required
  49660. // even if the image contents are identical
  49661. forceUpload = true;
  49662. }
  49663. webglTextures[ textureCacheKey ].usedTimes ++;
  49664. // every time the texture cache key changes, it's necessary to check if an instance of
  49665. // WebGLTexture can be deleted in order to avoid a memory leak.
  49666. const webglTexture = webglTextures[ textureProperties.__cacheKey ];
  49667. if ( webglTexture !== undefined ) {
  49668. webglTextures[ textureProperties.__cacheKey ].usedTimes --;
  49669. if ( webglTexture.usedTimes === 0 ) {
  49670. deleteTexture( texture );
  49671. }
  49672. }
  49673. // store references to cache key and WebGLTexture object
  49674. textureProperties.__cacheKey = textureCacheKey;
  49675. textureProperties.__webglTexture = webglTextures[ textureCacheKey ].texture;
  49676. }
  49677. return forceUpload;
  49678. }
  49679. function getRow( index, rowLength, componentStride ) {
  49680. return Math.floor( Math.floor( index / componentStride ) / rowLength );
  49681. }
  49682. function updateTexture( texture, image, glFormat, glType ) {
  49683. const componentStride = 4; // only RGBA supported
  49684. const updateRanges = texture.updateRanges;
  49685. if ( updateRanges.length === 0 ) {
  49686. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, image.width, image.height, glFormat, glType, image.data );
  49687. } else {
  49688. // Before applying update ranges, we merge any adjacent / overlapping
  49689. // ranges to reduce load on `gl.texSubImage2D`. Empirically, this has led
  49690. // to performance improvements for applications which make heavy use of
  49691. // update ranges. Likely due to GPU command overhead.
  49692. //
  49693. // Note that to reduce garbage collection between frames, we merge the
  49694. // update ranges in-place. This is safe because this method will clear the
  49695. // update ranges once updated.
  49696. updateRanges.sort( ( a, b ) => a.start - b.start );
  49697. // To merge the update ranges in-place, we work from left to right in the
  49698. // existing updateRanges array, merging ranges. This may result in a final
  49699. // array which is smaller than the original. This index tracks the last
  49700. // index representing a merged range, any data after this index can be
  49701. // trimmed once the merge algorithm is completed.
  49702. let mergeIndex = 0;
  49703. for ( let i = 1; i < updateRanges.length; i ++ ) {
  49704. const previousRange = updateRanges[ mergeIndex ];
  49705. const range = updateRanges[ i ];
  49706. // Only merge if in the same row and overlapping/adjacent
  49707. const previousEnd = previousRange.start + previousRange.count;
  49708. const currentRow = getRow( range.start, image.width, componentStride );
  49709. const previousRow = getRow( previousRange.start, image.width, componentStride );
  49710. // We add one here to merge adjacent ranges. This is safe because ranges
  49711. // operate over positive integers.
  49712. if (
  49713. range.start <= previousEnd + 1 &&
  49714. currentRow === previousRow &&
  49715. getRow( range.start + range.count - 1, image.width, componentStride ) === currentRow // ensure range doesn't spill
  49716. ) {
  49717. previousRange.count = Math.max(
  49718. previousRange.count,
  49719. range.start + range.count - previousRange.start
  49720. );
  49721. } else {
  49722. ++ mergeIndex;
  49723. updateRanges[ mergeIndex ] = range;
  49724. }
  49725. }
  49726. // Trim the array to only contain the merged ranges.
  49727. updateRanges.length = mergeIndex + 1;
  49728. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  49729. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  49730. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  49731. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  49732. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49733. const range = updateRanges[ i ];
  49734. const pixelStart = Math.floor( range.start / componentStride );
  49735. const pixelCount = Math.ceil( range.count / componentStride );
  49736. const x = pixelStart % image.width;
  49737. const y = Math.floor( pixelStart / image.width );
  49738. // Assumes update ranges refer to contiguous memory
  49739. const width = pixelCount;
  49740. const height = 1;
  49741. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, x );
  49742. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, y );
  49743. state.texSubImage2D( _gl.TEXTURE_2D, 0, x, y, width, height, glFormat, glType, image.data );
  49744. }
  49745. texture.clearUpdateRanges();
  49746. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  49747. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  49748. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  49749. }
  49750. }
  49751. function uploadTexture( textureProperties, texture, slot ) {
  49752. let textureType = _gl.TEXTURE_2D;
  49753. if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) textureType = _gl.TEXTURE_2D_ARRAY;
  49754. if ( texture.isData3DTexture ) textureType = _gl.TEXTURE_3D;
  49755. const forceUpload = initTexture( textureProperties, texture );
  49756. const source = texture.source;
  49757. state.bindTexture( textureType, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49758. const sourceProperties = properties.get( source );
  49759. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49760. state.activeTexture( _gl.TEXTURE0 + slot );
  49761. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49762. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49763. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49764. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49765. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49766. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49767. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49768. let image = resizeImage( texture.image, false, capabilities.maxTextureSize );
  49769. image = verifyColorSpace( texture, image );
  49770. const glFormat = utils.convert( texture.format, texture.colorSpace );
  49771. const glType = utils.convert( texture.type );
  49772. let glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  49773. setTextureParameters( textureType, texture );
  49774. let mipmap;
  49775. const mipmaps = texture.mipmaps;
  49776. const useTexStorage = ( texture.isVideoTexture !== true );
  49777. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  49778. const dataReady = source.dataReady;
  49779. const levels = getMipLevels( texture, image );
  49780. if ( texture.isDepthTexture ) {
  49781. glInternalFormat = getInternalDepthFormat( texture.format === DepthStencilFormat, texture.type );
  49782. //
  49783. if ( allocateMemory ) {
  49784. if ( useTexStorage ) {
  49785. state.texStorage2D( _gl.TEXTURE_2D, 1, glInternalFormat, image.width, image.height );
  49786. } else {
  49787. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, null );
  49788. }
  49789. }
  49790. } else if ( texture.isDataTexture ) {
  49791. // use manually created mipmaps if available
  49792. // if there are no manual mipmaps
  49793. // set 0 level mipmap and then use GL to generate other mipmap levels
  49794. if ( mipmaps.length > 0 ) {
  49795. if ( useTexStorage && allocateMemory ) {
  49796. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49797. }
  49798. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49799. mipmap = mipmaps[ i ];
  49800. if ( useTexStorage ) {
  49801. if ( dataReady ) {
  49802. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49803. }
  49804. } else {
  49805. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49806. }
  49807. }
  49808. texture.generateMipmaps = false;
  49809. } else {
  49810. if ( useTexStorage ) {
  49811. if ( allocateMemory ) {
  49812. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49813. }
  49814. if ( dataReady ) {
  49815. updateTexture( texture, image, glFormat, glType );
  49816. }
  49817. } else {
  49818. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, image.width, image.height, 0, glFormat, glType, image.data );
  49819. }
  49820. }
  49821. } else if ( texture.isCompressedTexture ) {
  49822. if ( texture.isCompressedArrayTexture ) {
  49823. if ( useTexStorage && allocateMemory ) {
  49824. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height, image.depth );
  49825. }
  49826. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49827. mipmap = mipmaps[ i ];
  49828. if ( texture.format !== RGBAFormat ) {
  49829. if ( glFormat !== null ) {
  49830. if ( useTexStorage ) {
  49831. if ( dataReady ) {
  49832. if ( texture.layerUpdates.size > 0 ) {
  49833. const layerByteLength = getByteLength( mipmap.width, mipmap.height, texture.format, texture.type );
  49834. for ( const layerIndex of texture.layerUpdates ) {
  49835. const layerData = mipmap.data.subarray(
  49836. layerIndex * layerByteLength / mipmap.data.BYTES_PER_ELEMENT,
  49837. ( layerIndex + 1 ) * layerByteLength / mipmap.data.BYTES_PER_ELEMENT
  49838. );
  49839. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, layerIndex, mipmap.width, mipmap.height, 1, glFormat, layerData );
  49840. }
  49841. texture.clearLayerUpdates();
  49842. } else {
  49843. state.compressedTexSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  49844. }
  49845. }
  49846. } else {
  49847. state.compressedTexImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, mipmap.data, 0, 0 );
  49848. }
  49849. } else {
  49850. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49851. }
  49852. } else {
  49853. if ( useTexStorage ) {
  49854. if ( dataReady ) {
  49855. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  49856. }
  49857. } else {
  49858. state.texImage3D( _gl.TEXTURE_2D_ARRAY, i, glInternalFormat, mipmap.width, mipmap.height, image.depth, 0, glFormat, glType, mipmap.data );
  49859. }
  49860. }
  49861. }
  49862. } else {
  49863. if ( useTexStorage && allocateMemory ) {
  49864. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, mipmaps[ 0 ].width, mipmaps[ 0 ].height );
  49865. }
  49866. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49867. mipmap = mipmaps[ i ];
  49868. if ( texture.format !== RGBAFormat ) {
  49869. if ( glFormat !== null ) {
  49870. if ( useTexStorage ) {
  49871. if ( dataReady ) {
  49872. state.compressedTexSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  49873. }
  49874. } else {
  49875. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  49876. }
  49877. } else {
  49878. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  49879. }
  49880. } else {
  49881. if ( useTexStorage ) {
  49882. if ( dataReady ) {
  49883. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  49884. }
  49885. } else {
  49886. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  49887. }
  49888. }
  49889. }
  49890. }
  49891. } else if ( texture.isDataArrayTexture ) {
  49892. if ( useTexStorage ) {
  49893. if ( allocateMemory ) {
  49894. state.texStorage3D( _gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, image.width, image.height, image.depth );
  49895. }
  49896. if ( dataReady ) {
  49897. if ( texture.layerUpdates.size > 0 ) {
  49898. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  49899. for ( const layerIndex of texture.layerUpdates ) {
  49900. const layerData = image.data.subarray(
  49901. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  49902. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  49903. );
  49904. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  49905. }
  49906. texture.clearLayerUpdates();
  49907. } else {
  49908. state.texSubImage3D( _gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49909. }
  49910. }
  49911. } else {
  49912. state.texImage3D( _gl.TEXTURE_2D_ARRAY, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49913. }
  49914. } else if ( texture.isData3DTexture ) {
  49915. if ( useTexStorage ) {
  49916. if ( allocateMemory ) {
  49917. state.texStorage3D( _gl.TEXTURE_3D, levels, glInternalFormat, image.width, image.height, image.depth );
  49918. }
  49919. if ( dataReady ) {
  49920. state.texSubImage3D( _gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  49921. }
  49922. } else {
  49923. state.texImage3D( _gl.TEXTURE_3D, 0, glInternalFormat, image.width, image.height, image.depth, 0, glFormat, glType, image.data );
  49924. }
  49925. } else if ( texture.isFramebufferTexture ) {
  49926. if ( allocateMemory ) {
  49927. if ( useTexStorage ) {
  49928. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, image.width, image.height );
  49929. } else {
  49930. let width = image.width, height = image.height;
  49931. for ( let i = 0; i < levels; i ++ ) {
  49932. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, width, height, 0, glFormat, glType, null );
  49933. width >>= 1;
  49934. height >>= 1;
  49935. }
  49936. }
  49937. }
  49938. } else {
  49939. // regular Texture (image, video, canvas)
  49940. // use manually created mipmaps if available
  49941. // if there are no manual mipmaps
  49942. // set 0 level mipmap and then use GL to generate other mipmap levels
  49943. if ( mipmaps.length > 0 ) {
  49944. if ( useTexStorage && allocateMemory ) {
  49945. const dimensions = getDimensions( mipmaps[ 0 ] );
  49946. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49947. }
  49948. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  49949. mipmap = mipmaps[ i ];
  49950. if ( useTexStorage ) {
  49951. if ( dataReady ) {
  49952. state.texSubImage2D( _gl.TEXTURE_2D, i, 0, 0, glFormat, glType, mipmap );
  49953. }
  49954. } else {
  49955. state.texImage2D( _gl.TEXTURE_2D, i, glInternalFormat, glFormat, glType, mipmap );
  49956. }
  49957. }
  49958. texture.generateMipmaps = false;
  49959. } else {
  49960. if ( useTexStorage ) {
  49961. if ( allocateMemory ) {
  49962. const dimensions = getDimensions( image );
  49963. state.texStorage2D( _gl.TEXTURE_2D, levels, glInternalFormat, dimensions.width, dimensions.height );
  49964. }
  49965. if ( dataReady ) {
  49966. state.texSubImage2D( _gl.TEXTURE_2D, 0, 0, 0, glFormat, glType, image );
  49967. }
  49968. } else {
  49969. state.texImage2D( _gl.TEXTURE_2D, 0, glInternalFormat, glFormat, glType, image );
  49970. }
  49971. }
  49972. }
  49973. if ( textureNeedsGenerateMipmaps( texture ) ) {
  49974. generateMipmap( textureType );
  49975. }
  49976. sourceProperties.__version = source.version;
  49977. if ( texture.onUpdate ) texture.onUpdate( texture );
  49978. }
  49979. textureProperties.__version = texture.version;
  49980. }
  49981. function uploadCubeTexture( textureProperties, texture, slot ) {
  49982. if ( texture.image.length !== 6 ) return;
  49983. const forceUpload = initTexture( textureProperties, texture );
  49984. const source = texture.source;
  49985. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture, _gl.TEXTURE0 + slot );
  49986. const sourceProperties = properties.get( source );
  49987. if ( source.version !== sourceProperties.__version || forceUpload === true ) {
  49988. state.activeTexture( _gl.TEXTURE0 + slot );
  49989. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  49990. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  49991. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? _gl.NONE : _gl.BROWSER_DEFAULT_WEBGL;
  49992. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  49993. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  49994. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  49995. _gl.pixelStorei( _gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  49996. const isCompressed = ( texture.isCompressedTexture || texture.image[ 0 ].isCompressedTexture );
  49997. const isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  49998. const cubeImage = [];
  49999. for ( let i = 0; i < 6; i ++ ) {
  50000. if ( ! isCompressed && ! isDataTexture ) {
  50001. cubeImage[ i ] = resizeImage( texture.image[ i ], true, capabilities.maxCubemapSize );
  50002. } else {
  50003. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  50004. }
  50005. cubeImage[ i ] = verifyColorSpace( texture, cubeImage[ i ] );
  50006. }
  50007. const image = cubeImage[ 0 ],
  50008. glFormat = utils.convert( texture.format, texture.colorSpace ),
  50009. glType = utils.convert( texture.type ),
  50010. glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50011. const useTexStorage = ( texture.isVideoTexture !== true );
  50012. const allocateMemory = ( sourceProperties.__version === undefined ) || ( forceUpload === true );
  50013. const dataReady = source.dataReady;
  50014. let levels = getMipLevels( texture, image );
  50015. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50016. let mipmaps;
  50017. if ( isCompressed ) {
  50018. if ( useTexStorage && allocateMemory ) {
  50019. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, image.width, image.height );
  50020. }
  50021. for ( let i = 0; i < 6; i ++ ) {
  50022. mipmaps = cubeImage[ i ].mipmaps;
  50023. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50024. const mipmap = mipmaps[ j ];
  50025. if ( texture.format !== RGBAFormat ) {
  50026. if ( glFormat !== null ) {
  50027. if ( useTexStorage ) {
  50028. if ( dataReady ) {
  50029. state.compressedTexSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  50030. }
  50031. } else {
  50032. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  50033. }
  50034. } else {
  50035. warn( 'WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  50036. }
  50037. } else {
  50038. if ( useTexStorage ) {
  50039. if ( dataReady ) {
  50040. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, 0, 0, mipmap.width, mipmap.height, glFormat, glType, mipmap.data );
  50041. }
  50042. } else {
  50043. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glInternalFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  50044. }
  50045. }
  50046. }
  50047. }
  50048. } else {
  50049. mipmaps = texture.mipmaps;
  50050. if ( useTexStorage && allocateMemory ) {
  50051. // TODO: Uniformly handle mipmap definitions
  50052. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  50053. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  50054. if ( mipmaps.length > 0 ) levels ++;
  50055. const dimensions = getDimensions( cubeImage[ 0 ] );
  50056. state.texStorage2D( _gl.TEXTURE_CUBE_MAP, levels, glInternalFormat, dimensions.width, dimensions.height );
  50057. }
  50058. for ( let i = 0; i < 6; i ++ ) {
  50059. if ( isDataTexture ) {
  50060. if ( useTexStorage ) {
  50061. if ( dataReady ) {
  50062. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, cubeImage[ i ].width, cubeImage[ i ].height, glFormat, glType, cubeImage[ i ].data );
  50063. }
  50064. } else {
  50065. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  50066. }
  50067. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50068. const mipmap = mipmaps[ j ];
  50069. const mipmapImage = mipmap.image[ i ].image;
  50070. if ( useTexStorage ) {
  50071. if ( dataReady ) {
  50072. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, mipmapImage.width, mipmapImage.height, glFormat, glType, mipmapImage.data );
  50073. }
  50074. } else {
  50075. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, mipmapImage.width, mipmapImage.height, 0, glFormat, glType, mipmapImage.data );
  50076. }
  50077. }
  50078. } else {
  50079. if ( useTexStorage ) {
  50080. if ( dataReady ) {
  50081. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, glFormat, glType, cubeImage[ i ] );
  50082. }
  50083. } else {
  50084. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, glFormat, glType, cubeImage[ i ] );
  50085. }
  50086. for ( let j = 0; j < mipmaps.length; j ++ ) {
  50087. const mipmap = mipmaps[ j ];
  50088. if ( useTexStorage ) {
  50089. if ( dataReady ) {
  50090. state.texSubImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, glFormat, glType, mipmap.image[ i ] );
  50091. }
  50092. } else {
  50093. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, glInternalFormat, glFormat, glType, mipmap.image[ i ] );
  50094. }
  50095. }
  50096. }
  50097. }
  50098. }
  50099. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50100. // We assume images for cube map have the same size.
  50101. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50102. }
  50103. sourceProperties.__version = source.version;
  50104. if ( texture.onUpdate ) texture.onUpdate( texture );
  50105. }
  50106. textureProperties.__version = texture.version;
  50107. }
  50108. // Render targets
  50109. // Setup storage for target texture and bind it to correct framebuffer
  50110. function setupFrameBufferTexture( framebuffer, renderTarget, texture, attachment, textureTarget, level ) {
  50111. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50112. const glType = utils.convert( texture.type );
  50113. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50114. const renderTargetProperties = properties.get( renderTarget );
  50115. const textureProperties = properties.get( texture );
  50116. textureProperties.__renderTarget = renderTarget;
  50117. if ( ! renderTargetProperties.__hasExternalTextures ) {
  50118. const width = Math.max( 1, renderTarget.width >> level );
  50119. const height = Math.max( 1, renderTarget.height >> level );
  50120. if ( textureTarget === _gl.TEXTURE_3D || textureTarget === _gl.TEXTURE_2D_ARRAY ) {
  50121. state.texImage3D( textureTarget, level, glInternalFormat, width, height, renderTarget.depth, 0, glFormat, glType, null );
  50122. } else {
  50123. state.texImage2D( textureTarget, level, glInternalFormat, width, height, 0, glFormat, glType, null );
  50124. }
  50125. }
  50126. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50127. if ( useMultisampledRTT( renderTarget ) ) {
  50128. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, 0, getRenderTargetSamples( renderTarget ) );
  50129. } else if ( textureTarget === _gl.TEXTURE_2D || ( textureTarget >= _gl.TEXTURE_CUBE_MAP_POSITIVE_X && textureTarget <= _gl.TEXTURE_CUBE_MAP_NEGATIVE_Z ) ) { // see #24753
  50130. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, textureProperties.__webglTexture, level );
  50131. }
  50132. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50133. }
  50134. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  50135. function setupRenderBufferStorage( renderbuffer, renderTarget, isMultisample ) {
  50136. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50137. if ( renderTarget.depthBuffer ) {
  50138. // retrieve the depth attachment types
  50139. const depthTexture = renderTarget.depthTexture;
  50140. const depthType = depthTexture && depthTexture.isDepthTexture ? depthTexture.type : null;
  50141. const glInternalFormat = getInternalDepthFormat( renderTarget.stencilBuffer, depthType );
  50142. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50143. // set up the attachment
  50144. const samples = getRenderTargetSamples( renderTarget );
  50145. const isUseMultisampledRTT = useMultisampledRTT( renderTarget );
  50146. if ( isUseMultisampledRTT ) {
  50147. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50148. } else if ( isMultisample ) {
  50149. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50150. } else {
  50151. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50152. }
  50153. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50154. } else {
  50155. const textures = renderTarget.textures;
  50156. for ( let i = 0; i < textures.length; i ++ ) {
  50157. const texture = textures[ i ];
  50158. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50159. const glType = utils.convert( texture.type );
  50160. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace );
  50161. const samples = getRenderTargetSamples( renderTarget );
  50162. if ( isMultisample && useMultisampledRTT( renderTarget ) === false ) {
  50163. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50164. } else if ( useMultisampledRTT( renderTarget ) ) {
  50165. multisampledRTTExt.renderbufferStorageMultisampleEXT( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50166. } else {
  50167. _gl.renderbufferStorage( _gl.RENDERBUFFER, glInternalFormat, renderTarget.width, renderTarget.height );
  50168. }
  50169. }
  50170. }
  50171. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50172. }
  50173. // Setup resources for a Depth Texture for a FBO (needs an extension)
  50174. function setupDepthTexture( framebuffer, renderTarget, cubeFace ) {
  50175. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50176. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  50177. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  50178. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  50179. }
  50180. const textureProperties = properties.get( renderTarget.depthTexture );
  50181. textureProperties.__renderTarget = renderTarget;
  50182. // upload an empty depth texture with framebuffer size
  50183. if ( ! textureProperties.__webglTexture ||
  50184. renderTarget.depthTexture.image.width !== renderTarget.width ||
  50185. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  50186. renderTarget.depthTexture.image.width = renderTarget.width;
  50187. renderTarget.depthTexture.image.height = renderTarget.height;
  50188. renderTarget.depthTexture.needsUpdate = true;
  50189. }
  50190. if ( isCube ) {
  50191. // For cube depth textures, initialize and bind without uploading image data
  50192. if ( textureProperties.__webglInit === undefined ) {
  50193. textureProperties.__webglInit = true;
  50194. renderTarget.depthTexture.addEventListener( 'dispose', onTextureDispose );
  50195. }
  50196. // Only create and allocate storage once
  50197. if ( textureProperties.__webglTexture === undefined ) {
  50198. textureProperties.__webglTexture = _gl.createTexture();
  50199. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50200. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.depthTexture );
  50201. // Allocate storage for all 6 faces with correct depth texture format
  50202. const glFormat = utils.convert( renderTarget.depthTexture.format );
  50203. const glType = utils.convert( renderTarget.depthTexture.type );
  50204. // Use proper internal format for depth textures
  50205. let glInternalFormat;
  50206. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50207. glInternalFormat = _gl.DEPTH_COMPONENT24;
  50208. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50209. glInternalFormat = _gl.DEPTH24_STENCIL8;
  50210. }
  50211. for ( let i = 0; i < 6; i ++ ) {
  50212. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glInternalFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  50213. }
  50214. }
  50215. } else {
  50216. setTexture2D( renderTarget.depthTexture, 0 );
  50217. }
  50218. const webglDepthTexture = textureProperties.__webglTexture;
  50219. const samples = getRenderTargetSamples( renderTarget );
  50220. const glTextureType = isCube ? _gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace : _gl.TEXTURE_2D;
  50221. const glAttachmentType = renderTarget.depthTexture.format === DepthStencilFormat ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50222. if ( renderTarget.depthTexture.format === DepthFormat ) {
  50223. if ( useMultisampledRTT( renderTarget ) ) {
  50224. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50225. } else {
  50226. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50227. }
  50228. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  50229. if ( useMultisampledRTT( renderTarget ) ) {
  50230. multisampledRTTExt.framebufferTexture2DMultisampleEXT( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0, samples );
  50231. } else {
  50232. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, glAttachmentType, glTextureType, webglDepthTexture, 0 );
  50233. }
  50234. } else {
  50235. throw new Error( 'Unknown depthTexture format' );
  50236. }
  50237. }
  50238. // Setup GL resources for a non-texture depth buffer
  50239. function setupDepthRenderbuffer( renderTarget ) {
  50240. const renderTargetProperties = properties.get( renderTarget );
  50241. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50242. // if the bound depth texture has changed
  50243. if ( renderTargetProperties.__boundDepthTexture !== renderTarget.depthTexture ) {
  50244. // fire the dispose event to get rid of stored state associated with the previously bound depth buffer
  50245. const depthTexture = renderTarget.depthTexture;
  50246. if ( renderTargetProperties.__depthDisposeCallback ) {
  50247. renderTargetProperties.__depthDisposeCallback();
  50248. }
  50249. // set up dispose listeners to track when the currently attached buffer is implicitly unbound
  50250. if ( depthTexture ) {
  50251. const disposeEvent = () => {
  50252. delete renderTargetProperties.__boundDepthTexture;
  50253. delete renderTargetProperties.__depthDisposeCallback;
  50254. depthTexture.removeEventListener( 'dispose', disposeEvent );
  50255. };
  50256. depthTexture.addEventListener( 'dispose', disposeEvent );
  50257. renderTargetProperties.__depthDisposeCallback = disposeEvent;
  50258. }
  50259. renderTargetProperties.__boundDepthTexture = depthTexture;
  50260. }
  50261. if ( renderTarget.depthTexture && ! renderTargetProperties.__autoAllocateDepthBuffer ) {
  50262. if ( isCube ) {
  50263. // For cube render targets with depth texture, setup each face
  50264. for ( let i = 0; i < 6; i ++ ) {
  50265. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, i );
  50266. }
  50267. } else {
  50268. const mipmaps = renderTarget.texture.mipmaps;
  50269. if ( mipmaps && mipmaps.length > 0 ) {
  50270. setupDepthTexture( renderTargetProperties.__webglFramebuffer[ 0 ], renderTarget, 0 );
  50271. } else {
  50272. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget, 0 );
  50273. }
  50274. }
  50275. } else {
  50276. if ( isCube ) {
  50277. renderTargetProperties.__webglDepthbuffer = [];
  50278. for ( let i = 0; i < 6; i ++ ) {
  50279. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  50280. if ( renderTargetProperties.__webglDepthbuffer[ i ] === undefined ) {
  50281. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  50282. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget, false );
  50283. } else {
  50284. // attach buffer if it's been created already
  50285. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50286. const renderbuffer = renderTargetProperties.__webglDepthbuffer[ i ];
  50287. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50288. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50289. }
  50290. }
  50291. } else {
  50292. const mipmaps = renderTarget.texture.mipmaps;
  50293. if ( mipmaps && mipmaps.length > 0 ) {
  50294. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50295. } else {
  50296. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50297. }
  50298. if ( renderTargetProperties.__webglDepthbuffer === undefined ) {
  50299. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  50300. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget, false );
  50301. } else {
  50302. // attach buffer if it's been created already
  50303. const glAttachmentType = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50304. const renderbuffer = renderTargetProperties.__webglDepthbuffer;
  50305. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  50306. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, glAttachmentType, _gl.RENDERBUFFER, renderbuffer );
  50307. }
  50308. }
  50309. }
  50310. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50311. }
  50312. // rebind framebuffer with external textures
  50313. function rebindTextures( renderTarget, colorTexture, depthTexture ) {
  50314. const renderTargetProperties = properties.get( renderTarget );
  50315. if ( colorTexture !== undefined ) {
  50316. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, renderTarget.texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, 0 );
  50317. }
  50318. if ( depthTexture !== undefined ) {
  50319. setupDepthRenderbuffer( renderTarget );
  50320. }
  50321. }
  50322. // Set up GL resources for the render target
  50323. function setupRenderTarget( renderTarget ) {
  50324. const texture = renderTarget.texture;
  50325. const renderTargetProperties = properties.get( renderTarget );
  50326. const textureProperties = properties.get( texture );
  50327. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  50328. const textures = renderTarget.textures;
  50329. const isCube = ( renderTarget.isWebGLCubeRenderTarget === true );
  50330. const isMultipleRenderTargets = ( textures.length > 1 );
  50331. if ( ! isMultipleRenderTargets ) {
  50332. if ( textureProperties.__webglTexture === undefined ) {
  50333. textureProperties.__webglTexture = _gl.createTexture();
  50334. }
  50335. textureProperties.__version = texture.version;
  50336. info.memory.textures ++;
  50337. }
  50338. // Setup framebuffer
  50339. if ( isCube ) {
  50340. renderTargetProperties.__webglFramebuffer = [];
  50341. for ( let i = 0; i < 6; i ++ ) {
  50342. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50343. renderTargetProperties.__webglFramebuffer[ i ] = [];
  50344. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50345. renderTargetProperties.__webglFramebuffer[ i ][ level ] = _gl.createFramebuffer();
  50346. }
  50347. } else {
  50348. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  50349. }
  50350. }
  50351. } else {
  50352. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50353. renderTargetProperties.__webglFramebuffer = [];
  50354. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50355. renderTargetProperties.__webglFramebuffer[ level ] = _gl.createFramebuffer();
  50356. }
  50357. } else {
  50358. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  50359. }
  50360. if ( isMultipleRenderTargets ) {
  50361. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50362. const attachmentProperties = properties.get( textures[ i ] );
  50363. if ( attachmentProperties.__webglTexture === undefined ) {
  50364. attachmentProperties.__webglTexture = _gl.createTexture();
  50365. info.memory.textures ++;
  50366. }
  50367. }
  50368. }
  50369. if ( ( renderTarget.samples > 0 ) && useMultisampledRTT( renderTarget ) === false ) {
  50370. renderTargetProperties.__webglMultisampledFramebuffer = _gl.createFramebuffer();
  50371. renderTargetProperties.__webglColorRenderbuffer = [];
  50372. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50373. for ( let i = 0; i < textures.length; i ++ ) {
  50374. const texture = textures[ i ];
  50375. renderTargetProperties.__webglColorRenderbuffer[ i ] = _gl.createRenderbuffer();
  50376. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50377. const glFormat = utils.convert( texture.format, texture.colorSpace );
  50378. const glType = utils.convert( texture.type );
  50379. const glInternalFormat = getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, renderTarget.isXRRenderTarget === true );
  50380. const samples = getRenderTargetSamples( renderTarget );
  50381. _gl.renderbufferStorageMultisample( _gl.RENDERBUFFER, samples, glInternalFormat, renderTarget.width, renderTarget.height );
  50382. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50383. }
  50384. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  50385. if ( renderTarget.depthBuffer ) {
  50386. renderTargetProperties.__webglDepthRenderbuffer = _gl.createRenderbuffer();
  50387. setupRenderBufferStorage( renderTargetProperties.__webglDepthRenderbuffer, renderTarget, true );
  50388. }
  50389. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  50390. }
  50391. }
  50392. // Setup color buffer
  50393. if ( isCube ) {
  50394. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  50395. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture );
  50396. for ( let i = 0; i < 6; i ++ ) {
  50397. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50398. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50399. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ][ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level );
  50400. }
  50401. } else {
  50402. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0 );
  50403. }
  50404. }
  50405. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50406. generateMipmap( _gl.TEXTURE_CUBE_MAP );
  50407. }
  50408. state.unbindTexture();
  50409. } else if ( isMultipleRenderTargets ) {
  50410. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50411. const attachment = textures[ i ];
  50412. const attachmentProperties = properties.get( attachment );
  50413. let glTextureType = _gl.TEXTURE_2D;
  50414. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50415. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50416. }
  50417. state.bindTexture( glTextureType, attachmentProperties.__webglTexture );
  50418. setTextureParameters( glTextureType, attachment );
  50419. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, attachment, _gl.COLOR_ATTACHMENT0 + i, glTextureType, 0 );
  50420. if ( textureNeedsGenerateMipmaps( attachment ) ) {
  50421. generateMipmap( glTextureType );
  50422. }
  50423. }
  50424. state.unbindTexture();
  50425. } else {
  50426. let glTextureType = _gl.TEXTURE_2D;
  50427. if ( renderTarget.isWebGL3DRenderTarget || renderTarget.isWebGLArrayRenderTarget ) {
  50428. glTextureType = renderTarget.isWebGL3DRenderTarget ? _gl.TEXTURE_3D : _gl.TEXTURE_2D_ARRAY;
  50429. }
  50430. state.bindTexture( glTextureType, textureProperties.__webglTexture );
  50431. setTextureParameters( glTextureType, texture );
  50432. if ( texture.mipmaps && texture.mipmaps.length > 0 ) {
  50433. for ( let level = 0; level < texture.mipmaps.length; level ++ ) {
  50434. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ level ], renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, level );
  50435. }
  50436. } else {
  50437. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, texture, _gl.COLOR_ATTACHMENT0, glTextureType, 0 );
  50438. }
  50439. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50440. generateMipmap( glTextureType );
  50441. }
  50442. state.unbindTexture();
  50443. }
  50444. // Setup depth and stencil buffers
  50445. if ( renderTarget.depthBuffer ) {
  50446. setupDepthRenderbuffer( renderTarget );
  50447. }
  50448. }
  50449. function updateRenderTargetMipmap( renderTarget ) {
  50450. const textures = renderTarget.textures;
  50451. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  50452. const texture = textures[ i ];
  50453. if ( textureNeedsGenerateMipmaps( texture ) ) {
  50454. const targetType = getTargetType( renderTarget );
  50455. const webglTexture = properties.get( texture ).__webglTexture;
  50456. state.bindTexture( targetType, webglTexture );
  50457. generateMipmap( targetType );
  50458. state.unbindTexture();
  50459. }
  50460. }
  50461. }
  50462. const invalidationArrayRead = [];
  50463. const invalidationArrayDraw = [];
  50464. function updateMultisampleRenderTarget( renderTarget ) {
  50465. if ( renderTarget.samples > 0 ) {
  50466. if ( useMultisampledRTT( renderTarget ) === false ) {
  50467. const textures = renderTarget.textures;
  50468. const width = renderTarget.width;
  50469. const height = renderTarget.height;
  50470. let mask = _gl.COLOR_BUFFER_BIT;
  50471. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50472. const renderTargetProperties = properties.get( renderTarget );
  50473. const isMultipleRenderTargets = ( textures.length > 1 );
  50474. // If MRT we need to remove FBO attachments
  50475. if ( isMultipleRenderTargets ) {
  50476. for ( let i = 0; i < textures.length; i ++ ) {
  50477. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50478. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, null );
  50479. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50480. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, null, 0 );
  50481. }
  50482. }
  50483. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50484. const mipmaps = renderTarget.texture.mipmaps;
  50485. if ( mipmaps && mipmaps.length > 0 ) {
  50486. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ 0 ] );
  50487. } else {
  50488. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50489. }
  50490. for ( let i = 0; i < textures.length; i ++ ) {
  50491. if ( renderTarget.resolveDepthBuffer ) {
  50492. if ( renderTarget.depthBuffer ) mask |= _gl.DEPTH_BUFFER_BIT;
  50493. // resolving stencil is slow with a D3D backend. disable it for all transmission render targets (see #27799)
  50494. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= _gl.STENCIL_BUFFER_BIT;
  50495. }
  50496. if ( isMultipleRenderTargets ) {
  50497. _gl.framebufferRenderbuffer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50498. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50499. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, webglTexture, 0 );
  50500. }
  50501. _gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, _gl.NEAREST );
  50502. if ( supportsInvalidateFramebuffer === true ) {
  50503. invalidationArrayRead.length = 0;
  50504. invalidationArrayDraw.length = 0;
  50505. invalidationArrayRead.push( _gl.COLOR_ATTACHMENT0 + i );
  50506. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false ) {
  50507. invalidationArrayRead.push( depthStyle );
  50508. invalidationArrayDraw.push( depthStyle );
  50509. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, invalidationArrayDraw );
  50510. }
  50511. _gl.invalidateFramebuffer( _gl.READ_FRAMEBUFFER, invalidationArrayRead );
  50512. }
  50513. }
  50514. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  50515. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  50516. // If MRT since pre-blit we removed the FBO we need to reconstruct the attachments
  50517. if ( isMultipleRenderTargets ) {
  50518. for ( let i = 0; i < textures.length; i ++ ) {
  50519. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50520. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.RENDERBUFFER, renderTargetProperties.__webglColorRenderbuffer[ i ] );
  50521. const webglTexture = properties.get( textures[ i ] ).__webglTexture;
  50522. state.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  50523. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, webglTexture, 0 );
  50524. }
  50525. }
  50526. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, renderTargetProperties.__webglMultisampledFramebuffer );
  50527. } else {
  50528. if ( renderTarget.depthBuffer && renderTarget.resolveDepthBuffer === false && supportsInvalidateFramebuffer ) {
  50529. const depthStyle = renderTarget.stencilBuffer ? _gl.DEPTH_STENCIL_ATTACHMENT : _gl.DEPTH_ATTACHMENT;
  50530. _gl.invalidateFramebuffer( _gl.DRAW_FRAMEBUFFER, [ depthStyle ] );
  50531. }
  50532. }
  50533. }
  50534. }
  50535. function getRenderTargetSamples( renderTarget ) {
  50536. return Math.min( capabilities.maxSamples, renderTarget.samples );
  50537. }
  50538. function useMultisampledRTT( renderTarget ) {
  50539. const renderTargetProperties = properties.get( renderTarget );
  50540. return renderTarget.samples > 0 && extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTargetProperties.__useRenderToTexture !== false;
  50541. }
  50542. function updateVideoTexture( texture ) {
  50543. const frame = info.render.frame;
  50544. // Check the last frame we updated the VideoTexture
  50545. if ( _videoTextures.get( texture ) !== frame ) {
  50546. _videoTextures.set( texture, frame );
  50547. texture.update();
  50548. }
  50549. }
  50550. function verifyColorSpace( texture, image ) {
  50551. const colorSpace = texture.colorSpace;
  50552. const format = texture.format;
  50553. const type = texture.type;
  50554. if ( texture.isCompressedTexture === true || texture.isVideoTexture === true ) return image;
  50555. if ( colorSpace !== LinearSRGBColorSpace && colorSpace !== NoColorSpace ) {
  50556. // sRGB
  50557. if ( ColorManagement.getTransfer( colorSpace ) === SRGBTransfer ) {
  50558. // in WebGL 2 uncompressed textures can only be sRGB encoded if they have the RGBA8 format
  50559. if ( format !== RGBAFormat || type !== UnsignedByteType ) {
  50560. warn( 'WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.' );
  50561. }
  50562. } else {
  50563. error( 'WebGLTextures: Unsupported texture color space:', colorSpace );
  50564. }
  50565. }
  50566. return image;
  50567. }
  50568. function getDimensions( image ) {
  50569. if ( typeof HTMLImageElement !== 'undefined' && image instanceof HTMLImageElement ) {
  50570. // if intrinsic data are not available, fallback to width/height
  50571. _imageDimensions.width = image.naturalWidth || image.width;
  50572. _imageDimensions.height = image.naturalHeight || image.height;
  50573. } else if ( typeof VideoFrame !== 'undefined' && image instanceof VideoFrame ) {
  50574. _imageDimensions.width = image.displayWidth;
  50575. _imageDimensions.height = image.displayHeight;
  50576. } else {
  50577. _imageDimensions.width = image.width;
  50578. _imageDimensions.height = image.height;
  50579. }
  50580. return _imageDimensions;
  50581. }
  50582. //
  50583. this.allocateTextureUnit = allocateTextureUnit;
  50584. this.resetTextureUnits = resetTextureUnits;
  50585. this.setTexture2D = setTexture2D;
  50586. this.setTexture2DArray = setTexture2DArray;
  50587. this.setTexture3D = setTexture3D;
  50588. this.setTextureCube = setTextureCube;
  50589. this.rebindTextures = rebindTextures;
  50590. this.setupRenderTarget = setupRenderTarget;
  50591. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  50592. this.updateMultisampleRenderTarget = updateMultisampleRenderTarget;
  50593. this.setupDepthRenderbuffer = setupDepthRenderbuffer;
  50594. this.setupFrameBufferTexture = setupFrameBufferTexture;
  50595. this.useMultisampledRTT = useMultisampledRTT;
  50596. this.isReversedDepthBuffer = function () {
  50597. return state.buffers.depth.getReversed();
  50598. };
  50599. }
  50600. function WebGLUtils( gl, extensions ) {
  50601. function convert( p, colorSpace = NoColorSpace ) {
  50602. let extension;
  50603. const transfer = ColorManagement.getTransfer( colorSpace );
  50604. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  50605. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  50606. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  50607. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  50608. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  50609. if ( p === ByteType ) return gl.BYTE;
  50610. if ( p === ShortType ) return gl.SHORT;
  50611. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  50612. if ( p === IntType ) return gl.INT;
  50613. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  50614. if ( p === FloatType ) return gl.FLOAT;
  50615. if ( p === HalfFloatType ) return gl.HALF_FLOAT;
  50616. if ( p === AlphaFormat ) return gl.ALPHA;
  50617. if ( p === RGBFormat ) return gl.RGB;
  50618. if ( p === RGBAFormat ) return gl.RGBA;
  50619. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  50620. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  50621. // WebGL2 formats.
  50622. if ( p === RedFormat ) return gl.RED;
  50623. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  50624. if ( p === RGFormat ) return gl.RG;
  50625. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  50626. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  50627. // S3TC
  50628. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  50629. if ( transfer === SRGBTransfer ) {
  50630. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  50631. if ( extension !== null ) {
  50632. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  50633. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  50634. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  50635. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  50636. } else {
  50637. return null;
  50638. }
  50639. } else {
  50640. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  50641. if ( extension !== null ) {
  50642. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  50643. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  50644. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  50645. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  50646. } else {
  50647. return null;
  50648. }
  50649. }
  50650. }
  50651. // PVRTC
  50652. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  50653. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  50654. if ( extension !== null ) {
  50655. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  50656. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  50657. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  50658. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  50659. } else {
  50660. return null;
  50661. }
  50662. }
  50663. // ETC
  50664. 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 ) {
  50665. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  50666. if ( extension !== null ) {
  50667. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  50668. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  50669. if ( p === R11_EAC_Format ) return extension.COMPRESSED_R11_EAC;
  50670. if ( p === SIGNED_R11_EAC_Format ) return extension.COMPRESSED_SIGNED_R11_EAC;
  50671. if ( p === RG11_EAC_Format ) return extension.COMPRESSED_RG11_EAC;
  50672. if ( p === SIGNED_RG11_EAC_Format ) return extension.COMPRESSED_SIGNED_RG11_EAC;
  50673. } else {
  50674. return null;
  50675. }
  50676. }
  50677. // ASTC
  50678. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  50679. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  50680. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  50681. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  50682. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  50683. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  50684. if ( extension !== null ) {
  50685. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  50686. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  50687. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  50688. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  50689. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  50690. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  50691. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  50692. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  50693. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  50694. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  50695. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  50696. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  50697. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  50698. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  50699. } else {
  50700. return null;
  50701. }
  50702. }
  50703. // BPTC
  50704. if ( p === RGBA_BPTC_Format || p === RGB_BPTC_SIGNED_Format || p === RGB_BPTC_UNSIGNED_Format ) {
  50705. extension = extensions.get( 'EXT_texture_compression_bptc' );
  50706. if ( extension !== null ) {
  50707. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  50708. if ( p === RGB_BPTC_SIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;
  50709. if ( p === RGB_BPTC_UNSIGNED_Format ) return extension.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT;
  50710. } else {
  50711. return null;
  50712. }
  50713. }
  50714. // RGTC
  50715. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  50716. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  50717. if ( extension !== null ) {
  50718. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  50719. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  50720. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  50721. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  50722. } else {
  50723. return null;
  50724. }
  50725. }
  50726. //
  50727. if ( p === UnsignedInt248Type ) return gl.UNSIGNED_INT_24_8;
  50728. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  50729. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  50730. }
  50731. return { convert: convert };
  50732. }
  50733. const _occlusion_vertex = `
  50734. void main() {
  50735. gl_Position = vec4( position, 1.0 );
  50736. }`;
  50737. const _occlusion_fragment = `
  50738. uniform sampler2DArray depthColor;
  50739. uniform float depthWidth;
  50740. uniform float depthHeight;
  50741. void main() {
  50742. vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight );
  50743. if ( coord.x >= 1.0 ) {
  50744. gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r;
  50745. } else {
  50746. gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r;
  50747. }
  50748. }`;
  50749. /**
  50750. * A XR module that manages the access to the Depth Sensing API.
  50751. */
  50752. class WebXRDepthSensing {
  50753. /**
  50754. * Constructs a new depth sensing module.
  50755. */
  50756. constructor() {
  50757. /**
  50758. * An opaque texture representing the depth of the user's environment.
  50759. *
  50760. * @type {?ExternalTexture}
  50761. */
  50762. this.texture = null;
  50763. /**
  50764. * A plane mesh for visualizing the depth texture.
  50765. *
  50766. * @type {?Mesh}
  50767. */
  50768. this.mesh = null;
  50769. /**
  50770. * The depth near value.
  50771. *
  50772. * @type {number}
  50773. */
  50774. this.depthNear = 0;
  50775. /**
  50776. * The depth near far.
  50777. *
  50778. * @type {number}
  50779. */
  50780. this.depthFar = 0;
  50781. }
  50782. /**
  50783. * Inits the depth sensing module
  50784. *
  50785. * @param {XRWebGLDepthInformation} depthData - The XR depth data.
  50786. * @param {XRRenderState} renderState - The XR render state.
  50787. */
  50788. init( depthData, renderState ) {
  50789. if ( this.texture === null ) {
  50790. const texture = new ExternalTexture( depthData.texture );
  50791. if ( ( depthData.depthNear !== renderState.depthNear ) || ( depthData.depthFar !== renderState.depthFar ) ) {
  50792. this.depthNear = depthData.depthNear;
  50793. this.depthFar = depthData.depthFar;
  50794. }
  50795. this.texture = texture;
  50796. }
  50797. }
  50798. /**
  50799. * Returns a plane mesh that visualizes the depth texture.
  50800. *
  50801. * @param {ArrayCamera} cameraXR - The XR camera.
  50802. * @return {?Mesh} The plane mesh.
  50803. */
  50804. getMesh( cameraXR ) {
  50805. if ( this.texture !== null ) {
  50806. if ( this.mesh === null ) {
  50807. const viewport = cameraXR.cameras[ 0 ].viewport;
  50808. const material = new ShaderMaterial( {
  50809. vertexShader: _occlusion_vertex,
  50810. fragmentShader: _occlusion_fragment,
  50811. uniforms: {
  50812. depthColor: { value: this.texture },
  50813. depthWidth: { value: viewport.z },
  50814. depthHeight: { value: viewport.w }
  50815. }
  50816. } );
  50817. this.mesh = new Mesh( new PlaneGeometry( 20, 20 ), material );
  50818. }
  50819. }
  50820. return this.mesh;
  50821. }
  50822. /**
  50823. * Resets the module
  50824. */
  50825. reset() {
  50826. this.texture = null;
  50827. this.mesh = null;
  50828. }
  50829. /**
  50830. * Returns a texture representing the depth of the user's environment.
  50831. *
  50832. * @return {?ExternalTexture} The depth texture.
  50833. */
  50834. getDepthTexture() {
  50835. return this.texture;
  50836. }
  50837. }
  50838. /**
  50839. * This class represents an abstraction of the WebXR Device API and is
  50840. * internally used by {@link WebGLRenderer}. `WebXRManager` also provides a public
  50841. * interface that allows users to enable/disable XR and perform XR related
  50842. * tasks like for instance retrieving controllers.
  50843. *
  50844. * @augments EventDispatcher
  50845. * @hideconstructor
  50846. */
  50847. class WebXRManager extends EventDispatcher {
  50848. /**
  50849. * Constructs a new WebGL renderer.
  50850. *
  50851. * @param {WebGLRenderer} renderer - The renderer.
  50852. * @param {WebGL2RenderingContext} gl - The rendering context.
  50853. */
  50854. constructor( renderer, gl ) {
  50855. super();
  50856. const scope = this;
  50857. let session = null;
  50858. let framebufferScaleFactor = 1.0;
  50859. let referenceSpace = null;
  50860. let referenceSpaceType = 'local-floor';
  50861. // Set default foveation to maximum.
  50862. let foveation = 1.0;
  50863. let customReferenceSpace = null;
  50864. let pose = null;
  50865. let glBinding = null;
  50866. let glProjLayer = null;
  50867. let glBaseLayer = null;
  50868. let xrFrame = null;
  50869. const supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  50870. const depthSensing = new WebXRDepthSensing();
  50871. const cameraAccessTextures = {};
  50872. const attributes = gl.getContextAttributes();
  50873. let initialRenderTarget = null;
  50874. let newRenderTarget = null;
  50875. const controllers = [];
  50876. const controllerInputSources = [];
  50877. const currentSize = new Vector2();
  50878. let currentPixelRatio = null;
  50879. //
  50880. const cameraL = new PerspectiveCamera();
  50881. cameraL.viewport = new Vector4();
  50882. const cameraR = new PerspectiveCamera();
  50883. cameraR.viewport = new Vector4();
  50884. const cameras = [ cameraL, cameraR ];
  50885. const cameraXR = new ArrayCamera();
  50886. let _currentDepthNear = null;
  50887. let _currentDepthFar = null;
  50888. //
  50889. /**
  50890. * Whether the manager's XR camera should be automatically updated or not.
  50891. *
  50892. * @type {boolean}
  50893. * @default true
  50894. */
  50895. this.cameraAutoUpdate = true;
  50896. /**
  50897. * This flag notifies the renderer to be ready for XR rendering. Set it to `true`
  50898. * if you are going to use XR in your app.
  50899. *
  50900. * @type {boolean}
  50901. * @default false
  50902. */
  50903. this.enabled = false;
  50904. /**
  50905. * Whether XR presentation is active or not.
  50906. *
  50907. * @type {boolean}
  50908. * @readonly
  50909. * @default false
  50910. */
  50911. this.isPresenting = false;
  50912. /**
  50913. * Returns a group representing the `target ray` space of the XR controller.
  50914. * Use this space for visualizing 3D objects that support the user in pointing
  50915. * tasks like UI interaction.
  50916. *
  50917. * @param {number} index - The index of the controller.
  50918. * @return {Group} A group representing the `target ray` space.
  50919. */
  50920. this.getController = function ( index ) {
  50921. let controller = controllers[ index ];
  50922. if ( controller === undefined ) {
  50923. controller = new WebXRController();
  50924. controllers[ index ] = controller;
  50925. }
  50926. return controller.getTargetRaySpace();
  50927. };
  50928. /**
  50929. * Returns a group representing the `grip` space of the XR controller.
  50930. * Use this space for visualizing 3D objects that support the user in pointing
  50931. * tasks like UI interaction.
  50932. *
  50933. * Note: If you want to show something in the user's hand AND offer a
  50934. * pointing ray at the same time, you'll want to attached the handheld object
  50935. * to the group returned by `getControllerGrip()` and the ray to the
  50936. * group returned by `getController()`. The idea is to have two
  50937. * different groups in two different coordinate spaces for the same WebXR
  50938. * controller.
  50939. *
  50940. * @param {number} index - The index of the controller.
  50941. * @return {Group} A group representing the `grip` space.
  50942. */
  50943. this.getControllerGrip = function ( index ) {
  50944. let controller = controllers[ index ];
  50945. if ( controller === undefined ) {
  50946. controller = new WebXRController();
  50947. controllers[ index ] = controller;
  50948. }
  50949. return controller.getGripSpace();
  50950. };
  50951. /**
  50952. * Returns a group representing the `hand` space of the XR controller.
  50953. * Use this space for visualizing 3D objects that support the user in pointing
  50954. * tasks like UI interaction.
  50955. *
  50956. * @param {number} index - The index of the controller.
  50957. * @return {Group} A group representing the `hand` space.
  50958. */
  50959. this.getHand = function ( index ) {
  50960. let controller = controllers[ index ];
  50961. if ( controller === undefined ) {
  50962. controller = new WebXRController();
  50963. controllers[ index ] = controller;
  50964. }
  50965. return controller.getHandSpace();
  50966. };
  50967. //
  50968. function onSessionEvent( event ) {
  50969. const controllerIndex = controllerInputSources.indexOf( event.inputSource );
  50970. if ( controllerIndex === -1 ) {
  50971. return;
  50972. }
  50973. const controller = controllers[ controllerIndex ];
  50974. if ( controller !== undefined ) {
  50975. controller.update( event.inputSource, event.frame, customReferenceSpace || referenceSpace );
  50976. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  50977. }
  50978. }
  50979. function onSessionEnd() {
  50980. session.removeEventListener( 'select', onSessionEvent );
  50981. session.removeEventListener( 'selectstart', onSessionEvent );
  50982. session.removeEventListener( 'selectend', onSessionEvent );
  50983. session.removeEventListener( 'squeeze', onSessionEvent );
  50984. session.removeEventListener( 'squeezestart', onSessionEvent );
  50985. session.removeEventListener( 'squeezeend', onSessionEvent );
  50986. session.removeEventListener( 'end', onSessionEnd );
  50987. session.removeEventListener( 'inputsourceschange', onInputSourcesChange );
  50988. for ( let i = 0; i < controllers.length; i ++ ) {
  50989. const inputSource = controllerInputSources[ i ];
  50990. if ( inputSource === null ) continue;
  50991. controllerInputSources[ i ] = null;
  50992. controllers[ i ].disconnect( inputSource );
  50993. }
  50994. _currentDepthNear = null;
  50995. _currentDepthFar = null;
  50996. depthSensing.reset();
  50997. for ( const key in cameraAccessTextures ) {
  50998. delete cameraAccessTextures[ key ];
  50999. }
  51000. // restore framebuffer/rendering state
  51001. renderer.setRenderTarget( initialRenderTarget );
  51002. glBaseLayer = null;
  51003. glProjLayer = null;
  51004. glBinding = null;
  51005. session = null;
  51006. newRenderTarget = null;
  51007. //
  51008. animation.stop();
  51009. scope.isPresenting = false;
  51010. renderer.setPixelRatio( currentPixelRatio );
  51011. renderer.setSize( currentSize.width, currentSize.height, false );
  51012. scope.dispatchEvent( { type: 'sessionend' } );
  51013. }
  51014. /**
  51015. * Sets the framebuffer scale factor.
  51016. *
  51017. * This method can not be used during a XR session.
  51018. *
  51019. * @param {number} value - The framebuffer scale factor.
  51020. */
  51021. this.setFramebufferScaleFactor = function ( value ) {
  51022. framebufferScaleFactor = value;
  51023. if ( scope.isPresenting === true ) {
  51024. warn( 'WebXRManager: Cannot change framebuffer scale while presenting.' );
  51025. }
  51026. };
  51027. /**
  51028. * Sets the reference space type. Can be used to configure a spatial relationship with the user's physical
  51029. * environment. Depending on how the user moves in 3D space, setting an appropriate reference space can
  51030. * improve tracking. Default is `local-floor`. Valid values can be found here
  51031. * https://developer.mozilla.org/en-US/docs/Web/API/XRReferenceSpace#reference_space_types.
  51032. *
  51033. * This method can not be used during a XR session.
  51034. *
  51035. * @param {string} value - The reference space type.
  51036. */
  51037. this.setReferenceSpaceType = function ( value ) {
  51038. referenceSpaceType = value;
  51039. if ( scope.isPresenting === true ) {
  51040. warn( 'WebXRManager: Cannot change reference space type while presenting.' );
  51041. }
  51042. };
  51043. /**
  51044. * Returns the XR reference space.
  51045. *
  51046. * @return {XRReferenceSpace} The XR reference space.
  51047. */
  51048. this.getReferenceSpace = function () {
  51049. return customReferenceSpace || referenceSpace;
  51050. };
  51051. /**
  51052. * Sets a custom XR reference space.
  51053. *
  51054. * @param {XRReferenceSpace} space - The XR reference space.
  51055. */
  51056. this.setReferenceSpace = function ( space ) {
  51057. customReferenceSpace = space;
  51058. };
  51059. /**
  51060. * Returns the current base layer.
  51061. *
  51062. * This is an `XRProjectionLayer` when the targeted XR device supports the
  51063. * WebXR Layers API, or an `XRWebGLLayer` otherwise.
  51064. *
  51065. * @return {?(XRWebGLLayer|XRProjectionLayer)} The XR base layer.
  51066. */
  51067. this.getBaseLayer = function () {
  51068. return glProjLayer !== null ? glProjLayer : glBaseLayer;
  51069. };
  51070. /**
  51071. * Returns the current XR binding.
  51072. *
  51073. * Creates a new binding if needed and the browser is
  51074. * capable of doing so.
  51075. *
  51076. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  51077. */
  51078. this.getBinding = function () {
  51079. if ( glBinding === null && supportsGlBinding ) {
  51080. glBinding = new XRWebGLBinding( session, gl );
  51081. }
  51082. return glBinding;
  51083. };
  51084. /**
  51085. * Returns the current XR frame.
  51086. *
  51087. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  51088. */
  51089. this.getFrame = function () {
  51090. return xrFrame;
  51091. };
  51092. /**
  51093. * Returns the current XR session.
  51094. *
  51095. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  51096. */
  51097. this.getSession = function () {
  51098. return session;
  51099. };
  51100. /**
  51101. * After a XR session has been requested usually with one of the `*Button` modules, it
  51102. * is injected into the renderer with this method. This method triggers the start of
  51103. * the actual XR rendering.
  51104. *
  51105. * @async
  51106. * @param {XRSession} value - The XR session to set.
  51107. * @return {Promise} A Promise that resolves when the session has been set.
  51108. */
  51109. this.setSession = async function ( value ) {
  51110. session = value;
  51111. if ( session !== null ) {
  51112. initialRenderTarget = renderer.getRenderTarget();
  51113. session.addEventListener( 'select', onSessionEvent );
  51114. session.addEventListener( 'selectstart', onSessionEvent );
  51115. session.addEventListener( 'selectend', onSessionEvent );
  51116. session.addEventListener( 'squeeze', onSessionEvent );
  51117. session.addEventListener( 'squeezestart', onSessionEvent );
  51118. session.addEventListener( 'squeezeend', onSessionEvent );
  51119. session.addEventListener( 'end', onSessionEnd );
  51120. session.addEventListener( 'inputsourceschange', onInputSourcesChange );
  51121. if ( attributes.xrCompatible !== true ) {
  51122. await gl.makeXRCompatible();
  51123. }
  51124. currentPixelRatio = renderer.getPixelRatio();
  51125. renderer.getSize( currentSize );
  51126. // Check that the browser implements the necessary APIs to use an
  51127. // XRProjectionLayer rather than an XRWebGLLayer
  51128. const supportsLayers = supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype;
  51129. if ( ! supportsLayers ) {
  51130. const layerInit = {
  51131. antialias: attributes.antialias,
  51132. alpha: true,
  51133. depth: attributes.depth,
  51134. stencil: attributes.stencil,
  51135. framebufferScaleFactor: framebufferScaleFactor
  51136. };
  51137. glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  51138. session.updateRenderState( { baseLayer: glBaseLayer } );
  51139. renderer.setPixelRatio( 1 );
  51140. renderer.setSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight, false );
  51141. newRenderTarget = new WebGLRenderTarget(
  51142. glBaseLayer.framebufferWidth,
  51143. glBaseLayer.framebufferHeight,
  51144. {
  51145. format: RGBAFormat,
  51146. type: UnsignedByteType,
  51147. colorSpace: renderer.outputColorSpace,
  51148. stencilBuffer: attributes.stencil,
  51149. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  51150. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false )
  51151. }
  51152. );
  51153. } else {
  51154. let depthFormat = null;
  51155. let depthType = null;
  51156. let glDepthFormat = null;
  51157. if ( attributes.depth ) {
  51158. glDepthFormat = attributes.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  51159. depthFormat = attributes.stencil ? DepthStencilFormat : DepthFormat;
  51160. depthType = attributes.stencil ? UnsignedInt248Type : UnsignedIntType;
  51161. }
  51162. const projectionlayerInit = {
  51163. colorFormat: gl.RGBA8,
  51164. depthFormat: glDepthFormat,
  51165. scaleFactor: framebufferScaleFactor
  51166. };
  51167. glBinding = this.getBinding();
  51168. glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  51169. session.updateRenderState( { layers: [ glProjLayer ] } );
  51170. renderer.setPixelRatio( 1 );
  51171. renderer.setSize( glProjLayer.textureWidth, glProjLayer.textureHeight, false );
  51172. newRenderTarget = new WebGLRenderTarget(
  51173. glProjLayer.textureWidth,
  51174. glProjLayer.textureHeight,
  51175. {
  51176. format: RGBAFormat,
  51177. type: UnsignedByteType,
  51178. depthTexture: new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat ),
  51179. stencilBuffer: attributes.stencil,
  51180. colorSpace: renderer.outputColorSpace,
  51181. samples: attributes.antialias ? 4 : 0,
  51182. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  51183. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false )
  51184. } );
  51185. }
  51186. newRenderTarget.isXRRenderTarget = true; // TODO Remove this when possible, see #23278
  51187. this.setFoveation( foveation );
  51188. customReferenceSpace = null;
  51189. referenceSpace = await session.requestReferenceSpace( referenceSpaceType );
  51190. animation.setContext( session );
  51191. animation.start();
  51192. scope.isPresenting = true;
  51193. scope.dispatchEvent( { type: 'sessionstart' } );
  51194. }
  51195. };
  51196. /**
  51197. * Returns the environment blend mode from the current XR session.
  51198. *
  51199. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  51200. */
  51201. this.getEnvironmentBlendMode = function () {
  51202. if ( session !== null ) {
  51203. return session.environmentBlendMode;
  51204. }
  51205. };
  51206. /**
  51207. * Returns the current depth texture computed via depth sensing.
  51208. *
  51209. * See {@link WebXRDepthSensing#getDepthTexture}.
  51210. *
  51211. * @return {?Texture} The depth texture.
  51212. */
  51213. this.getDepthTexture = function () {
  51214. return depthSensing.getDepthTexture();
  51215. };
  51216. function onInputSourcesChange( event ) {
  51217. // Notify disconnected
  51218. for ( let i = 0; i < event.removed.length; i ++ ) {
  51219. const inputSource = event.removed[ i ];
  51220. const index = controllerInputSources.indexOf( inputSource );
  51221. if ( index >= 0 ) {
  51222. controllerInputSources[ index ] = null;
  51223. controllers[ index ].disconnect( inputSource );
  51224. }
  51225. }
  51226. // Notify connected
  51227. for ( let i = 0; i < event.added.length; i ++ ) {
  51228. const inputSource = event.added[ i ];
  51229. let controllerIndex = controllerInputSources.indexOf( inputSource );
  51230. if ( controllerIndex === -1 ) {
  51231. // Assign input source a controller that currently has no input source
  51232. for ( let i = 0; i < controllers.length; i ++ ) {
  51233. if ( i >= controllerInputSources.length ) {
  51234. controllerInputSources.push( inputSource );
  51235. controllerIndex = i;
  51236. break;
  51237. } else if ( controllerInputSources[ i ] === null ) {
  51238. controllerInputSources[ i ] = inputSource;
  51239. controllerIndex = i;
  51240. break;
  51241. }
  51242. }
  51243. // If all controllers do currently receive input we ignore new ones
  51244. if ( controllerIndex === -1 ) break;
  51245. }
  51246. const controller = controllers[ controllerIndex ];
  51247. if ( controller ) {
  51248. controller.connect( inputSource );
  51249. }
  51250. }
  51251. }
  51252. //
  51253. const cameraLPos = new Vector3();
  51254. const cameraRPos = new Vector3();
  51255. /**
  51256. * Assumes 2 cameras that are parallel and share an X-axis, and that
  51257. * the cameras' projection and world matrices have already been set.
  51258. * And that near and far planes are identical for both cameras.
  51259. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  51260. *
  51261. * @param {ArrayCamera} camera - The camera to update.
  51262. * @param {PerspectiveCamera} cameraL - The left camera.
  51263. * @param {PerspectiveCamera} cameraR - The right camera.
  51264. */
  51265. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  51266. cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  51267. cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  51268. const ipd = cameraLPos.distanceTo( cameraRPos );
  51269. const projL = cameraL.projectionMatrix.elements;
  51270. const projR = cameraR.projectionMatrix.elements;
  51271. // VR systems will have identical far and near planes, and
  51272. // most likely identical top and bottom frustum extents.
  51273. // Use the left camera for these values.
  51274. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  51275. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  51276. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  51277. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  51278. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  51279. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  51280. const left = near * leftFov;
  51281. const right = near * rightFov;
  51282. // Calculate the new camera's position offset from the
  51283. // left camera. xOffset should be roughly half `ipd`.
  51284. const zOffset = ipd / ( - leftFov + rightFov );
  51285. const xOffset = zOffset * - leftFov;
  51286. // TODO: Better way to apply this offset?
  51287. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  51288. camera.translateX( xOffset );
  51289. camera.translateZ( zOffset );
  51290. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  51291. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51292. // Check if the projection uses an infinite far plane.
  51293. if ( projL[ 10 ] === -1 ) {
  51294. // Use the projection matrix from the left eye.
  51295. // The camera offset is sufficient to include the view volumes
  51296. // of both eyes (assuming symmetric projections).
  51297. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  51298. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  51299. } else {
  51300. // Find the union of the frustum values of the cameras and scale
  51301. // the values so that the near plane's position does not change in world space,
  51302. // although must now be relative to the new union camera.
  51303. const near2 = near + zOffset;
  51304. const far2 = far + zOffset;
  51305. const left2 = left - xOffset;
  51306. const right2 = right + ( ipd - xOffset );
  51307. const top2 = topFov * far / far2 * near2;
  51308. const bottom2 = bottomFov * far / far2 * near2;
  51309. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  51310. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51311. }
  51312. }
  51313. function updateCamera( camera, parent ) {
  51314. if ( parent === null ) {
  51315. camera.matrixWorld.copy( camera.matrix );
  51316. } else {
  51317. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  51318. }
  51319. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  51320. }
  51321. /**
  51322. * Updates the state of the XR camera. Use this method on app level if you
  51323. * set `cameraAutoUpdate` to `false`. The method requires the non-XR
  51324. * camera of the scene as a parameter. The passed in camera's transformation
  51325. * is automatically adjusted to the position of the XR camera when calling
  51326. * this method.
  51327. *
  51328. * @param {Camera} camera - The camera.
  51329. */
  51330. this.updateCamera = function ( camera ) {
  51331. if ( session === null ) return;
  51332. let depthNear = camera.near;
  51333. let depthFar = camera.far;
  51334. if ( depthSensing.texture !== null ) {
  51335. if ( depthSensing.depthNear > 0 ) depthNear = depthSensing.depthNear;
  51336. if ( depthSensing.depthFar > 0 ) depthFar = depthSensing.depthFar;
  51337. }
  51338. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  51339. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  51340. if ( _currentDepthNear !== cameraXR.near || _currentDepthFar !== cameraXR.far ) {
  51341. // Note that the new renderState won't apply until the next frame. See #18320
  51342. session.updateRenderState( {
  51343. depthNear: cameraXR.near,
  51344. depthFar: cameraXR.far
  51345. } );
  51346. _currentDepthNear = cameraXR.near;
  51347. _currentDepthFar = cameraXR.far;
  51348. }
  51349. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  51350. cameraXR.layers.mask = camera.layers.mask | 0b110;
  51351. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  51352. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  51353. const parent = camera.parent;
  51354. const cameras = cameraXR.cameras;
  51355. updateCamera( cameraXR, parent );
  51356. for ( let i = 0; i < cameras.length; i ++ ) {
  51357. updateCamera( cameras[ i ], parent );
  51358. }
  51359. // update projection matrix for proper view frustum culling
  51360. if ( cameras.length === 2 ) {
  51361. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  51362. } else {
  51363. // assume single camera setup (AR)
  51364. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  51365. }
  51366. // update user camera and its children
  51367. updateUserCamera( camera, cameraXR, parent );
  51368. };
  51369. function updateUserCamera( camera, cameraXR, parent ) {
  51370. if ( parent === null ) {
  51371. camera.matrix.copy( cameraXR.matrixWorld );
  51372. } else {
  51373. camera.matrix.copy( parent.matrixWorld );
  51374. camera.matrix.invert();
  51375. camera.matrix.multiply( cameraXR.matrixWorld );
  51376. }
  51377. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51378. camera.updateMatrixWorld( true );
  51379. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  51380. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  51381. if ( camera.isPerspectiveCamera ) {
  51382. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  51383. camera.zoom = 1;
  51384. }
  51385. }
  51386. /**
  51387. * Returns an instance of {@link ArrayCamera} which represents the XR camera
  51388. * of the active XR session. For each view it holds a separate camera object.
  51389. *
  51390. * The camera's `fov` is currently not used and does not reflect the fov of
  51391. * the XR camera. If you need the fov on app level, you have to compute in
  51392. * manually from the XR camera's projection matrices.
  51393. *
  51394. * @return {ArrayCamera} The XR camera.
  51395. */
  51396. this.getCamera = function () {
  51397. return cameraXR;
  51398. };
  51399. /**
  51400. * Returns the amount of foveation used by the XR compositor for the projection layer.
  51401. *
  51402. * @return {number|undefined} The amount of foveation.
  51403. */
  51404. this.getFoveation = function () {
  51405. if ( glProjLayer === null && glBaseLayer === null ) {
  51406. return undefined;
  51407. }
  51408. return foveation;
  51409. };
  51410. /**
  51411. * Sets the foveation value.
  51412. *
  51413. * @param {number} value - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  51414. * and `1` means maximum foveation (the edges render at lower resolution).
  51415. */
  51416. this.setFoveation = function ( value ) {
  51417. // 0 = no foveation = full resolution
  51418. // 1 = maximum foveation = the edges render at lower resolution
  51419. foveation = value;
  51420. if ( glProjLayer !== null ) {
  51421. glProjLayer.fixedFoveation = value;
  51422. }
  51423. if ( glBaseLayer !== null && glBaseLayer.fixedFoveation !== undefined ) {
  51424. glBaseLayer.fixedFoveation = value;
  51425. }
  51426. };
  51427. /**
  51428. * Returns `true` if depth sensing is supported.
  51429. *
  51430. * @return {boolean} Whether depth sensing is supported or not.
  51431. */
  51432. this.hasDepthSensing = function () {
  51433. return depthSensing.texture !== null;
  51434. };
  51435. /**
  51436. * Returns the depth sensing mesh.
  51437. *
  51438. * See {@link WebXRDepthSensing#getMesh}.
  51439. *
  51440. * @return {Mesh} The depth sensing mesh.
  51441. */
  51442. this.getDepthSensingMesh = function () {
  51443. return depthSensing.getMesh( cameraXR );
  51444. };
  51445. /**
  51446. * Retrieves an opaque texture from the view-aligned {@link XRCamera}.
  51447. * Only available during the current animation loop.
  51448. *
  51449. * @param {XRCamera} xrCamera - The camera to query.
  51450. * @return {?Texture} An opaque texture representing the current raw camera frame.
  51451. */
  51452. this.getCameraTexture = function ( xrCamera ) {
  51453. return cameraAccessTextures[ xrCamera ];
  51454. };
  51455. // Animation Loop
  51456. let onAnimationFrameCallback = null;
  51457. function onAnimationFrame( time, frame ) {
  51458. pose = frame.getViewerPose( customReferenceSpace || referenceSpace );
  51459. xrFrame = frame;
  51460. if ( pose !== null ) {
  51461. const views = pose.views;
  51462. if ( glBaseLayer !== null ) {
  51463. renderer.setRenderTargetFramebuffer( newRenderTarget, glBaseLayer.framebuffer );
  51464. renderer.setRenderTarget( newRenderTarget );
  51465. }
  51466. let cameraXRNeedsUpdate = false;
  51467. // check if it's necessary to rebuild cameraXR's camera list
  51468. if ( views.length !== cameraXR.cameras.length ) {
  51469. cameraXR.cameras.length = 0;
  51470. cameraXRNeedsUpdate = true;
  51471. }
  51472. for ( let i = 0; i < views.length; i ++ ) {
  51473. const view = views[ i ];
  51474. let viewport = null;
  51475. if ( glBaseLayer !== null ) {
  51476. viewport = glBaseLayer.getViewport( view );
  51477. } else {
  51478. const glSubImage = glBinding.getViewSubImage( glProjLayer, view );
  51479. viewport = glSubImage.viewport;
  51480. // For side-by-side projection, we only produce a single texture for both eyes.
  51481. if ( i === 0 ) {
  51482. renderer.setRenderTargetTextures(
  51483. newRenderTarget,
  51484. glSubImage.colorTexture,
  51485. glSubImage.depthStencilTexture );
  51486. renderer.setRenderTarget( newRenderTarget );
  51487. }
  51488. }
  51489. let camera = cameras[ i ];
  51490. if ( camera === undefined ) {
  51491. camera = new PerspectiveCamera();
  51492. camera.layers.enable( i );
  51493. camera.viewport = new Vector4();
  51494. cameras[ i ] = camera;
  51495. }
  51496. camera.matrix.fromArray( view.transform.matrix );
  51497. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  51498. camera.projectionMatrix.fromArray( view.projectionMatrix );
  51499. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  51500. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  51501. if ( i === 0 ) {
  51502. cameraXR.matrix.copy( camera.matrix );
  51503. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  51504. }
  51505. if ( cameraXRNeedsUpdate === true ) {
  51506. cameraXR.cameras.push( camera );
  51507. }
  51508. }
  51509. //
  51510. const enabledFeatures = session.enabledFeatures;
  51511. const gpuDepthSensingEnabled = enabledFeatures &&
  51512. enabledFeatures.includes( 'depth-sensing' ) &&
  51513. session.depthUsage == 'gpu-optimized';
  51514. if ( gpuDepthSensingEnabled && supportsGlBinding ) {
  51515. glBinding = scope.getBinding();
  51516. const depthData = glBinding.getDepthInformation( views[ 0 ] );
  51517. if ( depthData && depthData.isValid && depthData.texture ) {
  51518. depthSensing.init( depthData, session.renderState );
  51519. }
  51520. }
  51521. const cameraAccessEnabled = enabledFeatures &&
  51522. enabledFeatures.includes( 'camera-access' );
  51523. if ( cameraAccessEnabled && supportsGlBinding ) {
  51524. renderer.state.unbindTexture();
  51525. glBinding = scope.getBinding();
  51526. for ( let i = 0; i < views.length; i ++ ) {
  51527. const camera = views[ i ].camera;
  51528. if ( camera ) {
  51529. let cameraTex = cameraAccessTextures[ camera ];
  51530. if ( ! cameraTex ) {
  51531. cameraTex = new ExternalTexture();
  51532. cameraAccessTextures[ camera ] = cameraTex;
  51533. }
  51534. const glTexture = glBinding.getCameraImage( camera );
  51535. cameraTex.sourceTexture = glTexture;
  51536. }
  51537. }
  51538. }
  51539. }
  51540. //
  51541. for ( let i = 0; i < controllers.length; i ++ ) {
  51542. const inputSource = controllerInputSources[ i ];
  51543. const controller = controllers[ i ];
  51544. if ( inputSource !== null && controller !== undefined ) {
  51545. controller.update( inputSource, frame, customReferenceSpace || referenceSpace );
  51546. }
  51547. }
  51548. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time, frame );
  51549. if ( frame.detectedPlanes ) {
  51550. scope.dispatchEvent( { type: 'planesdetected', data: frame } );
  51551. }
  51552. xrFrame = null;
  51553. }
  51554. const animation = new WebGLAnimation();
  51555. animation.setAnimationLoop( onAnimationFrame );
  51556. this.setAnimationLoop = function ( callback ) {
  51557. onAnimationFrameCallback = callback;
  51558. };
  51559. this.dispose = function () {};
  51560. }
  51561. }
  51562. const _e1 = /*@__PURE__*/ new Euler();
  51563. const _m1 = /*@__PURE__*/ new Matrix4();
  51564. function WebGLMaterials( renderer, properties ) {
  51565. function refreshTransformUniform( map, uniform ) {
  51566. if ( map.matrixAutoUpdate === true ) {
  51567. map.updateMatrix();
  51568. }
  51569. uniform.value.copy( map.matrix );
  51570. }
  51571. function refreshFogUniforms( uniforms, fog ) {
  51572. fog.color.getRGB( uniforms.fogColor.value, getUnlitUniformColorSpace( renderer ) );
  51573. if ( fog.isFog ) {
  51574. uniforms.fogNear.value = fog.near;
  51575. uniforms.fogFar.value = fog.far;
  51576. } else if ( fog.isFogExp2 ) {
  51577. uniforms.fogDensity.value = fog.density;
  51578. }
  51579. }
  51580. function refreshMaterialUniforms( uniforms, material, pixelRatio, height, transmissionRenderTarget ) {
  51581. if ( material.isMeshBasicMaterial ) {
  51582. refreshUniformsCommon( uniforms, material );
  51583. } else if ( material.isMeshLambertMaterial ) {
  51584. refreshUniformsCommon( uniforms, material );
  51585. } else if ( material.isMeshToonMaterial ) {
  51586. refreshUniformsCommon( uniforms, material );
  51587. refreshUniformsToon( uniforms, material );
  51588. } else if ( material.isMeshPhongMaterial ) {
  51589. refreshUniformsCommon( uniforms, material );
  51590. refreshUniformsPhong( uniforms, material );
  51591. } else if ( material.isMeshStandardMaterial ) {
  51592. refreshUniformsCommon( uniforms, material );
  51593. refreshUniformsStandard( uniforms, material );
  51594. if ( material.isMeshPhysicalMaterial ) {
  51595. refreshUniformsPhysical( uniforms, material, transmissionRenderTarget );
  51596. }
  51597. } else if ( material.isMeshMatcapMaterial ) {
  51598. refreshUniformsCommon( uniforms, material );
  51599. refreshUniformsMatcap( uniforms, material );
  51600. } else if ( material.isMeshDepthMaterial ) {
  51601. refreshUniformsCommon( uniforms, material );
  51602. } else if ( material.isMeshDistanceMaterial ) {
  51603. refreshUniformsCommon( uniforms, material );
  51604. refreshUniformsDistance( uniforms, material );
  51605. } else if ( material.isMeshNormalMaterial ) {
  51606. refreshUniformsCommon( uniforms, material );
  51607. } else if ( material.isLineBasicMaterial ) {
  51608. refreshUniformsLine( uniforms, material );
  51609. if ( material.isLineDashedMaterial ) {
  51610. refreshUniformsDash( uniforms, material );
  51611. }
  51612. } else if ( material.isPointsMaterial ) {
  51613. refreshUniformsPoints( uniforms, material, pixelRatio, height );
  51614. } else if ( material.isSpriteMaterial ) {
  51615. refreshUniformsSprites( uniforms, material );
  51616. } else if ( material.isShadowMaterial ) {
  51617. uniforms.color.value.copy( material.color );
  51618. uniforms.opacity.value = material.opacity;
  51619. } else if ( material.isShaderMaterial ) {
  51620. material.uniformsNeedUpdate = false; // #15581
  51621. }
  51622. }
  51623. function refreshUniformsCommon( uniforms, material ) {
  51624. uniforms.opacity.value = material.opacity;
  51625. if ( material.color ) {
  51626. uniforms.diffuse.value.copy( material.color );
  51627. }
  51628. if ( material.emissive ) {
  51629. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  51630. }
  51631. if ( material.map ) {
  51632. uniforms.map.value = material.map;
  51633. refreshTransformUniform( material.map, uniforms.mapTransform );
  51634. }
  51635. if ( material.alphaMap ) {
  51636. uniforms.alphaMap.value = material.alphaMap;
  51637. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51638. }
  51639. if ( material.bumpMap ) {
  51640. uniforms.bumpMap.value = material.bumpMap;
  51641. refreshTransformUniform( material.bumpMap, uniforms.bumpMapTransform );
  51642. uniforms.bumpScale.value = material.bumpScale;
  51643. if ( material.side === BackSide ) {
  51644. uniforms.bumpScale.value *= -1;
  51645. }
  51646. }
  51647. if ( material.normalMap ) {
  51648. uniforms.normalMap.value = material.normalMap;
  51649. refreshTransformUniform( material.normalMap, uniforms.normalMapTransform );
  51650. uniforms.normalScale.value.copy( material.normalScale );
  51651. if ( material.side === BackSide ) {
  51652. uniforms.normalScale.value.negate();
  51653. }
  51654. }
  51655. if ( material.displacementMap ) {
  51656. uniforms.displacementMap.value = material.displacementMap;
  51657. refreshTransformUniform( material.displacementMap, uniforms.displacementMapTransform );
  51658. uniforms.displacementScale.value = material.displacementScale;
  51659. uniforms.displacementBias.value = material.displacementBias;
  51660. }
  51661. if ( material.emissiveMap ) {
  51662. uniforms.emissiveMap.value = material.emissiveMap;
  51663. refreshTransformUniform( material.emissiveMap, uniforms.emissiveMapTransform );
  51664. }
  51665. if ( material.specularMap ) {
  51666. uniforms.specularMap.value = material.specularMap;
  51667. refreshTransformUniform( material.specularMap, uniforms.specularMapTransform );
  51668. }
  51669. if ( material.alphaTest > 0 ) {
  51670. uniforms.alphaTest.value = material.alphaTest;
  51671. }
  51672. const materialProperties = properties.get( material );
  51673. const envMap = materialProperties.envMap;
  51674. const envMapRotation = materialProperties.envMapRotation;
  51675. if ( envMap ) {
  51676. uniforms.envMap.value = envMap;
  51677. _e1.copy( envMapRotation );
  51678. // accommodate left-handed frame
  51679. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  51680. if ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) {
  51681. // environment maps which are not cube render targets or PMREMs follow a different convention
  51682. _e1.y *= -1;
  51683. _e1.z *= -1;
  51684. }
  51685. uniforms.envMapRotation.value.setFromMatrix4( _m1.makeRotationFromEuler( _e1 ) );
  51686. uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  51687. uniforms.reflectivity.value = material.reflectivity;
  51688. uniforms.ior.value = material.ior;
  51689. uniforms.refractionRatio.value = material.refractionRatio;
  51690. }
  51691. if ( material.lightMap ) {
  51692. uniforms.lightMap.value = material.lightMap;
  51693. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  51694. refreshTransformUniform( material.lightMap, uniforms.lightMapTransform );
  51695. }
  51696. if ( material.aoMap ) {
  51697. uniforms.aoMap.value = material.aoMap;
  51698. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  51699. refreshTransformUniform( material.aoMap, uniforms.aoMapTransform );
  51700. }
  51701. }
  51702. function refreshUniformsLine( uniforms, material ) {
  51703. uniforms.diffuse.value.copy( material.color );
  51704. uniforms.opacity.value = material.opacity;
  51705. if ( material.map ) {
  51706. uniforms.map.value = material.map;
  51707. refreshTransformUniform( material.map, uniforms.mapTransform );
  51708. }
  51709. }
  51710. function refreshUniformsDash( uniforms, material ) {
  51711. uniforms.dashSize.value = material.dashSize;
  51712. uniforms.totalSize.value = material.dashSize + material.gapSize;
  51713. uniforms.scale.value = material.scale;
  51714. }
  51715. function refreshUniformsPoints( uniforms, material, pixelRatio, height ) {
  51716. uniforms.diffuse.value.copy( material.color );
  51717. uniforms.opacity.value = material.opacity;
  51718. uniforms.size.value = material.size * pixelRatio;
  51719. uniforms.scale.value = height * 0.5;
  51720. if ( material.map ) {
  51721. uniforms.map.value = material.map;
  51722. refreshTransformUniform( material.map, uniforms.uvTransform );
  51723. }
  51724. if ( material.alphaMap ) {
  51725. uniforms.alphaMap.value = material.alphaMap;
  51726. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51727. }
  51728. if ( material.alphaTest > 0 ) {
  51729. uniforms.alphaTest.value = material.alphaTest;
  51730. }
  51731. }
  51732. function refreshUniformsSprites( uniforms, material ) {
  51733. uniforms.diffuse.value.copy( material.color );
  51734. uniforms.opacity.value = material.opacity;
  51735. uniforms.rotation.value = material.rotation;
  51736. if ( material.map ) {
  51737. uniforms.map.value = material.map;
  51738. refreshTransformUniform( material.map, uniforms.mapTransform );
  51739. }
  51740. if ( material.alphaMap ) {
  51741. uniforms.alphaMap.value = material.alphaMap;
  51742. refreshTransformUniform( material.alphaMap, uniforms.alphaMapTransform );
  51743. }
  51744. if ( material.alphaTest > 0 ) {
  51745. uniforms.alphaTest.value = material.alphaTest;
  51746. }
  51747. }
  51748. function refreshUniformsPhong( uniforms, material ) {
  51749. uniforms.specular.value.copy( material.specular );
  51750. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  51751. }
  51752. function refreshUniformsToon( uniforms, material ) {
  51753. if ( material.gradientMap ) {
  51754. uniforms.gradientMap.value = material.gradientMap;
  51755. }
  51756. }
  51757. function refreshUniformsStandard( uniforms, material ) {
  51758. uniforms.metalness.value = material.metalness;
  51759. if ( material.metalnessMap ) {
  51760. uniforms.metalnessMap.value = material.metalnessMap;
  51761. refreshTransformUniform( material.metalnessMap, uniforms.metalnessMapTransform );
  51762. }
  51763. uniforms.roughness.value = material.roughness;
  51764. if ( material.roughnessMap ) {
  51765. uniforms.roughnessMap.value = material.roughnessMap;
  51766. refreshTransformUniform( material.roughnessMap, uniforms.roughnessMapTransform );
  51767. }
  51768. if ( material.envMap ) {
  51769. //uniforms.envMap.value = material.envMap; // part of uniforms common
  51770. uniforms.envMapIntensity.value = material.envMapIntensity;
  51771. }
  51772. }
  51773. function refreshUniformsPhysical( uniforms, material, transmissionRenderTarget ) {
  51774. uniforms.ior.value = material.ior; // also part of uniforms common
  51775. if ( material.sheen > 0 ) {
  51776. uniforms.sheenColor.value.copy( material.sheenColor ).multiplyScalar( material.sheen );
  51777. uniforms.sheenRoughness.value = material.sheenRoughness;
  51778. if ( material.sheenColorMap ) {
  51779. uniforms.sheenColorMap.value = material.sheenColorMap;
  51780. refreshTransformUniform( material.sheenColorMap, uniforms.sheenColorMapTransform );
  51781. }
  51782. if ( material.sheenRoughnessMap ) {
  51783. uniforms.sheenRoughnessMap.value = material.sheenRoughnessMap;
  51784. refreshTransformUniform( material.sheenRoughnessMap, uniforms.sheenRoughnessMapTransform );
  51785. }
  51786. }
  51787. if ( material.clearcoat > 0 ) {
  51788. uniforms.clearcoat.value = material.clearcoat;
  51789. uniforms.clearcoatRoughness.value = material.clearcoatRoughness;
  51790. if ( material.clearcoatMap ) {
  51791. uniforms.clearcoatMap.value = material.clearcoatMap;
  51792. refreshTransformUniform( material.clearcoatMap, uniforms.clearcoatMapTransform );
  51793. }
  51794. if ( material.clearcoatRoughnessMap ) {
  51795. uniforms.clearcoatRoughnessMap.value = material.clearcoatRoughnessMap;
  51796. refreshTransformUniform( material.clearcoatRoughnessMap, uniforms.clearcoatRoughnessMapTransform );
  51797. }
  51798. if ( material.clearcoatNormalMap ) {
  51799. uniforms.clearcoatNormalMap.value = material.clearcoatNormalMap;
  51800. refreshTransformUniform( material.clearcoatNormalMap, uniforms.clearcoatNormalMapTransform );
  51801. uniforms.clearcoatNormalScale.value.copy( material.clearcoatNormalScale );
  51802. if ( material.side === BackSide ) {
  51803. uniforms.clearcoatNormalScale.value.negate();
  51804. }
  51805. }
  51806. }
  51807. if ( material.dispersion > 0 ) {
  51808. uniforms.dispersion.value = material.dispersion;
  51809. }
  51810. if ( material.iridescence > 0 ) {
  51811. uniforms.iridescence.value = material.iridescence;
  51812. uniforms.iridescenceIOR.value = material.iridescenceIOR;
  51813. uniforms.iridescenceThicknessMinimum.value = material.iridescenceThicknessRange[ 0 ];
  51814. uniforms.iridescenceThicknessMaximum.value = material.iridescenceThicknessRange[ 1 ];
  51815. if ( material.iridescenceMap ) {
  51816. uniforms.iridescenceMap.value = material.iridescenceMap;
  51817. refreshTransformUniform( material.iridescenceMap, uniforms.iridescenceMapTransform );
  51818. }
  51819. if ( material.iridescenceThicknessMap ) {
  51820. uniforms.iridescenceThicknessMap.value = material.iridescenceThicknessMap;
  51821. refreshTransformUniform( material.iridescenceThicknessMap, uniforms.iridescenceThicknessMapTransform );
  51822. }
  51823. }
  51824. if ( material.transmission > 0 ) {
  51825. uniforms.transmission.value = material.transmission;
  51826. uniforms.transmissionSamplerMap.value = transmissionRenderTarget.texture;
  51827. uniforms.transmissionSamplerSize.value.set( transmissionRenderTarget.width, transmissionRenderTarget.height );
  51828. if ( material.transmissionMap ) {
  51829. uniforms.transmissionMap.value = material.transmissionMap;
  51830. refreshTransformUniform( material.transmissionMap, uniforms.transmissionMapTransform );
  51831. }
  51832. uniforms.thickness.value = material.thickness;
  51833. if ( material.thicknessMap ) {
  51834. uniforms.thicknessMap.value = material.thicknessMap;
  51835. refreshTransformUniform( material.thicknessMap, uniforms.thicknessMapTransform );
  51836. }
  51837. uniforms.attenuationDistance.value = material.attenuationDistance;
  51838. uniforms.attenuationColor.value.copy( material.attenuationColor );
  51839. }
  51840. if ( material.anisotropy > 0 ) {
  51841. uniforms.anisotropyVector.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  51842. if ( material.anisotropyMap ) {
  51843. uniforms.anisotropyMap.value = material.anisotropyMap;
  51844. refreshTransformUniform( material.anisotropyMap, uniforms.anisotropyMapTransform );
  51845. }
  51846. }
  51847. uniforms.specularIntensity.value = material.specularIntensity;
  51848. uniforms.specularColor.value.copy( material.specularColor );
  51849. if ( material.specularColorMap ) {
  51850. uniforms.specularColorMap.value = material.specularColorMap;
  51851. refreshTransformUniform( material.specularColorMap, uniforms.specularColorMapTransform );
  51852. }
  51853. if ( material.specularIntensityMap ) {
  51854. uniforms.specularIntensityMap.value = material.specularIntensityMap;
  51855. refreshTransformUniform( material.specularIntensityMap, uniforms.specularIntensityMapTransform );
  51856. }
  51857. }
  51858. function refreshUniformsMatcap( uniforms, material ) {
  51859. if ( material.matcap ) {
  51860. uniforms.matcap.value = material.matcap;
  51861. }
  51862. }
  51863. function refreshUniformsDistance( uniforms, material ) {
  51864. const light = properties.get( material ).light;
  51865. uniforms.referencePosition.value.setFromMatrixPosition( light.matrixWorld );
  51866. uniforms.nearDistance.value = light.shadow.camera.near;
  51867. uniforms.farDistance.value = light.shadow.camera.far;
  51868. }
  51869. return {
  51870. refreshFogUniforms: refreshFogUniforms,
  51871. refreshMaterialUniforms: refreshMaterialUniforms
  51872. };
  51873. }
  51874. function WebGLUniformsGroups( gl, info, capabilities, state ) {
  51875. let buffers = {};
  51876. let updateList = {};
  51877. let allocatedBindingPoints = [];
  51878. const maxBindingPoints = gl.getParameter( gl.MAX_UNIFORM_BUFFER_BINDINGS ); // binding points are global whereas block indices are per shader program
  51879. function bind( uniformsGroup, program ) {
  51880. const webglProgram = program.program;
  51881. state.uniformBlockBinding( uniformsGroup, webglProgram );
  51882. }
  51883. function update( uniformsGroup, program ) {
  51884. let buffer = buffers[ uniformsGroup.id ];
  51885. if ( buffer === undefined ) {
  51886. prepareUniformsGroup( uniformsGroup );
  51887. buffer = createBuffer( uniformsGroup );
  51888. buffers[ uniformsGroup.id ] = buffer;
  51889. uniformsGroup.addEventListener( 'dispose', onUniformsGroupsDispose );
  51890. }
  51891. // ensure to update the binding points/block indices mapping for this program
  51892. const webglProgram = program.program;
  51893. state.updateUBOMapping( uniformsGroup, webglProgram );
  51894. // update UBO once per frame
  51895. const frame = info.render.frame;
  51896. if ( updateList[ uniformsGroup.id ] !== frame ) {
  51897. updateBufferData( uniformsGroup );
  51898. updateList[ uniformsGroup.id ] = frame;
  51899. }
  51900. }
  51901. function createBuffer( uniformsGroup ) {
  51902. // the setup of an UBO is independent of a particular shader program but global
  51903. const bindingPointIndex = allocateBindingPointIndex();
  51904. uniformsGroup.__bindingPointIndex = bindingPointIndex;
  51905. const buffer = gl.createBuffer();
  51906. const size = uniformsGroup.__size;
  51907. const usage = uniformsGroup.usage;
  51908. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51909. gl.bufferData( gl.UNIFORM_BUFFER, size, usage );
  51910. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51911. gl.bindBufferBase( gl.UNIFORM_BUFFER, bindingPointIndex, buffer );
  51912. return buffer;
  51913. }
  51914. function allocateBindingPointIndex() {
  51915. for ( let i = 0; i < maxBindingPoints; i ++ ) {
  51916. if ( allocatedBindingPoints.indexOf( i ) === -1 ) {
  51917. allocatedBindingPoints.push( i );
  51918. return i;
  51919. }
  51920. }
  51921. error( 'WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached.' );
  51922. return 0;
  51923. }
  51924. function updateBufferData( uniformsGroup ) {
  51925. const buffer = buffers[ uniformsGroup.id ];
  51926. const uniforms = uniformsGroup.uniforms;
  51927. const cache = uniformsGroup.__cache;
  51928. gl.bindBuffer( gl.UNIFORM_BUFFER, buffer );
  51929. for ( let i = 0, il = uniforms.length; i < il; i ++ ) {
  51930. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  51931. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  51932. const uniform = uniformArray[ j ];
  51933. if ( hasUniformChanged( uniform, i, j, cache ) === true ) {
  51934. const offset = uniform.__offset;
  51935. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  51936. let arrayOffset = 0;
  51937. for ( let k = 0; k < values.length; k ++ ) {
  51938. const value = values[ k ];
  51939. const info = getUniformSize( value );
  51940. // TODO add integer and struct support
  51941. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51942. uniform.__data[ 0 ] = value;
  51943. gl.bufferSubData( gl.UNIFORM_BUFFER, offset + arrayOffset, uniform.__data );
  51944. } else if ( value.isMatrix3 ) {
  51945. // manually converting 3x3 to 3x4
  51946. uniform.__data[ 0 ] = value.elements[ 0 ];
  51947. uniform.__data[ 1 ] = value.elements[ 1 ];
  51948. uniform.__data[ 2 ] = value.elements[ 2 ];
  51949. uniform.__data[ 3 ] = 0;
  51950. uniform.__data[ 4 ] = value.elements[ 3 ];
  51951. uniform.__data[ 5 ] = value.elements[ 4 ];
  51952. uniform.__data[ 6 ] = value.elements[ 5 ];
  51953. uniform.__data[ 7 ] = 0;
  51954. uniform.__data[ 8 ] = value.elements[ 6 ];
  51955. uniform.__data[ 9 ] = value.elements[ 7 ];
  51956. uniform.__data[ 10 ] = value.elements[ 8 ];
  51957. uniform.__data[ 11 ] = 0;
  51958. } else {
  51959. value.toArray( uniform.__data, arrayOffset );
  51960. arrayOffset += info.storage / Float32Array.BYTES_PER_ELEMENT;
  51961. }
  51962. }
  51963. gl.bufferSubData( gl.UNIFORM_BUFFER, offset, uniform.__data );
  51964. }
  51965. }
  51966. }
  51967. gl.bindBuffer( gl.UNIFORM_BUFFER, null );
  51968. }
  51969. function hasUniformChanged( uniform, index, indexArray, cache ) {
  51970. const value = uniform.value;
  51971. const indexString = index + '_' + indexArray;
  51972. if ( cache[ indexString ] === undefined ) {
  51973. // cache entry does not exist so far
  51974. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51975. cache[ indexString ] = value;
  51976. } else {
  51977. cache[ indexString ] = value.clone();
  51978. }
  51979. return true;
  51980. } else {
  51981. const cachedObject = cache[ indexString ];
  51982. // compare current value with cached entry
  51983. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  51984. if ( cachedObject !== value ) {
  51985. cache[ indexString ] = value;
  51986. return true;
  51987. }
  51988. } else {
  51989. if ( cachedObject.equals( value ) === false ) {
  51990. cachedObject.copy( value );
  51991. return true;
  51992. }
  51993. }
  51994. }
  51995. return false;
  51996. }
  51997. function prepareUniformsGroup( uniformsGroup ) {
  51998. // determine total buffer size according to the STD140 layout
  51999. // Hint: STD140 is the only supported layout in WebGL 2
  52000. const uniforms = uniformsGroup.uniforms;
  52001. let offset = 0; // global buffer offset in bytes
  52002. const chunkSize = 16; // size of a chunk in bytes
  52003. for ( let i = 0, l = uniforms.length; i < l; i ++ ) {
  52004. const uniformArray = Array.isArray( uniforms[ i ] ) ? uniforms[ i ] : [ uniforms[ i ] ];
  52005. for ( let j = 0, jl = uniformArray.length; j < jl; j ++ ) {
  52006. const uniform = uniformArray[ j ];
  52007. const values = Array.isArray( uniform.value ) ? uniform.value : [ uniform.value ];
  52008. for ( let k = 0, kl = values.length; k < kl; k ++ ) {
  52009. const value = values[ k ];
  52010. const info = getUniformSize( value );
  52011. const chunkOffset = offset % chunkSize; // offset in the current chunk
  52012. const chunkPadding = chunkOffset % info.boundary; // required padding to match boundary
  52013. const chunkStart = chunkOffset + chunkPadding; // the start position in the current chunk for the data
  52014. offset += chunkPadding;
  52015. // Check for chunk overflow
  52016. if ( chunkStart !== 0 && ( chunkSize - chunkStart ) < info.storage ) {
  52017. // Add padding and adjust offset
  52018. offset += ( chunkSize - chunkStart );
  52019. }
  52020. // the following two properties will be used for partial buffer updates
  52021. uniform.__data = new Float32Array( info.storage / Float32Array.BYTES_PER_ELEMENT );
  52022. uniform.__offset = offset;
  52023. // Update the global offset
  52024. offset += info.storage;
  52025. }
  52026. }
  52027. }
  52028. // ensure correct final padding
  52029. const chunkOffset = offset % chunkSize;
  52030. if ( chunkOffset > 0 ) offset += ( chunkSize - chunkOffset );
  52031. //
  52032. uniformsGroup.__size = offset;
  52033. uniformsGroup.__cache = {};
  52034. return this;
  52035. }
  52036. function getUniformSize( value ) {
  52037. const info = {
  52038. boundary: 0, // bytes
  52039. storage: 0 // bytes
  52040. };
  52041. // determine sizes according to STD140
  52042. if ( typeof value === 'number' || typeof value === 'boolean' ) {
  52043. // float/int/bool
  52044. info.boundary = 4;
  52045. info.storage = 4;
  52046. } else if ( value.isVector2 ) {
  52047. // vec2
  52048. info.boundary = 8;
  52049. info.storage = 8;
  52050. } else if ( value.isVector3 || value.isColor ) {
  52051. // vec3
  52052. info.boundary = 16;
  52053. info.storage = 12; // evil: vec3 must start on a 16-byte boundary but it only consumes 12 bytes
  52054. } else if ( value.isVector4 ) {
  52055. // vec4
  52056. info.boundary = 16;
  52057. info.storage = 16;
  52058. } else if ( value.isMatrix3 ) {
  52059. // mat3 (in STD140 a 3x3 matrix is represented as 3x4)
  52060. info.boundary = 48;
  52061. info.storage = 48;
  52062. } else if ( value.isMatrix4 ) {
  52063. // mat4
  52064. info.boundary = 64;
  52065. info.storage = 64;
  52066. } else if ( value.isTexture ) {
  52067. warn( 'WebGLRenderer: Texture samplers can not be part of an uniforms group.' );
  52068. } else {
  52069. warn( 'WebGLRenderer: Unsupported uniform value type.', value );
  52070. }
  52071. return info;
  52072. }
  52073. function onUniformsGroupsDispose( event ) {
  52074. const uniformsGroup = event.target;
  52075. uniformsGroup.removeEventListener( 'dispose', onUniformsGroupsDispose );
  52076. const index = allocatedBindingPoints.indexOf( uniformsGroup.__bindingPointIndex );
  52077. allocatedBindingPoints.splice( index, 1 );
  52078. gl.deleteBuffer( buffers[ uniformsGroup.id ] );
  52079. delete buffers[ uniformsGroup.id ];
  52080. delete updateList[ uniformsGroup.id ];
  52081. }
  52082. function dispose() {
  52083. for ( const id in buffers ) {
  52084. gl.deleteBuffer( buffers[ id ] );
  52085. }
  52086. allocatedBindingPoints = [];
  52087. buffers = {};
  52088. updateList = {};
  52089. }
  52090. return {
  52091. bind: bind,
  52092. update: update,
  52093. dispose: dispose
  52094. };
  52095. }
  52096. /**
  52097. * Precomputed DFG LUT for Image-Based Lighting
  52098. * Resolution: 32x32
  52099. * Samples: 4096 per texel
  52100. * Format: RG16F (2 half floats per texel: scale, bias)
  52101. */
  52102. const DATA = new Uint16Array( [
  52103. 0x2cd9, 0x3b64, 0x2d0e, 0x3b43, 0x2e20, 0x3aa7, 0x3061, 0x39fb, 0x325e, 0x397c, 0x3454, 0x3908, 0x357d, 0x3893, 0x3698, 0x381e, 0x379d, 0x375b, 0x3845, 0x3689, 0x38af, 0x35ca, 0x390d, 0x351e, 0x395f, 0x3484, 0x39a8, 0x33f9, 0x39e6, 0x330a, 0x3a1c, 0x3239, 0x3a4b, 0x3183, 0x3a73, 0x30e5, 0x3a95, 0x305b, 0x3ab1, 0x2fc6, 0x3ac9, 0x2ef7, 0x3ade, 0x2e43, 0x3aee, 0x2da7, 0x3afc, 0x2d1f, 0x3b07, 0x2ca9, 0x3b10, 0x2c42, 0x3b17, 0x2bd1, 0x3b1c, 0x2b34, 0x3b1f, 0x2aaa, 0x3b22, 0x2a31, 0x3b23, 0x29c7, 0x3b23, 0x2968,
  52104. 0x32d4, 0x3a4b, 0x32dc, 0x3a45, 0x3308, 0x3a26, 0x3378, 0x39d0, 0x3425, 0x394a, 0x34c9, 0x38be, 0x359c, 0x383e, 0x3688, 0x3796, 0x3778, 0x36c4, 0x382f, 0x3603, 0x3898, 0x3553, 0x38f7, 0x34b3, 0x394b, 0x3424, 0x3994, 0x334c, 0x39d3, 0x326c, 0x3a08, 0x31a9, 0x3a35, 0x30fe, 0x3a5a, 0x306a, 0x3a78, 0x2fd1, 0x3a90, 0x2ef1, 0x3aa2, 0x2e2e, 0x3ab0, 0x2d86, 0x3aba, 0x2cf3, 0x3ac1, 0x2c74, 0x3ac4, 0x2c05, 0x3ac4, 0x2b49, 0x3ac2, 0x2aa1, 0x3abd, 0x2a0c, 0x3ab7, 0x298b, 0x3aaf, 0x2918, 0x3aa6, 0x28b3, 0x3a9b, 0x285a,
  52105. 0x3559, 0x3954, 0x355a, 0x3951, 0x3566, 0x3944, 0x3582, 0x391e, 0x35b6, 0x38d3, 0x360a, 0x386a, 0x3684, 0x37ed, 0x3720, 0x370d, 0x37d3, 0x3641, 0x3847, 0x3588, 0x38a3, 0x34e2, 0x38fa, 0x344d, 0x3948, 0x3391, 0x398d, 0x32a6, 0x39c8, 0x31d6, 0x39fa, 0x3121, 0x3a22, 0x3082, 0x3a43, 0x2ff0, 0x3a5c, 0x2f01, 0x3a6f, 0x2e32, 0x3a7c, 0x2d7e, 0x3a84, 0x2ce2, 0x3a87, 0x2c5b, 0x3a87, 0x2bcc, 0x3a83, 0x2b00, 0x3a7b, 0x2a4e, 0x3a71, 0x29b3, 0x3a66, 0x292c, 0x3a58, 0x28b4, 0x3a4b, 0x284b, 0x3a3d, 0x27dc, 0x3a2e, 0x2739,
  52106. 0x3709, 0x387c, 0x370a, 0x387b, 0x3710, 0x3874, 0x3720, 0x385f, 0x373d, 0x3834, 0x376a, 0x37e1, 0x37ac, 0x3732, 0x3805, 0x3675, 0x383f, 0x35bc, 0x3883, 0x3511, 0x38cb, 0x3476, 0x3912, 0x33d8, 0x3955, 0x32e2, 0x3991, 0x3208, 0x39c6, 0x3149, 0x39f1, 0x30a1, 0x3a15, 0x300f, 0x3a30, 0x2f21, 0x3a44, 0x2e45, 0x3a51, 0x2d87, 0x3a59, 0x2ce2, 0x3a5b, 0x2c53, 0x3a58, 0x2bb0, 0x3a52, 0x2ada, 0x3a49, 0x2a1f, 0x3a40, 0x297d, 0x3a34, 0x28f0, 0x3a25, 0x2874, 0x3a13, 0x2807, 0x3a00, 0x274e, 0x39eb, 0x26a6, 0x39d5, 0x2611,
  52107. 0x3840, 0x3780, 0x3840, 0x377e, 0x3842, 0x3776, 0x3846, 0x375e, 0x384f, 0x372a, 0x385b, 0x36d3, 0x386c, 0x3659, 0x3885, 0x35c7, 0x38a8, 0x352d, 0x38d4, 0x3497, 0x3906, 0x340c, 0x393b, 0x331a, 0x3970, 0x323a, 0x39a0, 0x3172, 0x39cb, 0x30c3, 0x39ef, 0x302a, 0x3a0c, 0x2f4a, 0x3a21, 0x2e63, 0x3a2f, 0x2d9b, 0x3a37, 0x2ced, 0x3a39, 0x2c57, 0x3a37, 0x2baa, 0x3a34, 0x2ac9, 0x3a2c, 0x2a05, 0x3a20, 0x295d, 0x3a11, 0x28ca, 0x39ff, 0x2849, 0x39eb, 0x27b2, 0x39d5, 0x26ed, 0x39be, 0x2640, 0x39a5, 0x25aa, 0x398b, 0x2523,
  52108. 0x38e2, 0x363b, 0x38e2, 0x363b, 0x38e3, 0x3635, 0x38e6, 0x3626, 0x38ea, 0x3606, 0x38f0, 0x35cd, 0x38f8, 0x3579, 0x3903, 0x350e, 0x3915, 0x3495, 0x392d, 0x3418, 0x394c, 0x3340, 0x3970, 0x3261, 0x3995, 0x3197, 0x39b8, 0x30e4, 0x39d8, 0x3046, 0x39f3, 0x2f76, 0x3a08, 0x2e86, 0x3a16, 0x2db5, 0x3a1e, 0x2cff, 0x3a22, 0x2c61, 0x3a24, 0x2bb3, 0x3a20, 0x2ac7, 0x3a17, 0x29fc, 0x3a0a, 0x294c, 0x39fa, 0x28b2, 0x39e7, 0x282e, 0x39d1, 0x2773, 0x39b9, 0x26a9, 0x399f, 0x25fa, 0x3985, 0x255f, 0x3968, 0x24d6, 0x394a, 0x245d,
  52109. 0x396e, 0x3524, 0x396e, 0x3524, 0x396e, 0x3520, 0x396f, 0x3517, 0x3971, 0x3502, 0x3973, 0x34dd, 0x3975, 0x34a5, 0x3978, 0x3458, 0x397e, 0x33f9, 0x3987, 0x3332, 0x3997, 0x326b, 0x39aa, 0x31ac, 0x39c0, 0x30fb, 0x39d7, 0x305c, 0x39eb, 0x2f9e, 0x39fc, 0x2ea7, 0x3a07, 0x2dcf, 0x3a0f, 0x2d13, 0x3a16, 0x2c70, 0x3a17, 0x2bc4, 0x3a14, 0x2ad0, 0x3a0a, 0x29fc, 0x39fd, 0x2945, 0x39ed, 0x28a6, 0x39d9, 0x281d, 0x39c2, 0x274a, 0x39a9, 0x267c, 0x398e, 0x25c7, 0x3971, 0x2528, 0x3952, 0x249e, 0x3931, 0x2425, 0x3910, 0x2374,
  52110. 0x39e5, 0x3436, 0x39e5, 0x3435, 0x39e5, 0x3434, 0x39e5, 0x342e, 0x39e5, 0x3420, 0x39e5, 0x3408, 0x39e3, 0x33c4, 0x39e1, 0x3359, 0x39df, 0x32d3, 0x39de, 0x323a, 0x39e1, 0x319a, 0x39e7, 0x30fb, 0x39f0, 0x3065, 0x39f9, 0x2fb6, 0x3a02, 0x2ec0, 0x3a08, 0x2de6, 0x3a0d, 0x2d26, 0x3a12, 0x2c7e, 0x3a13, 0x2bda, 0x3a0e, 0x2adc, 0x3a05, 0x2a02, 0x39f8, 0x2945, 0x39e7, 0x28a1, 0x39d3, 0x2813, 0x39bc, 0x2730, 0x39a2, 0x265c, 0x3985, 0x25a3, 0x3966, 0x2501, 0x3945, 0x2475, 0x3923, 0x23f3, 0x3901, 0x231c, 0x38dd, 0x225e,
  52111. 0x3a4b, 0x32d6, 0x3a4a, 0x32d6, 0x3a4a, 0x32d4, 0x3a4a, 0x32cc, 0x3a48, 0x32bb, 0x3a47, 0x329d, 0x3a43, 0x326b, 0x3a3d, 0x3222, 0x3a36, 0x31c2, 0x3a2e, 0x314f, 0x3a28, 0x30d2, 0x3a23, 0x3052, 0x3a20, 0x2fab, 0x3a1e, 0x2ec2, 0x3a1b, 0x2def, 0x3a19, 0x2d31, 0x3a1a, 0x2c89, 0x3a18, 0x2beb, 0x3a11, 0x2aea, 0x3a07, 0x2a0a, 0x39fa, 0x2948, 0x39e9, 0x28a1, 0x39d4, 0x280f, 0x39bd, 0x2721, 0x39a2, 0x2647, 0x3985, 0x258b, 0x3964, 0x24e5, 0x3942, 0x2455, 0x391f, 0x23b3, 0x38fb, 0x22d8, 0x38d4, 0x2219, 0x38ad, 0x2172,
  52112. 0x3aa0, 0x3180, 0x3aa0, 0x3180, 0x3aa0, 0x317f, 0x3a9f, 0x317b, 0x3a9d, 0x3170, 0x3a99, 0x315d, 0x3a95, 0x313d, 0x3a8d, 0x310c, 0x3a82, 0x30ca, 0x3a76, 0x3077, 0x3a69, 0x3019, 0x3a5c, 0x2f68, 0x3a4f, 0x2e9e, 0x3a42, 0x2dde, 0x3a37, 0x2d2b, 0x3a30, 0x2c89, 0x3a29, 0x2bef, 0x3a1f, 0x2af0, 0x3a12, 0x2a0f, 0x3a03, 0x294a, 0x39f1, 0x28a0, 0x39dc, 0x280c, 0x39c5, 0x2717, 0x39a9, 0x2638, 0x398b, 0x2578, 0x396a, 0x24d0, 0x3947, 0x243f, 0x3923, 0x2380, 0x38fc, 0x22a4, 0x38d4, 0x21e4, 0x38ac, 0x213c, 0x3883, 0x20a8,
  52113. 0x3ae8, 0x3062, 0x3ae8, 0x3062, 0x3ae7, 0x3061, 0x3ae6, 0x305f, 0x3ae4, 0x305a, 0x3ae0, 0x304f, 0x3ada, 0x303b, 0x3ad1, 0x301b, 0x3ac5, 0x2fdd, 0x3ab6, 0x2f6a, 0x3aa4, 0x2ede, 0x3a91, 0x2e45, 0x3a7c, 0x2da5, 0x3a67, 0x2d0a, 0x3a57, 0x2c77, 0x3a48, 0x2bdc, 0x3a38, 0x2ae5, 0x3a27, 0x2a0a, 0x3a16, 0x2947, 0x3a02, 0x289d, 0x39eb, 0x2808, 0x39d3, 0x270d, 0x39b6, 0x262b, 0x3997, 0x256a, 0x3976, 0x24bf, 0x3952, 0x242b, 0x392d, 0x2358, 0x3904, 0x227a, 0x38db, 0x21b8, 0x38b2, 0x2110, 0x3887, 0x207d, 0x385b, 0x1ff6,
  52114. 0x3b23, 0x2ee8, 0x3b23, 0x2ee8, 0x3b22, 0x2ee8, 0x3b21, 0x2ee7, 0x3b1f, 0x2ee3, 0x3b1a, 0x2ed6, 0x3b14, 0x2ec1, 0x3b0b, 0x2e99, 0x3afe, 0x2e60, 0x3aee, 0x2e12, 0x3ad8, 0x2dad, 0x3ac1, 0x2d3d, 0x3aa5, 0x2cc3, 0x3a8b, 0x2c48, 0x3a76, 0x2ba2, 0x3a60, 0x2ac0, 0x3a49, 0x29f2, 0x3a32, 0x2938, 0x3a1b, 0x2893, 0x3a02, 0x27ff, 0x39e8, 0x26ff, 0x39ca, 0x261e, 0x39aa, 0x255b, 0x3988, 0x24b0, 0x3964, 0x241c, 0x393d, 0x2336, 0x3913, 0x2257, 0x38e9, 0x2195, 0x38be, 0x20eb, 0x3891, 0x2059, 0x3864, 0x1fae, 0x3837, 0x1ecd,
  52115. 0x3b54, 0x2d61, 0x3b54, 0x2d61, 0x3b53, 0x2d61, 0x3b52, 0x2d62, 0x3b4f, 0x2d61, 0x3b4b, 0x2d5c, 0x3b45, 0x2d51, 0x3b3b, 0x2d3d, 0x3b2e, 0x2d1a, 0x3b1d, 0x2ce7, 0x3b06, 0x2ca3, 0x3aeb, 0x2c52, 0x3acb, 0x2bee, 0x3ab0, 0x2b31, 0x3a94, 0x2a74, 0x3a77, 0x29bf, 0x3a5a, 0x2915, 0x3a3f, 0x287a, 0x3a22, 0x27de, 0x3a05, 0x26e4, 0x39e5, 0x2609, 0x39c3, 0x2547, 0x39a0, 0x249f, 0x397b, 0x240c, 0x3953, 0x2314, 0x3928, 0x2238, 0x38fd, 0x2175, 0x38d0, 0x20cb, 0x38a2, 0x2038, 0x3873, 0x1f71, 0x3844, 0x1e90, 0x3815, 0x1dce,
  52116. 0x3b7c, 0x2c22, 0x3b7c, 0x2c22, 0x3b7b, 0x2c23, 0x3b7a, 0x2c25, 0x3b77, 0x2c27, 0x3b73, 0x2c26, 0x3b6d, 0x2c23, 0x3b64, 0x2c1a, 0x3b57, 0x2c07, 0x3b46, 0x2bd1, 0x3b2e, 0x2b79, 0x3b0f, 0x2b07, 0x3aef, 0x2a86, 0x3ad1, 0x29f8, 0x3ab0, 0x2967, 0x3a8e, 0x28d7, 0x3a6d, 0x284e, 0x3a4c, 0x279f, 0x3a2b, 0x26b7, 0x3a08, 0x25e5, 0x39e4, 0x252c, 0x39be, 0x2488, 0x3998, 0x23f0, 0x396f, 0x22f2, 0x3943, 0x2215, 0x3917, 0x2155, 0x38e8, 0x20ae, 0x38b9, 0x201c, 0x3888, 0x1f38, 0x3857, 0x1e5a, 0x3826, 0x1d9a, 0x37eb, 0x1cf0,
  52117. 0x3b9c, 0x2a43, 0x3b9c, 0x2a43, 0x3b9b, 0x2a46, 0x3b9a, 0x2a4a, 0x3b98, 0x2a50, 0x3b93, 0x2a54, 0x3b8e, 0x2a59, 0x3b85, 0x2a56, 0x3b79, 0x2a45, 0x3b67, 0x2a24, 0x3b4f, 0x29ee, 0x3b2f, 0x29a4, 0x3b10, 0x294b, 0x3aef, 0x28e5, 0x3ac9, 0x2877, 0x3aa4, 0x2809, 0x3a7e, 0x2739, 0x3a59, 0x266d, 0x3a34, 0x25af, 0x3a0c, 0x2503, 0x39e4, 0x2468, 0x39bb, 0x23bb, 0x3990, 0x22c6, 0x3963, 0x21f0, 0x3936, 0x2133, 0x3906, 0x208f, 0x38d5, 0x1ffd, 0x38a3, 0x1f04, 0x3870, 0x1e28, 0x383d, 0x1d69, 0x380b, 0x1cc3, 0x37b0, 0x1c32,
  52118. 0x3bb5, 0x28aa, 0x3bb5, 0x28ab, 0x3bb5, 0x28ad, 0x3bb4, 0x28b2, 0x3bb2, 0x28b9, 0x3bae, 0x28c2, 0x3ba8, 0x28ca, 0x3ba0, 0x28d1, 0x3b94, 0x28cd, 0x3b83, 0x28c1, 0x3b6a, 0x28a3, 0x3b4b, 0x2876, 0x3b2d, 0x283d, 0x3b09, 0x27ea, 0x3ae1, 0x274b, 0x3ab9, 0x26a6, 0x3a8f, 0x25fe, 0x3a67, 0x255d, 0x3a3d, 0x24c5, 0x3a11, 0x2439, 0x39e6, 0x2371, 0x39b9, 0x228d, 0x398a, 0x21c1, 0x395a, 0x210b, 0x3929, 0x206c, 0x38f7, 0x1fc1, 0x38c3, 0x1ecb, 0x388f, 0x1df6, 0x385a, 0x1d3a, 0x3825, 0x1c99, 0x37e1, 0x1c08, 0x3779, 0x1b1b,
  52119. 0x3bc9, 0x26d3, 0x3bc9, 0x26d4, 0x3bc9, 0x26d9, 0x3bc8, 0x26e3, 0x3bc6, 0x26ef, 0x3bc2, 0x2705, 0x3bbd, 0x271a, 0x3bb6, 0x2731, 0x3baa, 0x273c, 0x3b9a, 0x273d, 0x3b81, 0x2726, 0x3b65, 0x26f7, 0x3b46, 0x26af, 0x3b20, 0x2650, 0x3af7, 0x25e1, 0x3acd, 0x256a, 0x3aa1, 0x24eb, 0x3a75, 0x246f, 0x3a46, 0x23ee, 0x3a17, 0x230d, 0x39e9, 0x223e, 0x39b7, 0x2183, 0x3985, 0x20d8, 0x3953, 0x2043, 0x391e, 0x1f7a, 0x38e9, 0x1e8d, 0x38b3, 0x1dbf, 0x387c, 0x1d0b, 0x3845, 0x1c6c, 0x380e, 0x1bc4, 0x37b0, 0x1ad2, 0x3745, 0x19fd,
  52120. 0x3bd9, 0x24e4, 0x3bd9, 0x24e5, 0x3bd9, 0x24e8, 0x3bd8, 0x24f2, 0x3bd5, 0x24fe, 0x3bd2, 0x2512, 0x3bce, 0x252b, 0x3bc6, 0x2544, 0x3bbc, 0x255a, 0x3bac, 0x256b, 0x3b93, 0x2569, 0x3b7a, 0x2557, 0x3b5b, 0x252f, 0x3b34, 0x24f7, 0x3b0c, 0x24ad, 0x3adf, 0x2458, 0x3ab1, 0x23f8, 0x3a82, 0x233f, 0x3a4f, 0x2286, 0x3a1e, 0x21d5, 0x39eb, 0x2130, 0x39b6, 0x2098, 0x3982, 0x200e, 0x394b, 0x1f25, 0x3914, 0x1e45, 0x38dc, 0x1d83, 0x38a3, 0x1cd6, 0x386b, 0x1c3d, 0x3831, 0x1b71, 0x37f2, 0x1a87, 0x3782, 0x19bc, 0x3714, 0x1909,
  52121. 0x3be5, 0x22d8, 0x3be5, 0x22d9, 0x3be4, 0x22df, 0x3be4, 0x22ef, 0x3be1, 0x2305, 0x3bde, 0x232a, 0x3bda, 0x2358, 0x3bd4, 0x2392, 0x3bcb, 0x23ca, 0x3bbb, 0x23f4, 0x3ba3, 0x2405, 0x3b8c, 0x2405, 0x3b6c, 0x23ec, 0x3b47, 0x23ae, 0x3b1d, 0x2353, 0x3af0, 0x22e2, 0x3ac0, 0x2261, 0x3a8e, 0x21d9, 0x3a5a, 0x214e, 0x3a26, 0x20c7, 0x39ee, 0x2045, 0x39b7, 0x1f97, 0x397f, 0x1eba, 0x3945, 0x1df0, 0x390b, 0x1d3a, 0x38d0, 0x1c9a, 0x3895, 0x1c0a, 0x385a, 0x1b18, 0x381f, 0x1a39, 0x37c9, 0x1975, 0x3756, 0x18cc, 0x36e6, 0x1836,
  52122. 0x3bed, 0x20a8, 0x3bed, 0x20a9, 0x3bed, 0x20ae, 0x3bed, 0x20bb, 0x3beb, 0x20cf, 0x3be8, 0x20ef, 0x3be4, 0x2119, 0x3bde, 0x214f, 0x3bd6, 0x2189, 0x3bc6, 0x21b8, 0x3bb1, 0x21de, 0x3b9a, 0x21f2, 0x3b7b, 0x21f2, 0x3b57, 0x21d8, 0x3b2d, 0x21a4, 0x3b00, 0x215f, 0x3acf, 0x2108, 0x3a99, 0x20a8, 0x3a64, 0x2043, 0x3a2c, 0x1fba, 0x39f2, 0x1ef3, 0x39b8, 0x1e36, 0x397c, 0x1d86, 0x3940, 0x1ce5, 0x3903, 0x1c52, 0x38c6, 0x1b9e, 0x3888, 0x1ab3, 0x384a, 0x19e4, 0x380e, 0x192b, 0x37a3, 0x188b, 0x372d, 0x17f7, 0x36ba, 0x1701,
  52123. 0x3bf4, 0x1e23, 0x3bf4, 0x1e25, 0x3bf4, 0x1e2d, 0x3bf3, 0x1e41, 0x3bf1, 0x1e64, 0x3bef, 0x1e9c, 0x3beb, 0x1ee1, 0x3be6, 0x1f40, 0x3bde, 0x1fa7, 0x3bce, 0x2001, 0x3bbd, 0x202f, 0x3ba6, 0x204e, 0x3b88, 0x205f, 0x3b64, 0x205b, 0x3b3b, 0x2044, 0x3b0e, 0x201f, 0x3adb, 0x1fcf, 0x3aa6, 0x1f4e, 0x3a6e, 0x1ec1, 0x3a33, 0x1e2b, 0x39f7, 0x1d95, 0x39ba, 0x1d06, 0x397b, 0x1c7d, 0x393c, 0x1bfc, 0x38fc, 0x1b13, 0x38bc, 0x1a40, 0x387c, 0x1983, 0x383c, 0x18da, 0x37fa, 0x1842, 0x377f, 0x177f, 0x3706, 0x1695, 0x3691, 0x15c8,
  52124. 0x3bf8, 0x1bca, 0x3bf8, 0x1bcc, 0x3bf8, 0x1bd8, 0x3bf8, 0x1bf7, 0x3bf6, 0x1c1b, 0x3bf4, 0x1c45, 0x3bf1, 0x1c83, 0x3bec, 0x1cce, 0x3be4, 0x1d21, 0x3bd5, 0x1d78, 0x3bc5, 0x1dd1, 0x3bb0, 0x1e17, 0x3b93, 0x1e4a, 0x3b70, 0x1e5f, 0x3b48, 0x1e57, 0x3b1b, 0x1e35, 0x3ae7, 0x1df6, 0x3ab2, 0x1da4, 0x3a77, 0x1d44, 0x3a3a, 0x1cdb, 0x39fc, 0x1c6e, 0x39bb, 0x1c03, 0x397a, 0x1b35, 0x3938, 0x1a72, 0x38f5, 0x19bb, 0x38b3, 0x1914, 0x3870, 0x187d, 0x382e, 0x17eb, 0x37db, 0x16f9, 0x375c, 0x1621, 0x36e1, 0x1565, 0x3669, 0x14be,
  52125. 0x3bfb, 0x18b9, 0x3bfb, 0x18ba, 0x3bfb, 0x18c3, 0x3bfb, 0x18da, 0x3bf9, 0x190a, 0x3bf7, 0x1948, 0x3bf5, 0x19ac, 0x3bf0, 0x1a20, 0x3be9, 0x1ab3, 0x3bdb, 0x1b49, 0x3bcd, 0x1be6, 0x3bb7, 0x1c34, 0x3b9c, 0x1c6d, 0x3b7a, 0x1c8e, 0x3b54, 0x1c9e, 0x3b26, 0x1c96, 0x3af2, 0x1c75, 0x3abc, 0x1c47, 0x3a80, 0x1c09, 0x3a42, 0x1b85, 0x3a01, 0x1aec, 0x39be, 0x1a50, 0x397a, 0x19b5, 0x3935, 0x1921, 0x38f0, 0x1895, 0x38aa, 0x1814, 0x3866, 0x173a, 0x3821, 0x1665, 0x37be, 0x15a4, 0x373c, 0x14f9, 0x36be, 0x1460, 0x3644, 0x13b3,
  52126. 0x3bfd, 0x156b, 0x3bfd, 0x156c, 0x3bfd, 0x1578, 0x3bfd, 0x1598, 0x3bfc, 0x15dd, 0x3bfa, 0x163c, 0x3bf7, 0x16cb, 0x3bf3, 0x177b, 0x3beb, 0x1833, 0x3be0, 0x18ad, 0x3bd2, 0x192e, 0x3bbd, 0x19a6, 0x3ba4, 0x1a0c, 0x3b83, 0x1a5a, 0x3b5d, 0x1a8c, 0x3b30, 0x1a9b, 0x3afd, 0x1a86, 0x3ac6, 0x1a5c, 0x3a89, 0x1a11, 0x3a49, 0x19b7, 0x3a06, 0x194f, 0x39c1, 0x18e3, 0x397a, 0x1873, 0x3933, 0x1805, 0x38eb, 0x173a, 0x38a3, 0x1676, 0x385c, 0x15bf, 0x3816, 0x1519, 0x37a2, 0x1482, 0x371d, 0x13f7, 0x369c, 0x1306, 0x3620, 0x1231,
  52127. 0x3bff, 0x11cb, 0x3bff, 0x11cd, 0x3bfe, 0x11dd, 0x3bfe, 0x1219, 0x3bfd, 0x126b, 0x3bfb, 0x12e9, 0x3bf9, 0x13c5, 0x3bf5, 0x1460, 0x3bee, 0x150f, 0x3be3, 0x15c9, 0x3bd6, 0x168a, 0x3bc3, 0x174f, 0x3baa, 0x1806, 0x3b8b, 0x184f, 0x3b66, 0x1888, 0x3b39, 0x18a6, 0x3b07, 0x18ad, 0x3acf, 0x189c, 0x3a92, 0x1876, 0x3a50, 0x1840, 0x3a0c, 0x17fd, 0x39c4, 0x176a, 0x397b, 0x16ce, 0x3931, 0x1634, 0x38e6, 0x1599, 0x389c, 0x1508, 0x3852, 0x147f, 0x380a, 0x1401, 0x3788, 0x131c, 0x36ff, 0x124a, 0x367c, 0x1190, 0x35fe, 0x10ea,
  52128. 0x3bff, 0x0daa, 0x3bff, 0x0dad, 0x3bff, 0x0dc0, 0x3bff, 0x0e0e, 0x3bfe, 0x0e87, 0x3bfc, 0x0f14, 0x3bfb, 0x1029, 0x3bf7, 0x10d1, 0x3bf0, 0x11d3, 0x3be6, 0x12c9, 0x3bd9, 0x13fc, 0x3bc7, 0x1499, 0x3bb0, 0x152a, 0x3b92, 0x15ab, 0x3b6e, 0x1615, 0x3b42, 0x165a, 0x3b10, 0x1681, 0x3ad8, 0x1683, 0x3a9a, 0x1665, 0x3a57, 0x1629, 0x3a11, 0x15dd, 0x39c8, 0x1580, 0x397c, 0x1518, 0x3930, 0x14ae, 0x38e3, 0x1441, 0x3896, 0x13b1, 0x384a, 0x12e9, 0x37ff, 0x122f, 0x376f, 0x1182, 0x36e3, 0x10e5, 0x365e, 0x1057, 0x35de, 0x0fac,
  52129. 0x3c00, 0x08ea, 0x3c00, 0x08ed, 0x3c00, 0x0902, 0x3c00, 0x0961, 0x3bff, 0x09f3, 0x3bfd, 0x0abc, 0x3bfb, 0x0c1f, 0x3bf8, 0x0d15, 0x3bf1, 0x0e5b, 0x3be8, 0x0fb4, 0x3bdc, 0x10b0, 0x3bcb, 0x1190, 0x3bb5, 0x126c, 0x3b97, 0x132c, 0x3b74, 0x13de, 0x3b4a, 0x1432, 0x3b18, 0x145e, 0x3ae0, 0x1472, 0x3aa2, 0x146f, 0x3a5f, 0x1456, 0x3a17, 0x142e, 0x39cc, 0x13ee, 0x397e, 0x136b, 0x392f, 0x12e1, 0x38df, 0x124f, 0x3890, 0x11bd, 0x3842, 0x1131, 0x37eb, 0x10ac, 0x3757, 0x102e, 0x36c9, 0x0f76, 0x3640, 0x0ea3, 0x35bf, 0x0de4,
  52130. 0x3c00, 0x039b, 0x3c00, 0x039d, 0x3c00, 0x03b2, 0x3c00, 0x041c, 0x3bff, 0x04be, 0x3bfd, 0x05d6, 0x3bfc, 0x0764, 0x3bf8, 0x08e2, 0x3bf2, 0x0a67, 0x3bea, 0x0c1b, 0x3bde, 0x0d41, 0x3bcd, 0x0e5f, 0x3bb8, 0x0f8c, 0x3b9c, 0x1057, 0x3b7a, 0x10e5, 0x3b51, 0x1155, 0x3b20, 0x11a5, 0x3ae8, 0x11da, 0x3aaa, 0x11ef, 0x3a66, 0x11e5, 0x3a1d, 0x11c1, 0x39d0, 0x1185, 0x3980, 0x113b, 0x392e, 0x10e5, 0x38dc, 0x1087, 0x388b, 0x1028, 0x383b, 0x0f94, 0x37d9, 0x0edb, 0x3741, 0x0e2c, 0x36af, 0x0d89, 0x3625, 0x0cf2, 0x35a1, 0x0c69,
  52131. 0x3c00, 0x0107, 0x3c00, 0x0108, 0x3c00, 0x0110, 0x3c00, 0x0145, 0x3bff, 0x0197, 0x3bfe, 0x0224, 0x3bfc, 0x030c, 0x3bf8, 0x0478, 0x3bf3, 0x062c, 0x3beb, 0x0833, 0x3be0, 0x0979, 0x3bd0, 0x0aeb, 0x3bbc, 0x0c3d, 0x3ba0, 0x0d01, 0x3b80, 0x0dbd, 0x3b57, 0x0e69, 0x3b27, 0x0eeb, 0x3af0, 0x0f53, 0x3ab1, 0x0f8a, 0x3a6c, 0x0f9f, 0x3a22, 0x0f8b, 0x39d4, 0x0f5b, 0x3982, 0x0f0f, 0x392f, 0x0eac, 0x38da, 0x0e3d, 0x3886, 0x0dc9, 0x3834, 0x0d51, 0x37c7, 0x0cd9, 0x372c, 0x0c65, 0x3697, 0x0bef, 0x360a, 0x0b20, 0x3585, 0x0a62,
  52132. 0x3c00, 0x0031, 0x3c00, 0x0031, 0x3c00, 0x0034, 0x3c00, 0x004b, 0x3bff, 0x006f, 0x3bfe, 0x00c9, 0x3bfc, 0x011b, 0x3bf9, 0x0207, 0x3bf4, 0x02d6, 0x3bec, 0x0415, 0x3be1, 0x0587, 0x3bd2, 0x0703, 0x3bbf, 0x087d, 0x3ba5, 0x096a, 0x3b85, 0x0a59, 0x3b5d, 0x0b32, 0x3b2e, 0x0bee, 0x3af7, 0x0c44, 0x3ab8, 0x0c7c, 0x3a73, 0x0c9c, 0x3a28, 0x0ca4, 0x39d8, 0x0c98, 0x3985, 0x0c77, 0x392f, 0x0c4a, 0x38d9, 0x0c10, 0x3882, 0x0ba0, 0x382e, 0x0b14, 0x37b6, 0x0a84, 0x3717, 0x09f5, 0x3680, 0x0969, 0x35f0, 0x08e6, 0x356a, 0x086a,
  52133. 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x0004, 0x3c00, 0x000d, 0x3bff, 0x0021, 0x3bfe, 0x003b, 0x3bfd, 0x0070, 0x3bf9, 0x00c7, 0x3bf4, 0x012e, 0x3bed, 0x01c8, 0x3be3, 0x0274, 0x3bd4, 0x033b, 0x3bc1, 0x043a, 0x3ba8, 0x0534, 0x3b89, 0x0641, 0x3b62, 0x073b, 0x3b34, 0x0815, 0x3afd, 0x087c, 0x3abf, 0x08d0, 0x3a7a, 0x090a, 0x3a2e, 0x092c, 0x39dd, 0x0936, 0x3988, 0x0928, 0x3930, 0x0907, 0x38d7, 0x08d7, 0x387f, 0x089b, 0x3828, 0x0855, 0x37a7, 0x080b, 0x3704, 0x077b, 0x366a, 0x06e1, 0x35d8, 0x0649, 0x3550, 0x05b8,
  52134. 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0000, 0x3c00, 0x0003, 0x3bff, 0x0012, 0x3bfe, 0x001a, 0x3bfd, 0x0035, 0x3bfa, 0x0050, 0x3bf4, 0x0061, 0x3bed, 0x00a5, 0x3be4, 0x00ee, 0x3bd6, 0x0146, 0x3bc3, 0x01ab, 0x3bab, 0x0211, 0x3b8d, 0x028e, 0x3b67, 0x0303, 0x3b39, 0x0375, 0x3b04, 0x03e2, 0x3ac6, 0x0441, 0x3a80, 0x0492, 0x3a34, 0x04cd, 0x39e1, 0x04f2, 0x398b, 0x0504, 0x3931, 0x0502, 0x38d6, 0x04ec, 0x387c, 0x04c7, 0x3822, 0x0496, 0x3798, 0x045c, 0x36f2, 0x041a, 0x3655, 0x03d5, 0x35c1, 0x038e, 0x3537, 0x0347
  52135. ] );
  52136. let lut = null;
  52137. function getDFGLUT() {
  52138. if ( lut === null ) {
  52139. lut = new DataTexture( DATA, 32, 32, RGFormat, HalfFloatType );
  52140. lut.name = 'DFG_LUT';
  52141. lut.minFilter = LinearFilter;
  52142. lut.magFilter = LinearFilter;
  52143. lut.wrapS = ClampToEdgeWrapping;
  52144. lut.wrapT = ClampToEdgeWrapping;
  52145. lut.generateMipmaps = false;
  52146. lut.needsUpdate = true;
  52147. }
  52148. return lut;
  52149. }
  52150. /**
  52151. * This renderer uses WebGL 2 to display scenes.
  52152. *
  52153. * WebGL 1 is not supported since `r163`.
  52154. */
  52155. class WebGLRenderer {
  52156. /**
  52157. * Constructs a new WebGL renderer.
  52158. *
  52159. * @param {WebGLRenderer~Options} [parameters] - The configuration parameter.
  52160. */
  52161. constructor( parameters = {} ) {
  52162. const {
  52163. canvas = createCanvasElement(),
  52164. context = null,
  52165. depth = true,
  52166. stencil = false,
  52167. alpha = false,
  52168. antialias = false,
  52169. premultipliedAlpha = true,
  52170. preserveDrawingBuffer = false,
  52171. powerPreference = 'default',
  52172. failIfMajorPerformanceCaveat = false,
  52173. reversedDepthBuffer = false,
  52174. } = parameters;
  52175. /**
  52176. * This flag can be used for type testing.
  52177. *
  52178. * @type {boolean}
  52179. * @readonly
  52180. * @default true
  52181. */
  52182. this.isWebGLRenderer = true;
  52183. let _alpha;
  52184. if ( context !== null ) {
  52185. if ( typeof WebGLRenderingContext !== 'undefined' && context instanceof WebGLRenderingContext ) {
  52186. throw new Error( 'THREE.WebGLRenderer: WebGL 1 is not supported since r163.' );
  52187. }
  52188. _alpha = context.getContextAttributes().alpha;
  52189. } else {
  52190. _alpha = alpha;
  52191. }
  52192. const INTEGER_FORMATS = new Set( [
  52193. RGBAIntegerFormat,
  52194. RGIntegerFormat,
  52195. RedIntegerFormat
  52196. ] );
  52197. const UNSIGNED_TYPES = new Set( [
  52198. UnsignedByteType,
  52199. UnsignedIntType,
  52200. UnsignedShortType,
  52201. UnsignedInt248Type,
  52202. UnsignedShort4444Type,
  52203. UnsignedShort5551Type
  52204. ] );
  52205. const uintClearColor = new Uint32Array( 4 );
  52206. const intClearColor = new Int32Array( 4 );
  52207. let currentRenderList = null;
  52208. let currentRenderState = null;
  52209. // render() can be called from within a callback triggered by another render.
  52210. // We track this so that the nested render call gets its list and state isolated from the parent render call.
  52211. const renderListStack = [];
  52212. const renderStateStack = [];
  52213. // public properties
  52214. /**
  52215. * A canvas where the renderer draws its output.This is automatically created by the renderer
  52216. * in the constructor (if not provided already); you just need to add it to your page like so:
  52217. * ```js
  52218. * document.body.appendChild( renderer.domElement );
  52219. * ```
  52220. *
  52221. * @type {HTMLCanvasElement|OffscreenCanvas}
  52222. */
  52223. this.domElement = canvas;
  52224. /**
  52225. * A object with debug configuration settings.
  52226. *
  52227. * - `checkShaderErrors`: If it is `true`, defines whether material shader programs are
  52228. * checked for errors during compilation and linkage process. It may be useful to disable
  52229. * this check in production for performance gain. It is strongly recommended to keep these
  52230. * checks enabled during development. If the shader does not compile and link - it will not
  52231. * work and associated material will not render.
  52232. * - `onShaderError(gl, program, glVertexShader,glFragmentShader)`: A callback function that
  52233. * can be used for custom error reporting. The callback receives the WebGL context, an instance
  52234. * of WebGLProgram as well two instances of WebGLShader representing the vertex and fragment shader.
  52235. * Assigning a custom function disables the default error reporting.
  52236. *
  52237. * @type {Object}
  52238. */
  52239. this.debug = {
  52240. /**
  52241. * Enables error checking and reporting when shader programs are being compiled.
  52242. * @type {boolean}
  52243. */
  52244. checkShaderErrors: true,
  52245. /**
  52246. * Callback for custom error reporting.
  52247. * @type {?Function}
  52248. */
  52249. onShaderError: null
  52250. };
  52251. // clearing
  52252. /**
  52253. * Whether the renderer should automatically clear its output before rendering a frame or not.
  52254. *
  52255. * @type {boolean}
  52256. * @default true
  52257. */
  52258. this.autoClear = true;
  52259. /**
  52260. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52261. * the color buffer or not.
  52262. *
  52263. * @type {boolean}
  52264. * @default true
  52265. */
  52266. this.autoClearColor = true;
  52267. /**
  52268. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52269. * the depth buffer or not.
  52270. *
  52271. * @type {boolean}
  52272. * @default true
  52273. */
  52274. this.autoClearDepth = true;
  52275. /**
  52276. * If {@link WebGLRenderer#autoClear} set to `true`, whether the renderer should clear
  52277. * the stencil buffer or not.
  52278. *
  52279. * @type {boolean}
  52280. * @default true
  52281. */
  52282. this.autoClearStencil = true;
  52283. // scene graph
  52284. /**
  52285. * Whether the renderer should sort objects or not.
  52286. *
  52287. * Note: Sorting is used to attempt to properly render objects that have some
  52288. * degree of transparency. By definition, sorting objects may not work in all
  52289. * cases. Depending on the needs of application, it may be necessary to turn
  52290. * off sorting and use other methods to deal with transparency rendering e.g.
  52291. * manually determining each object's rendering order.
  52292. *
  52293. * @type {boolean}
  52294. * @default true
  52295. */
  52296. this.sortObjects = true;
  52297. // user-defined clipping
  52298. /**
  52299. * User-defined clipping planes specified in world space. These planes apply globally.
  52300. * Points in space whose dot product with the plane is negative are cut away.
  52301. *
  52302. * @type {Array<Plane>}
  52303. */
  52304. this.clippingPlanes = [];
  52305. /**
  52306. * Whether the renderer respects object-level clipping planes or not.
  52307. *
  52308. * @type {boolean}
  52309. * @default false
  52310. */
  52311. this.localClippingEnabled = false;
  52312. // tone mapping
  52313. /**
  52314. * The tone mapping technique of the renderer.
  52315. *
  52316. * @type {(NoToneMapping|LinearToneMapping|ReinhardToneMapping|CineonToneMapping|ACESFilmicToneMapping|CustomToneMapping|AgXToneMapping|NeutralToneMapping)}
  52317. * @default NoToneMapping
  52318. */
  52319. this.toneMapping = NoToneMapping;
  52320. /**
  52321. * Exposure level of tone mapping.
  52322. *
  52323. * @type {number}
  52324. * @default 1
  52325. */
  52326. this.toneMappingExposure = 1.0;
  52327. // transmission
  52328. /**
  52329. * The normalized resolution scale for the transmission render target, measured in percentage
  52330. * of viewport dimensions. Lowering this value can result in significant performance improvements
  52331. * when using {@link MeshPhysicalMaterial#transmission}.
  52332. *
  52333. * @type {number}
  52334. * @default 1
  52335. */
  52336. this.transmissionResolutionScale = 1.0;
  52337. // internal properties
  52338. const _this = this;
  52339. let _isContextLost = false;
  52340. // internal state cache
  52341. this._outputColorSpace = SRGBColorSpace;
  52342. let _currentActiveCubeFace = 0;
  52343. let _currentActiveMipmapLevel = 0;
  52344. let _currentRenderTarget = null;
  52345. let _currentMaterialId = -1;
  52346. let _currentCamera = null;
  52347. const _currentViewport = new Vector4();
  52348. const _currentScissor = new Vector4();
  52349. let _currentScissorTest = null;
  52350. const _currentClearColor = new Color( 0x000000 );
  52351. let _currentClearAlpha = 0;
  52352. //
  52353. let _width = canvas.width;
  52354. let _height = canvas.height;
  52355. let _pixelRatio = 1;
  52356. let _opaqueSort = null;
  52357. let _transparentSort = null;
  52358. const _viewport = new Vector4( 0, 0, _width, _height );
  52359. const _scissor = new Vector4( 0, 0, _width, _height );
  52360. let _scissorTest = false;
  52361. // frustum
  52362. const _frustum = new Frustum();
  52363. // clipping
  52364. let _clippingEnabled = false;
  52365. let _localClippingEnabled = false;
  52366. // camera matrices cache
  52367. const _projScreenMatrix = new Matrix4();
  52368. const _vector3 = new Vector3();
  52369. const _vector4 = new Vector4();
  52370. const _emptyScene = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: true };
  52371. let _renderBackground = false;
  52372. function getTargetPixelRatio() {
  52373. return _currentRenderTarget === null ? _pixelRatio : 1;
  52374. }
  52375. // initialize
  52376. let _gl = context;
  52377. function getContext( contextName, contextAttributes ) {
  52378. return canvas.getContext( contextName, contextAttributes );
  52379. }
  52380. try {
  52381. const contextAttributes = {
  52382. alpha: true,
  52383. depth,
  52384. stencil,
  52385. antialias,
  52386. premultipliedAlpha,
  52387. preserveDrawingBuffer,
  52388. powerPreference,
  52389. failIfMajorPerformanceCaveat,
  52390. };
  52391. // OffscreenCanvas does not have setAttribute, see #22811
  52392. if ( 'setAttribute' in canvas ) canvas.setAttribute( 'data-engine', `three.js r${REVISION}` );
  52393. // event listeners must be registered before WebGL context is created, see #12753
  52394. canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  52395. canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  52396. canvas.addEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52397. if ( _gl === null ) {
  52398. const contextName = 'webgl2';
  52399. _gl = getContext( contextName, contextAttributes );
  52400. if ( _gl === null ) {
  52401. if ( getContext( contextName ) ) {
  52402. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  52403. } else {
  52404. throw new Error( 'Error creating WebGL context.' );
  52405. }
  52406. }
  52407. }
  52408. } catch ( e ) {
  52409. error( 'WebGLRenderer: ' + e.message );
  52410. throw e;
  52411. }
  52412. let extensions, capabilities, state, info;
  52413. let properties, textures, cubemaps, cubeuvmaps, attributes, geometries, objects;
  52414. let programCache, materials, renderLists, renderStates, clipping, shadowMap;
  52415. let background, morphtargets, bufferRenderer, indexedBufferRenderer;
  52416. let utils, bindingStates, uniformsGroups;
  52417. function initGLContext() {
  52418. extensions = new WebGLExtensions( _gl );
  52419. extensions.init();
  52420. utils = new WebGLUtils( _gl, extensions );
  52421. capabilities = new WebGLCapabilities( _gl, extensions, parameters, utils );
  52422. state = new WebGLState( _gl, extensions );
  52423. if ( capabilities.reversedDepthBuffer && reversedDepthBuffer ) {
  52424. state.buffers.depth.setReversed( true );
  52425. }
  52426. info = new WebGLInfo( _gl );
  52427. properties = new WebGLProperties();
  52428. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, info );
  52429. cubemaps = new WebGLCubeMaps( _this );
  52430. cubeuvmaps = new WebGLCubeUVMaps( _this );
  52431. attributes = new WebGLAttributes( _gl );
  52432. bindingStates = new WebGLBindingStates( _gl, attributes );
  52433. geometries = new WebGLGeometries( _gl, attributes, info, bindingStates );
  52434. objects = new WebGLObjects( _gl, geometries, attributes, info );
  52435. morphtargets = new WebGLMorphtargets( _gl, capabilities, textures );
  52436. clipping = new WebGLClipping( properties );
  52437. programCache = new WebGLPrograms( _this, cubemaps, cubeuvmaps, extensions, capabilities, bindingStates, clipping );
  52438. materials = new WebGLMaterials( _this, properties );
  52439. renderLists = new WebGLRenderLists();
  52440. renderStates = new WebGLRenderStates( extensions );
  52441. background = new WebGLBackground( _this, cubemaps, cubeuvmaps, state, objects, _alpha, premultipliedAlpha );
  52442. shadowMap = new WebGLShadowMap( _this, objects, capabilities );
  52443. uniformsGroups = new WebGLUniformsGroups( _gl, info, capabilities, state );
  52444. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, info );
  52445. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, info );
  52446. info.programs = programCache.programs;
  52447. /**
  52448. * Holds details about the capabilities of the current rendering context.
  52449. *
  52450. * @name WebGLRenderer#capabilities
  52451. * @type {WebGLRenderer~Capabilities}
  52452. */
  52453. _this.capabilities = capabilities;
  52454. /**
  52455. * Provides methods for retrieving and testing WebGL extensions.
  52456. *
  52457. * - `get(extensionName:string)`: Used to check whether a WebGL extension is supported
  52458. * and return the extension object if available.
  52459. * - `has(extensionName:string)`: returns `true` if the extension is supported.
  52460. *
  52461. * @name WebGLRenderer#extensions
  52462. * @type {Object}
  52463. */
  52464. _this.extensions = extensions;
  52465. /**
  52466. * Used to track properties of other objects like native WebGL objects.
  52467. *
  52468. * @name WebGLRenderer#properties
  52469. * @type {Object}
  52470. */
  52471. _this.properties = properties;
  52472. /**
  52473. * Manages the render lists of the renderer.
  52474. *
  52475. * @name WebGLRenderer#renderLists
  52476. * @type {Object}
  52477. */
  52478. _this.renderLists = renderLists;
  52479. /**
  52480. * Interface for managing shadows.
  52481. *
  52482. * @name WebGLRenderer#shadowMap
  52483. * @type {WebGLRenderer~ShadowMap}
  52484. */
  52485. _this.shadowMap = shadowMap;
  52486. /**
  52487. * Interface for managing the WebGL state.
  52488. *
  52489. * @name WebGLRenderer#state
  52490. * @type {Object}
  52491. */
  52492. _this.state = state;
  52493. /**
  52494. * Holds a series of statistical information about the GPU memory
  52495. * and the rendering process. Useful for debugging and monitoring.
  52496. *
  52497. * By default these data are reset at each render call but when having
  52498. * multiple render passes per frame (e.g. when using post processing) it can
  52499. * be preferred to reset with a custom pattern. First, set `autoReset` to
  52500. * `false`.
  52501. * ```js
  52502. * renderer.info.autoReset = false;
  52503. * ```
  52504. * Call `reset()` whenever you have finished to render a single frame.
  52505. * ```js
  52506. * renderer.info.reset();
  52507. * ```
  52508. *
  52509. * @name WebGLRenderer#info
  52510. * @type {WebGLRenderer~Info}
  52511. */
  52512. _this.info = info;
  52513. }
  52514. initGLContext();
  52515. // xr
  52516. const xr = new WebXRManager( _this, _gl );
  52517. /**
  52518. * A reference to the XR manager.
  52519. *
  52520. * @type {WebXRManager}
  52521. */
  52522. this.xr = xr;
  52523. /**
  52524. * Returns the rendering context.
  52525. *
  52526. * @return {WebGL2RenderingContext} The rendering context.
  52527. */
  52528. this.getContext = function () {
  52529. return _gl;
  52530. };
  52531. /**
  52532. * Returns the rendering context attributes.
  52533. *
  52534. * @return {WebGLContextAttributes} The rendering context attributes.
  52535. */
  52536. this.getContextAttributes = function () {
  52537. return _gl.getContextAttributes();
  52538. };
  52539. /**
  52540. * Simulates a loss of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52541. */
  52542. this.forceContextLoss = function () {
  52543. const extension = extensions.get( 'WEBGL_lose_context' );
  52544. if ( extension ) extension.loseContext();
  52545. };
  52546. /**
  52547. * Simulates a restore of the WebGL context. This requires support for the `WEBGL_lose_context` extension.
  52548. */
  52549. this.forceContextRestore = function () {
  52550. const extension = extensions.get( 'WEBGL_lose_context' );
  52551. if ( extension ) extension.restoreContext();
  52552. };
  52553. /**
  52554. * Returns the pixel ratio.
  52555. *
  52556. * @return {number} The pixel ratio.
  52557. */
  52558. this.getPixelRatio = function () {
  52559. return _pixelRatio;
  52560. };
  52561. /**
  52562. * Sets the given pixel ratio and resizes the canvas if necessary.
  52563. *
  52564. * @param {number} value - The pixel ratio.
  52565. */
  52566. this.setPixelRatio = function ( value ) {
  52567. if ( value === undefined ) return;
  52568. _pixelRatio = value;
  52569. this.setSize( _width, _height, false );
  52570. };
  52571. /**
  52572. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  52573. *
  52574. * @param {Vector2} target - The method writes the result in this target object.
  52575. * @return {Vector2} The renderer's size in logical pixels.
  52576. */
  52577. this.getSize = function ( target ) {
  52578. return target.set( _width, _height );
  52579. };
  52580. /**
  52581. * Resizes the output canvas to (width, height) with device pixel ratio taken
  52582. * into account, and also sets the viewport to fit that size, starting in (0,
  52583. * 0). Setting `updateStyle` to false prevents any style changes to the output canvas.
  52584. *
  52585. * @param {number} width - The width in logical pixels.
  52586. * @param {number} height - The height in logical pixels.
  52587. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  52588. */
  52589. this.setSize = function ( width, height, updateStyle = true ) {
  52590. if ( xr.isPresenting ) {
  52591. warn( 'WebGLRenderer: Can\'t change size while VR device is presenting.' );
  52592. return;
  52593. }
  52594. _width = width;
  52595. _height = height;
  52596. canvas.width = Math.floor( width * _pixelRatio );
  52597. canvas.height = Math.floor( height * _pixelRatio );
  52598. if ( updateStyle === true ) {
  52599. canvas.style.width = width + 'px';
  52600. canvas.style.height = height + 'px';
  52601. }
  52602. this.setViewport( 0, 0, width, height );
  52603. };
  52604. /**
  52605. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  52606. *
  52607. * @param {Vector2} target - The method writes the result in this target object.
  52608. * @return {Vector2} The drawing buffer size.
  52609. */
  52610. this.getDrawingBufferSize = function ( target ) {
  52611. return target.set( _width * _pixelRatio, _height * _pixelRatio ).floor();
  52612. };
  52613. /**
  52614. * This method allows to define the drawing buffer size by specifying
  52615. * width, height and pixel ratio all at once. The size of the drawing
  52616. * buffer is computed with this formula:
  52617. * ```js
  52618. * size.x = width * pixelRatio;
  52619. * size.y = height * pixelRatio;
  52620. * ```
  52621. *
  52622. * @param {number} width - The width in logical pixels.
  52623. * @param {number} height - The height in logical pixels.
  52624. * @param {number} pixelRatio - The pixel ratio.
  52625. */
  52626. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  52627. _width = width;
  52628. _height = height;
  52629. _pixelRatio = pixelRatio;
  52630. canvas.width = Math.floor( width * pixelRatio );
  52631. canvas.height = Math.floor( height * pixelRatio );
  52632. this.setViewport( 0, 0, width, height );
  52633. };
  52634. /**
  52635. * Returns the current viewport definition.
  52636. *
  52637. * @param {Vector2} target - The method writes the result in this target object.
  52638. * @return {Vector2} The current viewport definition.
  52639. */
  52640. this.getCurrentViewport = function ( target ) {
  52641. return target.copy( _currentViewport );
  52642. };
  52643. /**
  52644. * Returns the viewport definition.
  52645. *
  52646. * @param {Vector4} target - The method writes the result in this target object.
  52647. * @return {Vector4} The viewport definition.
  52648. */
  52649. this.getViewport = function ( target ) {
  52650. return target.copy( _viewport );
  52651. };
  52652. /**
  52653. * Sets the viewport to render from `(x, y)` to `(x + width, y + height)`.
  52654. *
  52655. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52656. * Or alternatively a four-component vector specifying all the parameters of the viewport.
  52657. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  52658. * @param {number} width - The width of the viewport in logical pixel unit.
  52659. * @param {number} height - The height of the viewport in logical pixel unit.
  52660. */
  52661. this.setViewport = function ( x, y, width, height ) {
  52662. if ( x.isVector4 ) {
  52663. _viewport.set( x.x, x.y, x.z, x.w );
  52664. } else {
  52665. _viewport.set( x, y, width, height );
  52666. }
  52667. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).round() );
  52668. };
  52669. /**
  52670. * Returns the scissor region.
  52671. *
  52672. * @param {Vector4} target - The method writes the result in this target object.
  52673. * @return {Vector4} The scissor region.
  52674. */
  52675. this.getScissor = function ( target ) {
  52676. return target.copy( _scissor );
  52677. };
  52678. /**
  52679. * Sets the scissor region to render from `(x, y)` to `(x + width, y + height)`.
  52680. *
  52681. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52682. * Or alternatively a four-component vector specifying all the parameters of the scissor region.
  52683. * @param {number} y - The vertical coordinate for the lower left corner of the scissor region origin in logical pixel unit.
  52684. * @param {number} width - The width of the scissor region in logical pixel unit.
  52685. * @param {number} height - The height of the scissor region in logical pixel unit.
  52686. */
  52687. this.setScissor = function ( x, y, width, height ) {
  52688. if ( x.isVector4 ) {
  52689. _scissor.set( x.x, x.y, x.z, x.w );
  52690. } else {
  52691. _scissor.set( x, y, width, height );
  52692. }
  52693. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).round() );
  52694. };
  52695. /**
  52696. * Returns `true` if the scissor test is enabled.
  52697. *
  52698. * @return {boolean} Whether the scissor test is enabled or not.
  52699. */
  52700. this.getScissorTest = function () {
  52701. return _scissorTest;
  52702. };
  52703. /**
  52704. * Enable or disable the scissor test. When this is enabled, only the pixels
  52705. * within the defined scissor area will be affected by further renderer
  52706. * actions.
  52707. *
  52708. * @param {boolean} boolean - Whether the scissor test is enabled or not.
  52709. */
  52710. this.setScissorTest = function ( boolean ) {
  52711. state.setScissorTest( _scissorTest = boolean );
  52712. };
  52713. /**
  52714. * Sets a custom opaque sort function for the render lists. Pass `null`
  52715. * to use the default `painterSortStable` function.
  52716. *
  52717. * @param {?Function} method - The opaque sort function.
  52718. */
  52719. this.setOpaqueSort = function ( method ) {
  52720. _opaqueSort = method;
  52721. };
  52722. /**
  52723. * Sets a custom transparent sort function for the render lists. Pass `null`
  52724. * to use the default `reversePainterSortStable` function.
  52725. *
  52726. * @param {?Function} method - The opaque sort function.
  52727. */
  52728. this.setTransparentSort = function ( method ) {
  52729. _transparentSort = method;
  52730. };
  52731. // Clearing
  52732. /**
  52733. * Returns the clear color.
  52734. *
  52735. * @param {Color} target - The method writes the result in this target object.
  52736. * @return {Color} The clear color.
  52737. */
  52738. this.getClearColor = function ( target ) {
  52739. return target.copy( background.getClearColor() );
  52740. };
  52741. /**
  52742. * Sets the clear color and alpha.
  52743. *
  52744. * @param {Color} color - The clear color.
  52745. * @param {number} [alpha=1] - The clear alpha.
  52746. */
  52747. this.setClearColor = function () {
  52748. background.setClearColor( ...arguments );
  52749. };
  52750. /**
  52751. * Returns the clear alpha. Ranges within `[0,1]`.
  52752. *
  52753. * @return {number} The clear alpha.
  52754. */
  52755. this.getClearAlpha = function () {
  52756. return background.getClearAlpha();
  52757. };
  52758. /**
  52759. * Sets the clear alpha.
  52760. *
  52761. * @param {number} alpha - The clear alpha.
  52762. */
  52763. this.setClearAlpha = function () {
  52764. background.setClearAlpha( ...arguments );
  52765. };
  52766. /**
  52767. * Tells the renderer to clear its color, depth or stencil drawing buffer(s).
  52768. * This method initializes the buffers to the current clear color values.
  52769. *
  52770. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  52771. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  52772. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  52773. */
  52774. this.clear = function ( color = true, depth = true, stencil = true ) {
  52775. let bits = 0;
  52776. if ( color ) {
  52777. // check if we're trying to clear an integer target
  52778. let isIntegerFormat = false;
  52779. if ( _currentRenderTarget !== null ) {
  52780. const targetFormat = _currentRenderTarget.texture.format;
  52781. isIntegerFormat = INTEGER_FORMATS.has( targetFormat );
  52782. }
  52783. // use the appropriate clear functions to clear the target if it's a signed
  52784. // or unsigned integer target
  52785. if ( isIntegerFormat ) {
  52786. const targetType = _currentRenderTarget.texture.type;
  52787. const isUnsignedType = UNSIGNED_TYPES.has( targetType );
  52788. const clearColor = background.getClearColor();
  52789. const a = background.getClearAlpha();
  52790. const r = clearColor.r;
  52791. const g = clearColor.g;
  52792. const b = clearColor.b;
  52793. if ( isUnsignedType ) {
  52794. uintClearColor[ 0 ] = r;
  52795. uintClearColor[ 1 ] = g;
  52796. uintClearColor[ 2 ] = b;
  52797. uintClearColor[ 3 ] = a;
  52798. _gl.clearBufferuiv( _gl.COLOR, 0, uintClearColor );
  52799. } else {
  52800. intClearColor[ 0 ] = r;
  52801. intClearColor[ 1 ] = g;
  52802. intClearColor[ 2 ] = b;
  52803. intClearColor[ 3 ] = a;
  52804. _gl.clearBufferiv( _gl.COLOR, 0, intClearColor );
  52805. }
  52806. } else {
  52807. bits |= _gl.COLOR_BUFFER_BIT;
  52808. }
  52809. }
  52810. if ( depth ) {
  52811. bits |= _gl.DEPTH_BUFFER_BIT;
  52812. }
  52813. if ( stencil ) {
  52814. bits |= _gl.STENCIL_BUFFER_BIT;
  52815. this.state.buffers.stencil.setMask( 0xffffffff );
  52816. }
  52817. _gl.clear( bits );
  52818. };
  52819. /**
  52820. * Clears the color buffer. Equivalent to calling `renderer.clear( true, false, false )`.
  52821. */
  52822. this.clearColor = function () {
  52823. this.clear( true, false, false );
  52824. };
  52825. /**
  52826. * Clears the depth buffer. Equivalent to calling `renderer.clear( false, true, false )`.
  52827. */
  52828. this.clearDepth = function () {
  52829. this.clear( false, true, false );
  52830. };
  52831. /**
  52832. * Clears the stencil buffer. Equivalent to calling `renderer.clear( false, false, true )`.
  52833. */
  52834. this.clearStencil = function () {
  52835. this.clear( false, false, true );
  52836. };
  52837. /**
  52838. * Frees the GPU-related resources allocated by this instance. Call this
  52839. * method whenever this instance is no longer used in your app.
  52840. */
  52841. this.dispose = function () {
  52842. canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  52843. canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  52844. canvas.removeEventListener( 'webglcontextcreationerror', onContextCreationError, false );
  52845. background.dispose();
  52846. renderLists.dispose();
  52847. renderStates.dispose();
  52848. properties.dispose();
  52849. cubemaps.dispose();
  52850. cubeuvmaps.dispose();
  52851. objects.dispose();
  52852. bindingStates.dispose();
  52853. uniformsGroups.dispose();
  52854. programCache.dispose();
  52855. xr.dispose();
  52856. xr.removeEventListener( 'sessionstart', onXRSessionStart );
  52857. xr.removeEventListener( 'sessionend', onXRSessionEnd );
  52858. animation.stop();
  52859. };
  52860. // Events
  52861. function onContextLost( event ) {
  52862. event.preventDefault();
  52863. log( 'WebGLRenderer: Context Lost.' );
  52864. _isContextLost = true;
  52865. }
  52866. function onContextRestore( /* event */ ) {
  52867. log( 'WebGLRenderer: Context Restored.' );
  52868. _isContextLost = false;
  52869. const infoAutoReset = info.autoReset;
  52870. const shadowMapEnabled = shadowMap.enabled;
  52871. const shadowMapAutoUpdate = shadowMap.autoUpdate;
  52872. const shadowMapNeedsUpdate = shadowMap.needsUpdate;
  52873. const shadowMapType = shadowMap.type;
  52874. initGLContext();
  52875. info.autoReset = infoAutoReset;
  52876. shadowMap.enabled = shadowMapEnabled;
  52877. shadowMap.autoUpdate = shadowMapAutoUpdate;
  52878. shadowMap.needsUpdate = shadowMapNeedsUpdate;
  52879. shadowMap.type = shadowMapType;
  52880. }
  52881. function onContextCreationError( event ) {
  52882. error( 'WebGLRenderer: A WebGL context could not be created. Reason: ', event.statusMessage );
  52883. }
  52884. function onMaterialDispose( event ) {
  52885. const material = event.target;
  52886. material.removeEventListener( 'dispose', onMaterialDispose );
  52887. deallocateMaterial( material );
  52888. }
  52889. // Buffer deallocation
  52890. function deallocateMaterial( material ) {
  52891. releaseMaterialProgramReferences( material );
  52892. properties.remove( material );
  52893. }
  52894. function releaseMaterialProgramReferences( material ) {
  52895. const programs = properties.get( material ).programs;
  52896. if ( programs !== undefined ) {
  52897. programs.forEach( function ( program ) {
  52898. programCache.releaseProgram( program );
  52899. } );
  52900. if ( material.isShaderMaterial ) {
  52901. programCache.releaseShaderCache( material );
  52902. }
  52903. }
  52904. }
  52905. // Buffer rendering
  52906. this.renderBufferDirect = function ( camera, scene, geometry, material, object, group ) {
  52907. if ( scene === null ) scene = _emptyScene; // renderBufferDirect second parameter used to be fog (could be null)
  52908. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  52909. const program = setProgram( camera, scene, geometry, material, object );
  52910. state.setMaterial( material, frontFaceCW );
  52911. //
  52912. let index = geometry.index;
  52913. let rangeFactor = 1;
  52914. if ( material.wireframe === true ) {
  52915. index = geometries.getWireframeAttribute( geometry );
  52916. if ( index === undefined ) return;
  52917. rangeFactor = 2;
  52918. }
  52919. //
  52920. const drawRange = geometry.drawRange;
  52921. const position = geometry.attributes.position;
  52922. let drawStart = drawRange.start * rangeFactor;
  52923. let drawEnd = ( drawRange.start + drawRange.count ) * rangeFactor;
  52924. if ( group !== null ) {
  52925. drawStart = Math.max( drawStart, group.start * rangeFactor );
  52926. drawEnd = Math.min( drawEnd, ( group.start + group.count ) * rangeFactor );
  52927. }
  52928. if ( index !== null ) {
  52929. drawStart = Math.max( drawStart, 0 );
  52930. drawEnd = Math.min( drawEnd, index.count );
  52931. } else if ( position !== undefined && position !== null ) {
  52932. drawStart = Math.max( drawStart, 0 );
  52933. drawEnd = Math.min( drawEnd, position.count );
  52934. }
  52935. const drawCount = drawEnd - drawStart;
  52936. if ( drawCount < 0 || drawCount === Infinity ) return;
  52937. //
  52938. bindingStates.setup( object, material, program, geometry, index );
  52939. let attribute;
  52940. let renderer = bufferRenderer;
  52941. if ( index !== null ) {
  52942. attribute = attributes.get( index );
  52943. renderer = indexedBufferRenderer;
  52944. renderer.setIndex( attribute );
  52945. }
  52946. //
  52947. if ( object.isMesh ) {
  52948. if ( material.wireframe === true ) {
  52949. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  52950. renderer.setMode( _gl.LINES );
  52951. } else {
  52952. renderer.setMode( _gl.TRIANGLES );
  52953. }
  52954. } else if ( object.isLine ) {
  52955. let lineWidth = material.linewidth;
  52956. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  52957. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  52958. if ( object.isLineSegments ) {
  52959. renderer.setMode( _gl.LINES );
  52960. } else if ( object.isLineLoop ) {
  52961. renderer.setMode( _gl.LINE_LOOP );
  52962. } else {
  52963. renderer.setMode( _gl.LINE_STRIP );
  52964. }
  52965. } else if ( object.isPoints ) {
  52966. renderer.setMode( _gl.POINTS );
  52967. } else if ( object.isSprite ) {
  52968. renderer.setMode( _gl.TRIANGLES );
  52969. }
  52970. if ( object.isBatchedMesh ) {
  52971. if ( object._multiDrawInstances !== null ) {
  52972. // @deprecated, r174
  52973. warnOnce( 'WebGLRenderer: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  52974. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  52975. } else {
  52976. if ( ! extensions.get( 'WEBGL_multi_draw' ) ) {
  52977. const starts = object._multiDrawStarts;
  52978. const counts = object._multiDrawCounts;
  52979. const drawCount = object._multiDrawCount;
  52980. const bytesPerElement = index ? attributes.get( index ).bytesPerElement : 1;
  52981. const uniforms = properties.get( material ).currentProgram.getUniforms();
  52982. for ( let i = 0; i < drawCount; i ++ ) {
  52983. uniforms.setValue( _gl, '_gl_DrawID', i );
  52984. renderer.render( starts[ i ] / bytesPerElement, counts[ i ] );
  52985. }
  52986. } else {
  52987. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  52988. }
  52989. }
  52990. } else if ( object.isInstancedMesh ) {
  52991. renderer.renderInstances( drawStart, drawCount, object.count );
  52992. } else if ( geometry.isInstancedBufferGeometry ) {
  52993. const maxInstanceCount = geometry._maxInstanceCount !== undefined ? geometry._maxInstanceCount : Infinity;
  52994. const instanceCount = Math.min( geometry.instanceCount, maxInstanceCount );
  52995. renderer.renderInstances( drawStart, drawCount, instanceCount );
  52996. } else {
  52997. renderer.render( drawStart, drawCount );
  52998. }
  52999. };
  53000. // Compile
  53001. function prepareMaterial( material, scene, object ) {
  53002. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53003. material.side = BackSide;
  53004. material.needsUpdate = true;
  53005. getProgram( material, scene, object );
  53006. material.side = FrontSide;
  53007. material.needsUpdate = true;
  53008. getProgram( material, scene, object );
  53009. material.side = DoubleSide;
  53010. } else {
  53011. getProgram( material, scene, object );
  53012. }
  53013. }
  53014. /**
  53015. * Compiles all materials in the scene with the camera. This is useful to precompile shaders
  53016. * before the first rendering. If you want to add a 3D object to an existing scene, use the third
  53017. * optional parameter for applying the target scene.
  53018. *
  53019. * Note that the (target) scene's lighting and environment must be configured before calling this method.
  53020. *
  53021. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53022. * @param {Camera} camera - The camera.
  53023. * @param {?Scene} [targetScene=null] - The target scene.
  53024. * @return {Set<Material>} The precompiled materials.
  53025. */
  53026. this.compile = function ( scene, camera, targetScene = null ) {
  53027. if ( targetScene === null ) targetScene = scene;
  53028. currentRenderState = renderStates.get( targetScene );
  53029. currentRenderState.init( camera );
  53030. renderStateStack.push( currentRenderState );
  53031. // gather lights from both the target scene and the new object that will be added to the scene.
  53032. targetScene.traverseVisible( function ( object ) {
  53033. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53034. currentRenderState.pushLight( object );
  53035. if ( object.castShadow ) {
  53036. currentRenderState.pushShadow( object );
  53037. }
  53038. }
  53039. } );
  53040. if ( scene !== targetScene ) {
  53041. scene.traverseVisible( function ( object ) {
  53042. if ( object.isLight && object.layers.test( camera.layers ) ) {
  53043. currentRenderState.pushLight( object );
  53044. if ( object.castShadow ) {
  53045. currentRenderState.pushShadow( object );
  53046. }
  53047. }
  53048. } );
  53049. }
  53050. currentRenderState.setupLights();
  53051. // Only initialize materials in the new scene, not the targetScene.
  53052. const materials = new Set();
  53053. scene.traverse( function ( object ) {
  53054. if ( ! ( object.isMesh || object.isPoints || object.isLine || object.isSprite ) ) {
  53055. return;
  53056. }
  53057. const material = object.material;
  53058. if ( material ) {
  53059. if ( Array.isArray( material ) ) {
  53060. for ( let i = 0; i < material.length; i ++ ) {
  53061. const material2 = material[ i ];
  53062. prepareMaterial( material2, targetScene, object );
  53063. materials.add( material2 );
  53064. }
  53065. } else {
  53066. prepareMaterial( material, targetScene, object );
  53067. materials.add( material );
  53068. }
  53069. }
  53070. } );
  53071. currentRenderState = renderStateStack.pop();
  53072. return materials;
  53073. };
  53074. // compileAsync
  53075. /**
  53076. * Asynchronous version of {@link WebGLRenderer#compile}.
  53077. *
  53078. * This method makes use of the `KHR_parallel_shader_compile` WebGL extension. Hence,
  53079. * it is recommended to use this version of `compile()` whenever possible.
  53080. *
  53081. * @async
  53082. * @param {Object3D} scene - The scene or another type of 3D object to precompile.
  53083. * @param {Camera} camera - The camera.
  53084. * @param {?Scene} [targetScene=null] - The target scene.
  53085. * @return {Promise} A Promise that resolves when the given scene can be rendered without unnecessary stalling due to shader compilation.
  53086. */
  53087. this.compileAsync = function ( scene, camera, targetScene = null ) {
  53088. const materials = this.compile( scene, camera, targetScene );
  53089. // Wait for all the materials in the new object to indicate that they're
  53090. // ready to be used before resolving the promise.
  53091. return new Promise( ( resolve ) => {
  53092. function checkMaterialsReady() {
  53093. materials.forEach( function ( material ) {
  53094. const materialProperties = properties.get( material );
  53095. const program = materialProperties.currentProgram;
  53096. if ( program.isReady() ) {
  53097. // remove any programs that report they're ready to use from the list
  53098. materials.delete( material );
  53099. }
  53100. } );
  53101. // once the list of compiling materials is empty, call the callback
  53102. if ( materials.size === 0 ) {
  53103. resolve( scene );
  53104. return;
  53105. }
  53106. // if some materials are still not ready, wait a bit and check again
  53107. setTimeout( checkMaterialsReady, 10 );
  53108. }
  53109. if ( extensions.get( 'KHR_parallel_shader_compile' ) !== null ) {
  53110. // If we can check the compilation status of the materials without
  53111. // blocking then do so right away.
  53112. checkMaterialsReady();
  53113. } else {
  53114. // Otherwise start by waiting a bit to give the materials we just
  53115. // initialized a chance to finish.
  53116. setTimeout( checkMaterialsReady, 10 );
  53117. }
  53118. } );
  53119. };
  53120. // Animation Loop
  53121. let onAnimationFrameCallback = null;
  53122. function onAnimationFrame( time ) {
  53123. if ( onAnimationFrameCallback ) onAnimationFrameCallback( time );
  53124. }
  53125. function onXRSessionStart() {
  53126. animation.stop();
  53127. }
  53128. function onXRSessionEnd() {
  53129. animation.start();
  53130. }
  53131. const animation = new WebGLAnimation();
  53132. animation.setAnimationLoop( onAnimationFrame );
  53133. if ( typeof self !== 'undefined' ) animation.setContext( self );
  53134. /**
  53135. * Applications are advised to always define the animation loop
  53136. * with this method and not manually with `requestAnimationFrame()`
  53137. * for best compatibility.
  53138. *
  53139. * @param {?onAnimationCallback} callback - The application's animation loop.
  53140. */
  53141. this.setAnimationLoop = function ( callback ) {
  53142. onAnimationFrameCallback = callback;
  53143. xr.setAnimationLoop( callback );
  53144. ( callback === null ) ? animation.stop() : animation.start();
  53145. };
  53146. xr.addEventListener( 'sessionstart', onXRSessionStart );
  53147. xr.addEventListener( 'sessionend', onXRSessionEnd );
  53148. // Rendering
  53149. /**
  53150. * Renders the given scene (or other type of 3D object) using the given camera.
  53151. *
  53152. * The render is done to a previously specified render target set by calling {@link WebGLRenderer#setRenderTarget}
  53153. * or to the canvas as usual.
  53154. *
  53155. * By default render buffers are cleared before rendering but you can prevent
  53156. * this by setting the property `autoClear` to `false`. If you want to prevent
  53157. * only certain buffers being cleared you can `autoClearColor`, `autoClearDepth`
  53158. * or `autoClearStencil` to `false`. To force a clear, use {@link WebGLRenderer#clear}.
  53159. *
  53160. * @param {Object3D} scene - The scene to render.
  53161. * @param {Camera} camera - The camera.
  53162. */
  53163. this.render = function ( scene, camera ) {
  53164. if ( camera !== undefined && camera.isCamera !== true ) {
  53165. error( 'WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  53166. return;
  53167. }
  53168. if ( _isContextLost === true ) return;
  53169. // update scene graph
  53170. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  53171. // update camera matrices and frustum
  53172. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  53173. if ( xr.enabled === true && xr.isPresenting === true ) {
  53174. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  53175. camera = xr.getCamera(); // use XR camera for rendering
  53176. }
  53177. //
  53178. if ( scene.isScene === true ) scene.onBeforeRender( _this, scene, camera, _currentRenderTarget );
  53179. currentRenderState = renderStates.get( scene, renderStateStack.length );
  53180. currentRenderState.init( camera );
  53181. renderStateStack.push( currentRenderState );
  53182. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  53183. _frustum.setFromProjectionMatrix( _projScreenMatrix, WebGLCoordinateSystem, camera.reversedDepth );
  53184. _localClippingEnabled = this.localClippingEnabled;
  53185. _clippingEnabled = clipping.init( this.clippingPlanes, _localClippingEnabled );
  53186. currentRenderList = renderLists.get( scene, renderListStack.length );
  53187. currentRenderList.init();
  53188. renderListStack.push( currentRenderList );
  53189. if ( xr.enabled === true && xr.isPresenting === true ) {
  53190. const depthSensingMesh = _this.xr.getDepthSensingMesh();
  53191. if ( depthSensingMesh !== null ) {
  53192. projectObject( depthSensingMesh, camera, - Infinity, _this.sortObjects );
  53193. }
  53194. }
  53195. projectObject( scene, camera, 0, _this.sortObjects );
  53196. currentRenderList.finish();
  53197. if ( _this.sortObjects === true ) {
  53198. currentRenderList.sort( _opaqueSort, _transparentSort );
  53199. }
  53200. _renderBackground = xr.enabled === false || xr.isPresenting === false || xr.hasDepthSensing() === false;
  53201. if ( _renderBackground ) {
  53202. background.addToRenderList( currentRenderList, scene );
  53203. }
  53204. //
  53205. this.info.render.frame ++;
  53206. if ( _clippingEnabled === true ) clipping.beginShadows();
  53207. const shadowsArray = currentRenderState.state.shadowsArray;
  53208. shadowMap.render( shadowsArray, scene, camera );
  53209. if ( _clippingEnabled === true ) clipping.endShadows();
  53210. //
  53211. if ( this.info.autoReset === true ) this.info.reset();
  53212. // render scene
  53213. const opaqueObjects = currentRenderList.opaque;
  53214. const transmissiveObjects = currentRenderList.transmissive;
  53215. currentRenderState.setupLights();
  53216. if ( camera.isArrayCamera ) {
  53217. const cameras = camera.cameras;
  53218. if ( transmissiveObjects.length > 0 ) {
  53219. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53220. const camera2 = cameras[ i ];
  53221. renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera2 );
  53222. }
  53223. }
  53224. if ( _renderBackground ) background.render( scene );
  53225. for ( let i = 0, l = cameras.length; i < l; i ++ ) {
  53226. const camera2 = cameras[ i ];
  53227. renderScene( currentRenderList, scene, camera2, camera2.viewport );
  53228. }
  53229. } else {
  53230. if ( transmissiveObjects.length > 0 ) renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera );
  53231. if ( _renderBackground ) background.render( scene );
  53232. renderScene( currentRenderList, scene, camera );
  53233. }
  53234. //
  53235. if ( _currentRenderTarget !== null && _currentActiveMipmapLevel === 0 ) {
  53236. // resolve multisample renderbuffers to a single-sample texture if necessary
  53237. textures.updateMultisampleRenderTarget( _currentRenderTarget );
  53238. // Generate mipmap if we're using any kind of mipmap filtering
  53239. textures.updateRenderTargetMipmap( _currentRenderTarget );
  53240. }
  53241. //
  53242. if ( scene.isScene === true ) scene.onAfterRender( _this, scene, camera );
  53243. // _gl.finish();
  53244. bindingStates.resetDefaultState();
  53245. _currentMaterialId = -1;
  53246. _currentCamera = null;
  53247. renderStateStack.pop();
  53248. if ( renderStateStack.length > 0 ) {
  53249. currentRenderState = renderStateStack[ renderStateStack.length - 1 ];
  53250. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, currentRenderState.state.camera );
  53251. } else {
  53252. currentRenderState = null;
  53253. }
  53254. renderListStack.pop();
  53255. if ( renderListStack.length > 0 ) {
  53256. currentRenderList = renderListStack[ renderListStack.length - 1 ];
  53257. } else {
  53258. currentRenderList = null;
  53259. }
  53260. };
  53261. function projectObject( object, camera, groupOrder, sortObjects ) {
  53262. if ( object.visible === false ) return;
  53263. const visible = object.layers.test( camera.layers );
  53264. if ( visible ) {
  53265. if ( object.isGroup ) {
  53266. groupOrder = object.renderOrder;
  53267. } else if ( object.isLOD ) {
  53268. if ( object.autoUpdate === true ) object.update( camera );
  53269. } else if ( object.isLight ) {
  53270. currentRenderState.pushLight( object );
  53271. if ( object.castShadow ) {
  53272. currentRenderState.pushShadow( object );
  53273. }
  53274. } else if ( object.isSprite ) {
  53275. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  53276. if ( sortObjects ) {
  53277. _vector4.setFromMatrixPosition( object.matrixWorld )
  53278. .applyMatrix4( _projScreenMatrix );
  53279. }
  53280. const geometry = objects.update( object );
  53281. const material = object.material;
  53282. if ( material.visible ) {
  53283. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53284. }
  53285. }
  53286. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  53287. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  53288. const geometry = objects.update( object );
  53289. const material = object.material;
  53290. if ( sortObjects ) {
  53291. if ( object.boundingSphere !== undefined ) {
  53292. if ( object.boundingSphere === null ) object.computeBoundingSphere();
  53293. _vector4.copy( object.boundingSphere.center );
  53294. } else {
  53295. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  53296. _vector4.copy( geometry.boundingSphere.center );
  53297. }
  53298. _vector4
  53299. .applyMatrix4( object.matrixWorld )
  53300. .applyMatrix4( _projScreenMatrix );
  53301. }
  53302. if ( Array.isArray( material ) ) {
  53303. const groups = geometry.groups;
  53304. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53305. const group = groups[ i ];
  53306. const groupMaterial = material[ group.materialIndex ];
  53307. if ( groupMaterial && groupMaterial.visible ) {
  53308. currentRenderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group );
  53309. }
  53310. }
  53311. } else if ( material.visible ) {
  53312. currentRenderList.push( object, geometry, material, groupOrder, _vector4.z, null );
  53313. }
  53314. }
  53315. }
  53316. }
  53317. const children = object.children;
  53318. for ( let i = 0, l = children.length; i < l; i ++ ) {
  53319. projectObject( children[ i ], camera, groupOrder, sortObjects );
  53320. }
  53321. }
  53322. function renderScene( currentRenderList, scene, camera, viewport ) {
  53323. const { opaque: opaqueObjects, transmissive: transmissiveObjects, transparent: transparentObjects } = currentRenderList;
  53324. currentRenderState.setupLightsView( camera );
  53325. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53326. if ( viewport ) state.viewport( _currentViewport.copy( viewport ) );
  53327. if ( opaqueObjects.length > 0 ) renderObjects( opaqueObjects, scene, camera );
  53328. if ( transmissiveObjects.length > 0 ) renderObjects( transmissiveObjects, scene, camera );
  53329. if ( transparentObjects.length > 0 ) renderObjects( transparentObjects, scene, camera );
  53330. // Ensure depth buffer writing is enabled so it can be cleared on next render
  53331. state.buffers.depth.setTest( true );
  53332. state.buffers.depth.setMask( true );
  53333. state.buffers.color.setMask( true );
  53334. state.setPolygonOffset( false );
  53335. }
  53336. function renderTransmissionPass( opaqueObjects, transmissiveObjects, scene, camera ) {
  53337. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53338. if ( overrideMaterial !== null ) {
  53339. return;
  53340. }
  53341. if ( currentRenderState.state.transmissionRenderTarget[ camera.id ] === undefined ) {
  53342. currentRenderState.state.transmissionRenderTarget[ camera.id ] = new WebGLRenderTarget( 1, 1, {
  53343. generateMipmaps: true,
  53344. type: ( extensions.has( 'EXT_color_buffer_half_float' ) || extensions.has( 'EXT_color_buffer_float' ) ) ? HalfFloatType : UnsignedByteType,
  53345. minFilter: LinearMipmapLinearFilter,
  53346. samples: 4,
  53347. stencilBuffer: stencil,
  53348. resolveDepthBuffer: false,
  53349. resolveStencilBuffer: false,
  53350. colorSpace: ColorManagement.workingColorSpace,
  53351. } );
  53352. // debug
  53353. /*
  53354. const geometry = new PlaneGeometry();
  53355. const material = new MeshBasicMaterial( { map: _transmissionRenderTarget.texture } );
  53356. const mesh = new Mesh( geometry, material );
  53357. scene.add( mesh );
  53358. */
  53359. }
  53360. const transmissionRenderTarget = currentRenderState.state.transmissionRenderTarget[ camera.id ];
  53361. const activeViewport = camera.viewport || _currentViewport;
  53362. transmissionRenderTarget.setSize( activeViewport.z * _this.transmissionResolutionScale, activeViewport.w * _this.transmissionResolutionScale );
  53363. //
  53364. const currentRenderTarget = _this.getRenderTarget();
  53365. const currentActiveCubeFace = _this.getActiveCubeFace();
  53366. const currentActiveMipmapLevel = _this.getActiveMipmapLevel();
  53367. _this.setRenderTarget( transmissionRenderTarget );
  53368. _this.getClearColor( _currentClearColor );
  53369. _currentClearAlpha = _this.getClearAlpha();
  53370. if ( _currentClearAlpha < 1 ) _this.setClearColor( 0xffffff, 0.5 );
  53371. _this.clear();
  53372. if ( _renderBackground ) background.render( scene );
  53373. // Turn off the features which can affect the frag color for opaque objects pass.
  53374. // Otherwise they are applied twice in opaque objects pass and transmission objects pass.
  53375. const currentToneMapping = _this.toneMapping;
  53376. _this.toneMapping = NoToneMapping;
  53377. // Remove viewport from camera to avoid nested render calls resetting viewport to it (e.g Reflector).
  53378. // Transmission render pass requires viewport to match the transmissionRenderTarget.
  53379. const currentCameraViewport = camera.viewport;
  53380. if ( camera.viewport !== undefined ) camera.viewport = undefined;
  53381. currentRenderState.setupLightsView( camera );
  53382. if ( _clippingEnabled === true ) clipping.setGlobalState( _this.clippingPlanes, camera );
  53383. renderObjects( opaqueObjects, scene, camera );
  53384. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53385. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53386. if ( extensions.has( 'WEBGL_multisampled_render_to_texture' ) === false ) { // see #28131
  53387. let renderTargetNeedsUpdate = false;
  53388. for ( let i = 0, l = transmissiveObjects.length; i < l; i ++ ) {
  53389. const renderItem = transmissiveObjects[ i ];
  53390. const { object, geometry, material, group } = renderItem;
  53391. if ( material.side === DoubleSide && object.layers.test( camera.layers ) ) {
  53392. const currentSide = material.side;
  53393. material.side = BackSide;
  53394. material.needsUpdate = true;
  53395. renderObject( object, scene, camera, geometry, material, group );
  53396. material.side = currentSide;
  53397. material.needsUpdate = true;
  53398. renderTargetNeedsUpdate = true;
  53399. }
  53400. }
  53401. if ( renderTargetNeedsUpdate === true ) {
  53402. textures.updateMultisampleRenderTarget( transmissionRenderTarget );
  53403. textures.updateRenderTargetMipmap( transmissionRenderTarget );
  53404. }
  53405. }
  53406. _this.setRenderTarget( currentRenderTarget, currentActiveCubeFace, currentActiveMipmapLevel );
  53407. _this.setClearColor( _currentClearColor, _currentClearAlpha );
  53408. if ( currentCameraViewport !== undefined ) camera.viewport = currentCameraViewport;
  53409. _this.toneMapping = currentToneMapping;
  53410. }
  53411. function renderObjects( renderList, scene, camera ) {
  53412. const overrideMaterial = scene.isScene === true ? scene.overrideMaterial : null;
  53413. for ( let i = 0, l = renderList.length; i < l; i ++ ) {
  53414. const renderItem = renderList[ i ];
  53415. const { object, geometry, group } = renderItem;
  53416. let material = renderItem.material;
  53417. if ( material.allowOverride === true && overrideMaterial !== null ) {
  53418. material = overrideMaterial;
  53419. }
  53420. if ( object.layers.test( camera.layers ) ) {
  53421. renderObject( object, scene, camera, geometry, material, group );
  53422. }
  53423. }
  53424. }
  53425. function renderObject( object, scene, camera, geometry, material, group ) {
  53426. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  53427. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  53428. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  53429. material.onBeforeRender( _this, scene, camera, geometry, object, group );
  53430. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  53431. material.side = BackSide;
  53432. material.needsUpdate = true;
  53433. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53434. material.side = FrontSide;
  53435. material.needsUpdate = true;
  53436. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53437. material.side = DoubleSide;
  53438. } else {
  53439. _this.renderBufferDirect( camera, scene, geometry, material, object, group );
  53440. }
  53441. object.onAfterRender( _this, scene, camera, geometry, material, group );
  53442. }
  53443. function getProgram( material, scene, object ) {
  53444. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53445. const materialProperties = properties.get( material );
  53446. const lights = currentRenderState.state.lights;
  53447. const shadowsArray = currentRenderState.state.shadowsArray;
  53448. const lightsStateVersion = lights.state.version;
  53449. const parameters = programCache.getParameters( material, lights.state, shadowsArray, scene, object );
  53450. const programCacheKey = programCache.getProgramCacheKey( parameters );
  53451. let programs = materialProperties.programs;
  53452. // always update environment and fog - changing these trigger an getProgram call, but it's possible that the program doesn't change
  53453. materialProperties.environment = material.isMeshStandardMaterial ? scene.environment : null;
  53454. materialProperties.fog = scene.fog;
  53455. materialProperties.envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || materialProperties.environment );
  53456. materialProperties.envMapRotation = ( materialProperties.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  53457. if ( programs === undefined ) {
  53458. // new material
  53459. material.addEventListener( 'dispose', onMaterialDispose );
  53460. programs = new Map();
  53461. materialProperties.programs = programs;
  53462. }
  53463. let program = programs.get( programCacheKey );
  53464. if ( program !== undefined ) {
  53465. // early out if program and light state is identical
  53466. if ( materialProperties.currentProgram === program && materialProperties.lightsStateVersion === lightsStateVersion ) {
  53467. updateCommonMaterialProperties( material, parameters );
  53468. return program;
  53469. }
  53470. } else {
  53471. parameters.uniforms = programCache.getUniforms( material );
  53472. material.onBeforeCompile( parameters, _this );
  53473. program = programCache.acquireProgram( parameters, programCacheKey );
  53474. programs.set( programCacheKey, program );
  53475. materialProperties.uniforms = parameters.uniforms;
  53476. }
  53477. const uniforms = materialProperties.uniforms;
  53478. if ( ( ! material.isShaderMaterial && ! material.isRawShaderMaterial ) || material.clipping === true ) {
  53479. uniforms.clippingPlanes = clipping.uniform;
  53480. }
  53481. updateCommonMaterialProperties( material, parameters );
  53482. // store the light setup it was created for
  53483. materialProperties.needsLights = materialNeedsLights( material );
  53484. materialProperties.lightsStateVersion = lightsStateVersion;
  53485. if ( materialProperties.needsLights ) {
  53486. // wire up the material to this renderer's lighting state
  53487. uniforms.ambientLightColor.value = lights.state.ambient;
  53488. uniforms.lightProbe.value = lights.state.probe;
  53489. uniforms.directionalLights.value = lights.state.directional;
  53490. uniforms.directionalLightShadows.value = lights.state.directionalShadow;
  53491. uniforms.spotLights.value = lights.state.spot;
  53492. uniforms.spotLightShadows.value = lights.state.spotShadow;
  53493. uniforms.rectAreaLights.value = lights.state.rectArea;
  53494. uniforms.ltc_1.value = lights.state.rectAreaLTC1;
  53495. uniforms.ltc_2.value = lights.state.rectAreaLTC2;
  53496. uniforms.pointLights.value = lights.state.point;
  53497. uniforms.pointLightShadows.value = lights.state.pointShadow;
  53498. uniforms.hemisphereLights.value = lights.state.hemi;
  53499. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  53500. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  53501. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  53502. uniforms.spotLightMatrix.value = lights.state.spotLightMatrix;
  53503. uniforms.spotLightMap.value = lights.state.spotLightMap;
  53504. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  53505. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  53506. // TODO (abelnation): add area lights shadow info to uniforms
  53507. }
  53508. materialProperties.currentProgram = program;
  53509. materialProperties.uniformsList = null;
  53510. return program;
  53511. }
  53512. function getUniformList( materialProperties ) {
  53513. if ( materialProperties.uniformsList === null ) {
  53514. const progUniforms = materialProperties.currentProgram.getUniforms();
  53515. materialProperties.uniformsList = WebGLUniforms.seqWithValue( progUniforms.seq, materialProperties.uniforms );
  53516. }
  53517. return materialProperties.uniformsList;
  53518. }
  53519. function updateCommonMaterialProperties( material, parameters ) {
  53520. const materialProperties = properties.get( material );
  53521. materialProperties.outputColorSpace = parameters.outputColorSpace;
  53522. materialProperties.batching = parameters.batching;
  53523. materialProperties.batchingColor = parameters.batchingColor;
  53524. materialProperties.instancing = parameters.instancing;
  53525. materialProperties.instancingColor = parameters.instancingColor;
  53526. materialProperties.instancingMorph = parameters.instancingMorph;
  53527. materialProperties.skinning = parameters.skinning;
  53528. materialProperties.morphTargets = parameters.morphTargets;
  53529. materialProperties.morphNormals = parameters.morphNormals;
  53530. materialProperties.morphColors = parameters.morphColors;
  53531. materialProperties.morphTargetsCount = parameters.morphTargetsCount;
  53532. materialProperties.numClippingPlanes = parameters.numClippingPlanes;
  53533. materialProperties.numIntersection = parameters.numClipIntersection;
  53534. materialProperties.vertexAlphas = parameters.vertexAlphas;
  53535. materialProperties.vertexTangents = parameters.vertexTangents;
  53536. materialProperties.toneMapping = parameters.toneMapping;
  53537. }
  53538. function setProgram( camera, scene, geometry, material, object ) {
  53539. if ( scene.isScene !== true ) scene = _emptyScene; // scene could be a Mesh, Line, Points, ...
  53540. textures.resetTextureUnits();
  53541. const fog = scene.fog;
  53542. const environment = material.isMeshStandardMaterial ? scene.environment : null;
  53543. const colorSpace = ( _currentRenderTarget === null ) ? _this.outputColorSpace : ( _currentRenderTarget.isXRRenderTarget === true ? _currentRenderTarget.texture.colorSpace : LinearSRGBColorSpace );
  53544. const envMap = ( material.isMeshStandardMaterial ? cubeuvmaps : cubemaps ).get( material.envMap || environment );
  53545. const vertexAlphas = material.vertexColors === true && !! geometry.attributes.color && geometry.attributes.color.itemSize === 4;
  53546. const vertexTangents = !! geometry.attributes.tangent && ( !! material.normalMap || material.anisotropy > 0 );
  53547. const morphTargets = !! geometry.morphAttributes.position;
  53548. const morphNormals = !! geometry.morphAttributes.normal;
  53549. const morphColors = !! geometry.morphAttributes.color;
  53550. let toneMapping = NoToneMapping;
  53551. if ( material.toneMapped ) {
  53552. if ( _currentRenderTarget === null || _currentRenderTarget.isXRRenderTarget === true ) {
  53553. toneMapping = _this.toneMapping;
  53554. }
  53555. }
  53556. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  53557. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  53558. const materialProperties = properties.get( material );
  53559. const lights = currentRenderState.state.lights;
  53560. if ( _clippingEnabled === true ) {
  53561. if ( _localClippingEnabled === true || camera !== _currentCamera ) {
  53562. const useCache =
  53563. camera === _currentCamera &&
  53564. material.id === _currentMaterialId;
  53565. // we might want to call this function with some ClippingGroup
  53566. // object instead of the material, once it becomes feasible
  53567. // (#8465, #8379)
  53568. clipping.setState( material, camera, useCache );
  53569. }
  53570. }
  53571. //
  53572. let needsProgramChange = false;
  53573. if ( material.version === materialProperties.__version ) {
  53574. if ( materialProperties.needsLights && ( materialProperties.lightsStateVersion !== lights.state.version ) ) {
  53575. needsProgramChange = true;
  53576. } else if ( materialProperties.outputColorSpace !== colorSpace ) {
  53577. needsProgramChange = true;
  53578. } else if ( object.isBatchedMesh && materialProperties.batching === false ) {
  53579. needsProgramChange = true;
  53580. } else if ( ! object.isBatchedMesh && materialProperties.batching === true ) {
  53581. needsProgramChange = true;
  53582. } else if ( object.isBatchedMesh && materialProperties.batchingColor === true && object.colorTexture === null ) {
  53583. needsProgramChange = true;
  53584. } else if ( object.isBatchedMesh && materialProperties.batchingColor === false && object.colorTexture !== null ) {
  53585. needsProgramChange = true;
  53586. } else if ( object.isInstancedMesh && materialProperties.instancing === false ) {
  53587. needsProgramChange = true;
  53588. } else if ( ! object.isInstancedMesh && materialProperties.instancing === true ) {
  53589. needsProgramChange = true;
  53590. } else if ( object.isSkinnedMesh && materialProperties.skinning === false ) {
  53591. needsProgramChange = true;
  53592. } else if ( ! object.isSkinnedMesh && materialProperties.skinning === true ) {
  53593. needsProgramChange = true;
  53594. } else if ( object.isInstancedMesh && materialProperties.instancingColor === true && object.instanceColor === null ) {
  53595. needsProgramChange = true;
  53596. } else if ( object.isInstancedMesh && materialProperties.instancingColor === false && object.instanceColor !== null ) {
  53597. needsProgramChange = true;
  53598. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === true && object.morphTexture === null ) {
  53599. needsProgramChange = true;
  53600. } else if ( object.isInstancedMesh && materialProperties.instancingMorph === false && object.morphTexture !== null ) {
  53601. needsProgramChange = true;
  53602. } else if ( materialProperties.envMap !== envMap ) {
  53603. needsProgramChange = true;
  53604. } else if ( material.fog === true && materialProperties.fog !== fog ) {
  53605. needsProgramChange = true;
  53606. } else if ( materialProperties.numClippingPlanes !== undefined &&
  53607. ( materialProperties.numClippingPlanes !== clipping.numPlanes ||
  53608. materialProperties.numIntersection !== clipping.numIntersection ) ) {
  53609. needsProgramChange = true;
  53610. } else if ( materialProperties.vertexAlphas !== vertexAlphas ) {
  53611. needsProgramChange = true;
  53612. } else if ( materialProperties.vertexTangents !== vertexTangents ) {
  53613. needsProgramChange = true;
  53614. } else if ( materialProperties.morphTargets !== morphTargets ) {
  53615. needsProgramChange = true;
  53616. } else if ( materialProperties.morphNormals !== morphNormals ) {
  53617. needsProgramChange = true;
  53618. } else if ( materialProperties.morphColors !== morphColors ) {
  53619. needsProgramChange = true;
  53620. } else if ( materialProperties.toneMapping !== toneMapping ) {
  53621. needsProgramChange = true;
  53622. } else if ( materialProperties.morphTargetsCount !== morphTargetsCount ) {
  53623. needsProgramChange = true;
  53624. }
  53625. } else {
  53626. needsProgramChange = true;
  53627. materialProperties.__version = material.version;
  53628. }
  53629. //
  53630. let program = materialProperties.currentProgram;
  53631. if ( needsProgramChange === true ) {
  53632. program = getProgram( material, scene, object );
  53633. }
  53634. let refreshProgram = false;
  53635. let refreshMaterial = false;
  53636. let refreshLights = false;
  53637. const p_uniforms = program.getUniforms(),
  53638. m_uniforms = materialProperties.uniforms;
  53639. if ( state.useProgram( program.program ) ) {
  53640. refreshProgram = true;
  53641. refreshMaterial = true;
  53642. refreshLights = true;
  53643. }
  53644. if ( material.id !== _currentMaterialId ) {
  53645. _currentMaterialId = material.id;
  53646. refreshMaterial = true;
  53647. }
  53648. if ( refreshProgram || _currentCamera !== camera ) {
  53649. // common camera uniforms
  53650. const reversedDepthBuffer = state.buffers.depth.getReversed();
  53651. if ( reversedDepthBuffer && camera.reversedDepth !== true ) {
  53652. camera._reversedDepth = true;
  53653. camera.updateProjectionMatrix();
  53654. }
  53655. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  53656. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  53657. const uCamPos = p_uniforms.map.cameraPosition;
  53658. if ( uCamPos !== undefined ) {
  53659. uCamPos.setValue( _gl, _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  53660. }
  53661. if ( capabilities.logarithmicDepthBuffer ) {
  53662. p_uniforms.setValue( _gl, 'logDepthBufFC',
  53663. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  53664. }
  53665. // consider moving isOrthographic to UniformLib and WebGLMaterials, see https://github.com/mrdoob/three.js/pull/26467#issuecomment-1645185067
  53666. if ( material.isMeshPhongMaterial ||
  53667. material.isMeshToonMaterial ||
  53668. material.isMeshLambertMaterial ||
  53669. material.isMeshBasicMaterial ||
  53670. material.isMeshStandardMaterial ||
  53671. material.isShaderMaterial ) {
  53672. p_uniforms.setValue( _gl, 'isOrthographic', camera.isOrthographicCamera === true );
  53673. }
  53674. if ( _currentCamera !== camera ) {
  53675. _currentCamera = camera;
  53676. // lighting uniforms depend on the camera so enforce an update
  53677. // now, in case this material supports lights - or later, when
  53678. // the next material that does gets activated:
  53679. refreshMaterial = true; // set to true on material change
  53680. refreshLights = true; // remains set until update done
  53681. }
  53682. }
  53683. // Pre-allocate texture units for shadow samplers before setting data textures
  53684. if ( materialProperties.needsLights ) {
  53685. // Set shadow map uniforms first to ensure they get the first texture units
  53686. if ( lights.state.directionalShadowMap.length > 0 ) {
  53687. p_uniforms.setValue( _gl, 'directionalShadowMap', lights.state.directionalShadowMap, textures );
  53688. }
  53689. if ( lights.state.spotShadowMap.length > 0 ) {
  53690. p_uniforms.setValue( _gl, 'spotShadowMap', lights.state.spotShadowMap, textures );
  53691. }
  53692. if ( lights.state.pointShadowMap.length > 0 ) {
  53693. p_uniforms.setValue( _gl, 'pointShadowMap', lights.state.pointShadowMap, textures );
  53694. }
  53695. }
  53696. // skinning and morph target uniforms must be set even if material didn't change
  53697. // auto-setting of texture unit for bone and morph texture must go before other textures
  53698. // otherwise textures used for skinning and morphing can take over texture units reserved for other material textures
  53699. if ( object.isSkinnedMesh ) {
  53700. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  53701. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  53702. const skeleton = object.skeleton;
  53703. if ( skeleton ) {
  53704. if ( skeleton.boneTexture === null ) skeleton.computeBoneTexture();
  53705. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture, textures );
  53706. }
  53707. }
  53708. if ( object.isBatchedMesh ) {
  53709. p_uniforms.setOptional( _gl, object, 'batchingTexture' );
  53710. p_uniforms.setValue( _gl, 'batchingTexture', object._matricesTexture, textures );
  53711. p_uniforms.setOptional( _gl, object, 'batchingIdTexture' );
  53712. p_uniforms.setValue( _gl, 'batchingIdTexture', object._indirectTexture, textures );
  53713. p_uniforms.setOptional( _gl, object, 'batchingColorTexture' );
  53714. if ( object._colorsTexture !== null ) {
  53715. p_uniforms.setValue( _gl, 'batchingColorTexture', object._colorsTexture, textures );
  53716. }
  53717. }
  53718. const morphAttributes = geometry.morphAttributes;
  53719. if ( morphAttributes.position !== undefined || morphAttributes.normal !== undefined || ( morphAttributes.color !== undefined ) ) {
  53720. morphtargets.update( object, geometry, program );
  53721. }
  53722. if ( refreshMaterial || materialProperties.receiveShadow !== object.receiveShadow ) {
  53723. materialProperties.receiveShadow = object.receiveShadow;
  53724. p_uniforms.setValue( _gl, 'receiveShadow', object.receiveShadow );
  53725. }
  53726. // https://github.com/mrdoob/three.js/pull/24467#issuecomment-1209031512
  53727. if ( material.isMeshGouraudMaterial && material.envMap !== null ) {
  53728. m_uniforms.envMap.value = envMap;
  53729. m_uniforms.flipEnvMap.value = ( envMap.isCubeTexture && envMap.isRenderTargetTexture === false ) ? -1 : 1;
  53730. }
  53731. if ( material.isMeshStandardMaterial && material.envMap === null && scene.environment !== null ) {
  53732. m_uniforms.envMapIntensity.value = scene.environmentIntensity;
  53733. }
  53734. // Set DFG LUT for physically-based materials
  53735. if ( m_uniforms.dfgLUT !== undefined ) {
  53736. m_uniforms.dfgLUT.value = getDFGLUT();
  53737. }
  53738. if ( refreshMaterial ) {
  53739. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  53740. if ( materialProperties.needsLights ) {
  53741. // the current material requires lighting info
  53742. // note: all lighting uniforms are always set correctly
  53743. // they simply reference the renderer's state for their
  53744. // values
  53745. //
  53746. // use the current material's .needsUpdate flags to set
  53747. // the GL state when required
  53748. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  53749. }
  53750. // refresh uniforms common to several materials
  53751. if ( fog && material.fog === true ) {
  53752. materials.refreshFogUniforms( m_uniforms, fog );
  53753. }
  53754. materials.refreshMaterialUniforms( m_uniforms, material, _pixelRatio, _height, currentRenderState.state.transmissionRenderTarget[ camera.id ] );
  53755. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53756. }
  53757. if ( material.isShaderMaterial && material.uniformsNeedUpdate === true ) {
  53758. WebGLUniforms.upload( _gl, getUniformList( materialProperties ), m_uniforms, textures );
  53759. material.uniformsNeedUpdate = false;
  53760. }
  53761. if ( material.isSpriteMaterial ) {
  53762. p_uniforms.setValue( _gl, 'center', object.center );
  53763. }
  53764. // common matrices
  53765. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  53766. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  53767. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  53768. // UBOs
  53769. if ( material.isShaderMaterial || material.isRawShaderMaterial ) {
  53770. const groups = material.uniformsGroups;
  53771. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  53772. const group = groups[ i ];
  53773. uniformsGroups.update( group, program );
  53774. uniformsGroups.bind( group, program );
  53775. }
  53776. }
  53777. return program;
  53778. }
  53779. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  53780. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  53781. uniforms.ambientLightColor.needsUpdate = value;
  53782. uniforms.lightProbe.needsUpdate = value;
  53783. uniforms.directionalLights.needsUpdate = value;
  53784. uniforms.directionalLightShadows.needsUpdate = value;
  53785. uniforms.pointLights.needsUpdate = value;
  53786. uniforms.pointLightShadows.needsUpdate = value;
  53787. uniforms.spotLights.needsUpdate = value;
  53788. uniforms.spotLightShadows.needsUpdate = value;
  53789. uniforms.rectAreaLights.needsUpdate = value;
  53790. uniforms.hemisphereLights.needsUpdate = value;
  53791. }
  53792. function materialNeedsLights( material ) {
  53793. return material.isMeshLambertMaterial || material.isMeshToonMaterial || material.isMeshPhongMaterial ||
  53794. material.isMeshStandardMaterial || material.isShadowMaterial ||
  53795. ( material.isShaderMaterial && material.lights === true );
  53796. }
  53797. /**
  53798. * Returns the active cube face.
  53799. *
  53800. * @return {number} The active cube face.
  53801. */
  53802. this.getActiveCubeFace = function () {
  53803. return _currentActiveCubeFace;
  53804. };
  53805. /**
  53806. * Returns the active mipmap level.
  53807. *
  53808. * @return {number} The active mipmap level.
  53809. */
  53810. this.getActiveMipmapLevel = function () {
  53811. return _currentActiveMipmapLevel;
  53812. };
  53813. /**
  53814. * Returns the active render target.
  53815. *
  53816. * @return {?WebGLRenderTarget} The active render target. Returns `null` if no render target
  53817. * is currently set.
  53818. */
  53819. this.getRenderTarget = function () {
  53820. return _currentRenderTarget;
  53821. };
  53822. this.setRenderTargetTextures = function ( renderTarget, colorTexture, depthTexture ) {
  53823. const renderTargetProperties = properties.get( renderTarget );
  53824. renderTargetProperties.__autoAllocateDepthBuffer = renderTarget.resolveDepthBuffer === false;
  53825. if ( renderTargetProperties.__autoAllocateDepthBuffer === false ) {
  53826. // The multisample_render_to_texture extension doesn't work properly if there
  53827. // are midframe flushes and an external depth buffer. Disable use of the extension.
  53828. renderTargetProperties.__useRenderToTexture = false;
  53829. }
  53830. properties.get( renderTarget.texture ).__webglTexture = colorTexture;
  53831. properties.get( renderTarget.depthTexture ).__webglTexture = renderTargetProperties.__autoAllocateDepthBuffer ? undefined : depthTexture;
  53832. renderTargetProperties.__hasExternalTextures = true;
  53833. };
  53834. this.setRenderTargetFramebuffer = function ( renderTarget, defaultFramebuffer ) {
  53835. const renderTargetProperties = properties.get( renderTarget );
  53836. renderTargetProperties.__webglFramebuffer = defaultFramebuffer;
  53837. renderTargetProperties.__useDefaultFramebuffer = defaultFramebuffer === undefined;
  53838. };
  53839. const _scratchFrameBuffer = _gl.createFramebuffer();
  53840. /**
  53841. * Sets the active rendertarget.
  53842. *
  53843. * @param {?WebGLRenderTarget} renderTarget - The render target to set. When `null` is given,
  53844. * the canvas is set as the active render target instead.
  53845. * @param {number} [activeCubeFace=0] - The active cube face when using a cube render target.
  53846. * Indicates the z layer to render in to when using 3D or array render targets.
  53847. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  53848. */
  53849. this.setRenderTarget = function ( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  53850. _currentRenderTarget = renderTarget;
  53851. _currentActiveCubeFace = activeCubeFace;
  53852. _currentActiveMipmapLevel = activeMipmapLevel;
  53853. let useDefaultFramebuffer = true;
  53854. let framebuffer = null;
  53855. let isCube = false;
  53856. let isRenderTarget3D = false;
  53857. if ( renderTarget ) {
  53858. const renderTargetProperties = properties.get( renderTarget );
  53859. if ( renderTargetProperties.__useDefaultFramebuffer !== undefined ) {
  53860. // We need to make sure to rebind the framebuffer.
  53861. state.bindFramebuffer( _gl.FRAMEBUFFER, null );
  53862. useDefaultFramebuffer = false;
  53863. } else if ( renderTargetProperties.__webglFramebuffer === undefined ) {
  53864. textures.setupRenderTarget( renderTarget );
  53865. } else if ( renderTargetProperties.__hasExternalTextures ) {
  53866. // Color and depth texture must be rebound in order for the swapchain to update.
  53867. textures.rebindTextures( renderTarget, properties.get( renderTarget.texture ).__webglTexture, properties.get( renderTarget.depthTexture ).__webglTexture );
  53868. } else if ( renderTarget.depthBuffer ) {
  53869. // check if the depth texture is already bound to the frame buffer and that it's been initialized
  53870. const depthTexture = renderTarget.depthTexture;
  53871. if ( renderTargetProperties.__boundDepthTexture !== depthTexture ) {
  53872. // check if the depth texture is compatible
  53873. if (
  53874. depthTexture !== null &&
  53875. properties.has( depthTexture ) &&
  53876. ( renderTarget.width !== depthTexture.image.width || renderTarget.height !== depthTexture.image.height )
  53877. ) {
  53878. throw new Error( 'WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size.' );
  53879. }
  53880. // Swap the depth buffer to the currently attached one
  53881. textures.setupDepthRenderbuffer( renderTarget );
  53882. }
  53883. }
  53884. const texture = renderTarget.texture;
  53885. if ( texture.isData3DTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  53886. isRenderTarget3D = true;
  53887. }
  53888. const __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53889. if ( renderTarget.isWebGLCubeRenderTarget ) {
  53890. if ( Array.isArray( __webglFramebuffer[ activeCubeFace ] ) ) {
  53891. framebuffer = __webglFramebuffer[ activeCubeFace ][ activeMipmapLevel ];
  53892. } else {
  53893. framebuffer = __webglFramebuffer[ activeCubeFace ];
  53894. }
  53895. isCube = true;
  53896. } else if ( ( renderTarget.samples > 0 ) && textures.useMultisampledRTT( renderTarget ) === false ) {
  53897. framebuffer = properties.get( renderTarget ).__webglMultisampledFramebuffer;
  53898. } else {
  53899. if ( Array.isArray( __webglFramebuffer ) ) {
  53900. framebuffer = __webglFramebuffer[ activeMipmapLevel ];
  53901. } else {
  53902. framebuffer = __webglFramebuffer;
  53903. }
  53904. }
  53905. _currentViewport.copy( renderTarget.viewport );
  53906. _currentScissor.copy( renderTarget.scissor );
  53907. _currentScissorTest = renderTarget.scissorTest;
  53908. } else {
  53909. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ).floor();
  53910. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ).floor();
  53911. _currentScissorTest = _scissorTest;
  53912. }
  53913. // Use a scratch frame buffer if rendering to a mip level to avoid depth buffers
  53914. // being bound that are different sizes.
  53915. if ( activeMipmapLevel !== 0 ) {
  53916. framebuffer = _scratchFrameBuffer;
  53917. }
  53918. const framebufferBound = state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53919. if ( framebufferBound && useDefaultFramebuffer ) {
  53920. state.drawBuffers( renderTarget, framebuffer );
  53921. }
  53922. state.viewport( _currentViewport );
  53923. state.scissor( _currentScissor );
  53924. state.setScissorTest( _currentScissorTest );
  53925. if ( isCube ) {
  53926. const textureProperties = properties.get( renderTarget.texture );
  53927. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + activeCubeFace, textureProperties.__webglTexture, activeMipmapLevel );
  53928. } else if ( isRenderTarget3D ) {
  53929. const layer = activeCubeFace;
  53930. for ( let i = 0; i < renderTarget.textures.length; i ++ ) {
  53931. const textureProperties = properties.get( renderTarget.textures[ i ] );
  53932. _gl.framebufferTextureLayer( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, textureProperties.__webglTexture, activeMipmapLevel, layer );
  53933. }
  53934. } else if ( renderTarget !== null && activeMipmapLevel !== 0 ) {
  53935. // Only bind the frame buffer if we are using a scratch frame buffer to render to a mipmap.
  53936. // If we rebind the texture when using a multi sample buffer then an error about inconsistent samples will be thrown.
  53937. const textureProperties = properties.get( renderTarget.texture );
  53938. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, textureProperties.__webglTexture, activeMipmapLevel );
  53939. }
  53940. _currentMaterialId = -1; // reset current material to ensure correct uniform bindings
  53941. };
  53942. /**
  53943. * Reads the pixel data from the given render target into the given buffer.
  53944. *
  53945. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53946. * @param {number} x - The `x` coordinate of the copy region's origin.
  53947. * @param {number} y - The `y` coordinate of the copy region's origin.
  53948. * @param {number} width - The width of the copy region.
  53949. * @param {number} height - The height of the copy region.
  53950. * @param {TypedArray} buffer - The result buffer.
  53951. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  53952. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  53953. */
  53954. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  53955. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  53956. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  53957. return;
  53958. }
  53959. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  53960. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  53961. framebuffer = framebuffer[ activeCubeFaceIndex ];
  53962. }
  53963. if ( framebuffer ) {
  53964. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53965. try {
  53966. const texture = renderTarget.textures[ textureIndex ];
  53967. const textureFormat = texture.format;
  53968. const textureType = texture.type;
  53969. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  53970. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  53971. return;
  53972. }
  53973. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  53974. error( 'WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  53975. return;
  53976. }
  53977. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  53978. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  53979. // when using MRT, select the correct color buffer for the subsequent read command
  53980. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  53981. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  53982. }
  53983. } finally {
  53984. // restore framebuffer of current render target if necessary
  53985. const framebuffer = ( _currentRenderTarget !== null ) ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  53986. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  53987. }
  53988. }
  53989. };
  53990. /**
  53991. * Asynchronous, non-blocking version of {@link WebGLRenderer#readRenderTargetPixels}.
  53992. *
  53993. * It is recommended to use this version of `readRenderTargetPixels()` whenever possible.
  53994. *
  53995. * @async
  53996. * @param {WebGLRenderTarget} renderTarget - The render target to read from.
  53997. * @param {number} x - The `x` coordinate of the copy region's origin.
  53998. * @param {number} y - The `y` coordinate of the copy region's origin.
  53999. * @param {number} width - The width of the copy region.
  54000. * @param {number} height - The height of the copy region.
  54001. * @param {TypedArray} buffer - The result buffer.
  54002. * @param {number} [activeCubeFaceIndex] - The active cube face index.
  54003. * @param {number} [textureIndex=0] - The texture index of an MRT render target.
  54004. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  54005. */
  54006. this.readRenderTargetPixelsAsync = async function ( renderTarget, x, y, width, height, buffer, activeCubeFaceIndex, textureIndex = 0 ) {
  54007. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  54008. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  54009. }
  54010. let framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  54011. if ( renderTarget.isWebGLCubeRenderTarget && activeCubeFaceIndex !== undefined ) {
  54012. framebuffer = framebuffer[ activeCubeFaceIndex ];
  54013. }
  54014. if ( framebuffer ) {
  54015. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  54016. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  54017. // set the active frame buffer to the one we want to read
  54018. state.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  54019. const texture = renderTarget.textures[ textureIndex ];
  54020. const textureFormat = texture.format;
  54021. const textureType = texture.type;
  54022. if ( ! capabilities.textureFormatReadable( textureFormat ) ) {
  54023. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.' );
  54024. }
  54025. if ( ! capabilities.textureTypeReadable( textureType ) ) {
  54026. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.' );
  54027. }
  54028. const glBuffer = _gl.createBuffer();
  54029. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54030. _gl.bufferData( _gl.PIXEL_PACK_BUFFER, buffer.byteLength, _gl.STREAM_READ );
  54031. // when using MRT, select the correct color buffer for the subsequent read command
  54032. if ( renderTarget.textures.length > 1 ) _gl.readBuffer( _gl.COLOR_ATTACHMENT0 + textureIndex );
  54033. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), 0 );
  54034. // reset the frame buffer to the currently set buffer before waiting
  54035. const currFramebuffer = _currentRenderTarget !== null ? properties.get( _currentRenderTarget ).__webglFramebuffer : null;
  54036. state.bindFramebuffer( _gl.FRAMEBUFFER, currFramebuffer );
  54037. // check if the commands have finished every 8 ms
  54038. const sync = _gl.fenceSync( _gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  54039. _gl.flush();
  54040. await probeAsync( _gl, sync, 4 );
  54041. // read the data and delete the buffer
  54042. _gl.bindBuffer( _gl.PIXEL_PACK_BUFFER, glBuffer );
  54043. _gl.getBufferSubData( _gl.PIXEL_PACK_BUFFER, 0, buffer );
  54044. _gl.deleteBuffer( glBuffer );
  54045. _gl.deleteSync( sync );
  54046. return buffer;
  54047. } else {
  54048. throw new Error( 'THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.' );
  54049. }
  54050. }
  54051. };
  54052. /**
  54053. * Copies pixels from the current bound framebuffer into the given texture.
  54054. *
  54055. * @param {FramebufferTexture} texture - The texture.
  54056. * @param {?Vector2} [position=null] - The start position of the copy operation.
  54057. * @param {number} [level=0] - The mip level. The default represents the base mip.
  54058. */
  54059. this.copyFramebufferToTexture = function ( texture, position = null, level = 0 ) {
  54060. const levelScale = Math.pow( 2, - level );
  54061. const width = Math.floor( texture.image.width * levelScale );
  54062. const height = Math.floor( texture.image.height * levelScale );
  54063. const x = position !== null ? position.x : 0;
  54064. const y = position !== null ? position.y : 0;
  54065. textures.setTexture2D( texture, 0 );
  54066. _gl.copyTexSubImage2D( _gl.TEXTURE_2D, level, 0, 0, x, y, width, height );
  54067. state.unbindTexture();
  54068. };
  54069. const _srcFramebuffer = _gl.createFramebuffer();
  54070. const _dstFramebuffer = _gl.createFramebuffer();
  54071. /**
  54072. * Copies data of the given source texture into a destination texture.
  54073. *
  54074. * When using render target textures as `srcTexture` and `dstTexture`, you must make sure both render targets are initialized
  54075. * {@link WebGLRenderer#initRenderTarget}.
  54076. *
  54077. * @param {Texture} srcTexture - The source texture.
  54078. * @param {Texture} dstTexture - The destination texture.
  54079. * @param {?(Box2|Box3)} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  54080. * @param {?(Vector2|Vector3)} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  54081. * @param {number} [srcLevel=0] - The source mipmap level to copy.
  54082. * @param {?number} [dstLevel=null] - The destination mipmap level.
  54083. */
  54084. this.copyTextureToTexture = function ( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = null ) {
  54085. // support the previous signature with just a single dst mipmap level
  54086. if ( dstLevel === null ) {
  54087. if ( srcLevel !== 0 ) {
  54088. // @deprecated, r171
  54089. warnOnce( 'WebGLRenderer: copyTextureToTexture function signature has changed to support src and dst mipmap levels.' );
  54090. dstLevel = srcLevel;
  54091. srcLevel = 0;
  54092. } else {
  54093. dstLevel = 0;
  54094. }
  54095. }
  54096. // gather the necessary dimensions to copy
  54097. let width, height, depth, minX, minY, minZ;
  54098. let dstX, dstY, dstZ;
  54099. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  54100. if ( srcRegion !== null ) {
  54101. width = srcRegion.max.x - srcRegion.min.x;
  54102. height = srcRegion.max.y - srcRegion.min.y;
  54103. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  54104. minX = srcRegion.min.x;
  54105. minY = srcRegion.min.y;
  54106. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  54107. } else {
  54108. const levelScale = Math.pow( 2, - srcLevel );
  54109. width = Math.floor( image.width * levelScale );
  54110. height = Math.floor( image.height * levelScale );
  54111. if ( srcTexture.isDataArrayTexture ) {
  54112. depth = image.depth;
  54113. } else if ( srcTexture.isData3DTexture ) {
  54114. depth = Math.floor( image.depth * levelScale );
  54115. } else {
  54116. depth = 1;
  54117. }
  54118. minX = 0;
  54119. minY = 0;
  54120. minZ = 0;
  54121. }
  54122. if ( dstPosition !== null ) {
  54123. dstX = dstPosition.x;
  54124. dstY = dstPosition.y;
  54125. dstZ = dstPosition.z;
  54126. } else {
  54127. dstX = 0;
  54128. dstY = 0;
  54129. dstZ = 0;
  54130. }
  54131. // Set up the destination target
  54132. const glFormat = utils.convert( dstTexture.format );
  54133. const glType = utils.convert( dstTexture.type );
  54134. let glTarget;
  54135. if ( dstTexture.isData3DTexture ) {
  54136. textures.setTexture3D( dstTexture, 0 );
  54137. glTarget = _gl.TEXTURE_3D;
  54138. } else if ( dstTexture.isDataArrayTexture || dstTexture.isCompressedArrayTexture ) {
  54139. textures.setTexture2DArray( dstTexture, 0 );
  54140. glTarget = _gl.TEXTURE_2D_ARRAY;
  54141. } else {
  54142. textures.setTexture2D( dstTexture, 0 );
  54143. glTarget = _gl.TEXTURE_2D;
  54144. }
  54145. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  54146. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  54147. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  54148. // used for copying data from cpu
  54149. const currentUnpackRowLen = _gl.getParameter( _gl.UNPACK_ROW_LENGTH );
  54150. const currentUnpackImageHeight = _gl.getParameter( _gl.UNPACK_IMAGE_HEIGHT );
  54151. const currentUnpackSkipPixels = _gl.getParameter( _gl.UNPACK_SKIP_PIXELS );
  54152. const currentUnpackSkipRows = _gl.getParameter( _gl.UNPACK_SKIP_ROWS );
  54153. const currentUnpackSkipImages = _gl.getParameter( _gl.UNPACK_SKIP_IMAGES );
  54154. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, image.width );
  54155. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, image.height );
  54156. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, minX );
  54157. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, minY );
  54158. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, minZ );
  54159. // set up the src texture
  54160. const isSrc3D = srcTexture.isDataArrayTexture || srcTexture.isData3DTexture;
  54161. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture;
  54162. if ( srcTexture.isDepthTexture ) {
  54163. const srcTextureProperties = properties.get( srcTexture );
  54164. const dstTextureProperties = properties.get( dstTexture );
  54165. const srcRenderTargetProperties = properties.get( srcTextureProperties.__renderTarget );
  54166. const dstRenderTargetProperties = properties.get( dstTextureProperties.__renderTarget );
  54167. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, srcRenderTargetProperties.__webglFramebuffer );
  54168. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, dstRenderTargetProperties.__webglFramebuffer );
  54169. for ( let i = 0; i < depth; i ++ ) {
  54170. // if the source or destination are a 3d target then a layer needs to be bound
  54171. if ( isSrc3D ) {
  54172. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( srcTexture ).__webglTexture, srcLevel, minZ + i );
  54173. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, properties.get( dstTexture ).__webglTexture, dstLevel, dstZ + i );
  54174. }
  54175. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.DEPTH_BUFFER_BIT, _gl.NEAREST );
  54176. }
  54177. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54178. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54179. } else if ( srcLevel !== 0 || srcTexture.isRenderTargetTexture || properties.has( srcTexture ) ) {
  54180. // get the appropriate frame buffers
  54181. const srcTextureProperties = properties.get( srcTexture );
  54182. const dstTextureProperties = properties.get( dstTexture );
  54183. // bind the frame buffer targets
  54184. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, _srcFramebuffer );
  54185. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, _dstFramebuffer );
  54186. for ( let i = 0; i < depth; i ++ ) {
  54187. // assign the correct layers and mip maps to the frame buffers
  54188. if ( isSrc3D ) {
  54189. _gl.framebufferTextureLayer( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, srcTextureProperties.__webglTexture, srcLevel, minZ + i );
  54190. } else {
  54191. _gl.framebufferTexture2D( _gl.READ_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, srcTextureProperties.__webglTexture, srcLevel );
  54192. }
  54193. if ( isDst3D ) {
  54194. _gl.framebufferTextureLayer( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, dstTextureProperties.__webglTexture, dstLevel, dstZ + i );
  54195. } else {
  54196. _gl.framebufferTexture2D( _gl.DRAW_FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, dstTextureProperties.__webglTexture, dstLevel );
  54197. }
  54198. // copy the data using the fastest function that can achieve the copy
  54199. if ( srcLevel !== 0 ) {
  54200. _gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, _gl.COLOR_BUFFER_BIT, _gl.NEAREST );
  54201. } else if ( isDst3D ) {
  54202. _gl.copyTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ + i, minX, minY, width, height );
  54203. } else {
  54204. _gl.copyTexSubImage2D( glTarget, dstLevel, dstX, dstY, minX, minY, width, height );
  54205. }
  54206. }
  54207. // unbind read, draw buffers
  54208. state.bindFramebuffer( _gl.READ_FRAMEBUFFER, null );
  54209. state.bindFramebuffer( _gl.DRAW_FRAMEBUFFER, null );
  54210. } else {
  54211. if ( isDst3D ) {
  54212. // copy data into the 3d texture
  54213. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  54214. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  54215. } else if ( dstTexture.isCompressedArrayTexture ) {
  54216. _gl.compressedTexSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  54217. } else {
  54218. _gl.texSubImage3D( glTarget, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  54219. }
  54220. } else {
  54221. // copy data into the 2d texture
  54222. if ( srcTexture.isDataTexture ) {
  54223. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  54224. } else if ( srcTexture.isCompressedTexture ) {
  54225. _gl.compressedTexSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  54226. } else {
  54227. _gl.texSubImage2D( _gl.TEXTURE_2D, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  54228. }
  54229. }
  54230. }
  54231. // reset values
  54232. _gl.pixelStorei( _gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  54233. _gl.pixelStorei( _gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  54234. _gl.pixelStorei( _gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  54235. _gl.pixelStorei( _gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  54236. _gl.pixelStorei( _gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  54237. // Generate mipmaps only when copying level 0
  54238. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  54239. _gl.generateMipmap( glTarget );
  54240. }
  54241. state.unbindTexture();
  54242. };
  54243. /**
  54244. * Initializes the given WebGLRenderTarget memory. Useful for initializing a render target so data
  54245. * can be copied into it using {@link WebGLRenderer#copyTextureToTexture} before it has been
  54246. * rendered to.
  54247. *
  54248. * @param {WebGLRenderTarget} target - The render target.
  54249. */
  54250. this.initRenderTarget = function ( target ) {
  54251. if ( properties.get( target ).__webglFramebuffer === undefined ) {
  54252. textures.setupRenderTarget( target );
  54253. }
  54254. };
  54255. /**
  54256. * Initializes the given texture. Useful for preloading a texture rather than waiting until first
  54257. * render (which can cause noticeable lags due to decode and GPU upload overhead).
  54258. *
  54259. * @param {Texture} texture - The texture.
  54260. */
  54261. this.initTexture = function ( texture ) {
  54262. if ( texture.isCubeTexture ) {
  54263. textures.setTextureCube( texture, 0 );
  54264. } else if ( texture.isData3DTexture ) {
  54265. textures.setTexture3D( texture, 0 );
  54266. } else if ( texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  54267. textures.setTexture2DArray( texture, 0 );
  54268. } else {
  54269. textures.setTexture2D( texture, 0 );
  54270. }
  54271. state.unbindTexture();
  54272. };
  54273. /**
  54274. * Can be used to reset the internal WebGL state. This method is mostly
  54275. * relevant for applications which share a single WebGL context across
  54276. * multiple WebGL libraries.
  54277. */
  54278. this.resetState = function () {
  54279. _currentActiveCubeFace = 0;
  54280. _currentActiveMipmapLevel = 0;
  54281. _currentRenderTarget = null;
  54282. state.reset();
  54283. bindingStates.reset();
  54284. };
  54285. if ( typeof __THREE_DEVTOOLS__ !== 'undefined' ) {
  54286. __THREE_DEVTOOLS__.dispatchEvent( new CustomEvent( 'observe', { detail: this } ) );
  54287. }
  54288. }
  54289. /**
  54290. * Defines the coordinate system of the renderer.
  54291. *
  54292. * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`.
  54293. *
  54294. * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem}
  54295. * @default WebGLCoordinateSystem
  54296. * @readonly
  54297. */
  54298. get coordinateSystem() {
  54299. return WebGLCoordinateSystem;
  54300. }
  54301. /**
  54302. * Defines the output color space of the renderer.
  54303. *
  54304. * @type {SRGBColorSpace|LinearSRGBColorSpace}
  54305. * @default SRGBColorSpace
  54306. */
  54307. get outputColorSpace() {
  54308. return this._outputColorSpace;
  54309. }
  54310. set outputColorSpace( colorSpace ) {
  54311. this._outputColorSpace = colorSpace;
  54312. const gl = this.getContext();
  54313. gl.drawingBufferColorSpace = ColorManagement._getDrawingBufferColorSpace( colorSpace );
  54314. gl.unpackColorSpace = ColorManagement._getUnpackColorSpace();
  54315. }
  54316. }
  54317. exports.ACESFilmicToneMapping = ACESFilmicToneMapping;
  54318. exports.AddEquation = AddEquation;
  54319. exports.AddOperation = AddOperation;
  54320. exports.AdditiveAnimationBlendMode = AdditiveAnimationBlendMode;
  54321. exports.AdditiveBlending = AdditiveBlending;
  54322. exports.AgXToneMapping = AgXToneMapping;
  54323. exports.AlphaFormat = AlphaFormat;
  54324. exports.AlwaysCompare = AlwaysCompare;
  54325. exports.AlwaysDepth = AlwaysDepth;
  54326. exports.AlwaysStencilFunc = AlwaysStencilFunc;
  54327. exports.AmbientLight = AmbientLight;
  54328. exports.AnimationAction = AnimationAction;
  54329. exports.AnimationClip = AnimationClip;
  54330. exports.AnimationLoader = AnimationLoader;
  54331. exports.AnimationMixer = AnimationMixer;
  54332. exports.AnimationObjectGroup = AnimationObjectGroup;
  54333. exports.AnimationUtils = AnimationUtils;
  54334. exports.ArcCurve = ArcCurve;
  54335. exports.ArrayCamera = ArrayCamera;
  54336. exports.ArrowHelper = ArrowHelper;
  54337. exports.AttachedBindMode = AttachedBindMode;
  54338. exports.Audio = Audio;
  54339. exports.AudioAnalyser = AudioAnalyser;
  54340. exports.AudioContext = AudioContext;
  54341. exports.AudioListener = AudioListener;
  54342. exports.AudioLoader = AudioLoader;
  54343. exports.AxesHelper = AxesHelper;
  54344. exports.BackSide = BackSide;
  54345. exports.BasicDepthPacking = BasicDepthPacking;
  54346. exports.BasicShadowMap = BasicShadowMap;
  54347. exports.BatchedMesh = BatchedMesh;
  54348. exports.Bone = Bone;
  54349. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  54350. exports.Box2 = Box2;
  54351. exports.Box3 = Box3;
  54352. exports.Box3Helper = Box3Helper;
  54353. exports.BoxGeometry = BoxGeometry;
  54354. exports.BoxHelper = BoxHelper;
  54355. exports.BufferAttribute = BufferAttribute;
  54356. exports.BufferGeometry = BufferGeometry;
  54357. exports.BufferGeometryLoader = BufferGeometryLoader;
  54358. exports.ByteType = ByteType;
  54359. exports.Cache = Cache;
  54360. exports.Camera = Camera;
  54361. exports.CameraHelper = CameraHelper;
  54362. exports.CanvasTexture = CanvasTexture;
  54363. exports.CapsuleGeometry = CapsuleGeometry;
  54364. exports.CatmullRomCurve3 = CatmullRomCurve3;
  54365. exports.CineonToneMapping = CineonToneMapping;
  54366. exports.CircleGeometry = CircleGeometry;
  54367. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  54368. exports.Clock = Clock;
  54369. exports.Color = Color;
  54370. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  54371. exports.ColorManagement = ColorManagement;
  54372. exports.CompressedArrayTexture = CompressedArrayTexture;
  54373. exports.CompressedCubeTexture = CompressedCubeTexture;
  54374. exports.CompressedTexture = CompressedTexture;
  54375. exports.CompressedTextureLoader = CompressedTextureLoader;
  54376. exports.ConeGeometry = ConeGeometry;
  54377. exports.ConstantAlphaFactor = ConstantAlphaFactor;
  54378. exports.ConstantColorFactor = ConstantColorFactor;
  54379. exports.Controls = Controls;
  54380. exports.CubeCamera = CubeCamera;
  54381. exports.CubeDepthTexture = CubeDepthTexture;
  54382. exports.CubeReflectionMapping = CubeReflectionMapping;
  54383. exports.CubeRefractionMapping = CubeRefractionMapping;
  54384. exports.CubeTexture = CubeTexture;
  54385. exports.CubeTextureLoader = CubeTextureLoader;
  54386. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  54387. exports.CubicBezierCurve = CubicBezierCurve;
  54388. exports.CubicBezierCurve3 = CubicBezierCurve3;
  54389. exports.CubicInterpolant = CubicInterpolant;
  54390. exports.CullFaceBack = CullFaceBack;
  54391. exports.CullFaceFront = CullFaceFront;
  54392. exports.CullFaceFrontBack = CullFaceFrontBack;
  54393. exports.CullFaceNone = CullFaceNone;
  54394. exports.Curve = Curve;
  54395. exports.CurvePath = CurvePath;
  54396. exports.CustomBlending = CustomBlending;
  54397. exports.CustomToneMapping = CustomToneMapping;
  54398. exports.CylinderGeometry = CylinderGeometry;
  54399. exports.Cylindrical = Cylindrical;
  54400. exports.Data3DTexture = Data3DTexture;
  54401. exports.DataArrayTexture = DataArrayTexture;
  54402. exports.DataTexture = DataTexture;
  54403. exports.DataTextureLoader = DataTextureLoader;
  54404. exports.DataUtils = DataUtils;
  54405. exports.DecrementStencilOp = DecrementStencilOp;
  54406. exports.DecrementWrapStencilOp = DecrementWrapStencilOp;
  54407. exports.DefaultLoadingManager = DefaultLoadingManager;
  54408. exports.DepthFormat = DepthFormat;
  54409. exports.DepthStencilFormat = DepthStencilFormat;
  54410. exports.DepthTexture = DepthTexture;
  54411. exports.DetachedBindMode = DetachedBindMode;
  54412. exports.DirectionalLight = DirectionalLight;
  54413. exports.DirectionalLightHelper = DirectionalLightHelper;
  54414. exports.DiscreteInterpolant = DiscreteInterpolant;
  54415. exports.DodecahedronGeometry = DodecahedronGeometry;
  54416. exports.DoubleSide = DoubleSide;
  54417. exports.DstAlphaFactor = DstAlphaFactor;
  54418. exports.DstColorFactor = DstColorFactor;
  54419. exports.DynamicCopyUsage = DynamicCopyUsage;
  54420. exports.DynamicDrawUsage = DynamicDrawUsage;
  54421. exports.DynamicReadUsage = DynamicReadUsage;
  54422. exports.EdgesGeometry = EdgesGeometry;
  54423. exports.EllipseCurve = EllipseCurve;
  54424. exports.EqualCompare = EqualCompare;
  54425. exports.EqualDepth = EqualDepth;
  54426. exports.EqualStencilFunc = EqualStencilFunc;
  54427. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  54428. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  54429. exports.Euler = Euler;
  54430. exports.EventDispatcher = EventDispatcher;
  54431. exports.ExternalTexture = ExternalTexture;
  54432. exports.ExtrudeGeometry = ExtrudeGeometry;
  54433. exports.FileLoader = FileLoader;
  54434. exports.Float16BufferAttribute = Float16BufferAttribute;
  54435. exports.Float32BufferAttribute = Float32BufferAttribute;
  54436. exports.FloatType = FloatType;
  54437. exports.Fog = Fog;
  54438. exports.FogExp2 = FogExp2;
  54439. exports.FramebufferTexture = FramebufferTexture;
  54440. exports.FrontSide = FrontSide;
  54441. exports.Frustum = Frustum;
  54442. exports.FrustumArray = FrustumArray;
  54443. exports.GLBufferAttribute = GLBufferAttribute;
  54444. exports.GLSL1 = GLSL1;
  54445. exports.GLSL3 = GLSL3;
  54446. exports.GreaterCompare = GreaterCompare;
  54447. exports.GreaterDepth = GreaterDepth;
  54448. exports.GreaterEqualCompare = GreaterEqualCompare;
  54449. exports.GreaterEqualDepth = GreaterEqualDepth;
  54450. exports.GreaterEqualStencilFunc = GreaterEqualStencilFunc;
  54451. exports.GreaterStencilFunc = GreaterStencilFunc;
  54452. exports.GridHelper = GridHelper;
  54453. exports.Group = Group;
  54454. exports.HalfFloatType = HalfFloatType;
  54455. exports.HemisphereLight = HemisphereLight;
  54456. exports.HemisphereLightHelper = HemisphereLightHelper;
  54457. exports.IcosahedronGeometry = IcosahedronGeometry;
  54458. exports.IdentityDepthPacking = IdentityDepthPacking;
  54459. exports.ImageBitmapLoader = ImageBitmapLoader;
  54460. exports.ImageLoader = ImageLoader;
  54461. exports.ImageUtils = ImageUtils;
  54462. exports.IncrementStencilOp = IncrementStencilOp;
  54463. exports.IncrementWrapStencilOp = IncrementWrapStencilOp;
  54464. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  54465. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  54466. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  54467. exports.InstancedMesh = InstancedMesh;
  54468. exports.Int16BufferAttribute = Int16BufferAttribute;
  54469. exports.Int32BufferAttribute = Int32BufferAttribute;
  54470. exports.Int8BufferAttribute = Int8BufferAttribute;
  54471. exports.IntType = IntType;
  54472. exports.InterleavedBuffer = InterleavedBuffer;
  54473. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  54474. exports.Interpolant = Interpolant;
  54475. exports.InterpolateDiscrete = InterpolateDiscrete;
  54476. exports.InterpolateLinear = InterpolateLinear;
  54477. exports.InterpolateSmooth = InterpolateSmooth;
  54478. exports.InterpolationSamplingMode = InterpolationSamplingMode;
  54479. exports.InterpolationSamplingType = InterpolationSamplingType;
  54480. exports.InvertStencilOp = InvertStencilOp;
  54481. exports.KeepStencilOp = KeepStencilOp;
  54482. exports.KeyframeTrack = KeyframeTrack;
  54483. exports.LOD = LOD;
  54484. exports.LatheGeometry = LatheGeometry;
  54485. exports.Layers = Layers;
  54486. exports.LessCompare = LessCompare;
  54487. exports.LessDepth = LessDepth;
  54488. exports.LessEqualCompare = LessEqualCompare;
  54489. exports.LessEqualDepth = LessEqualDepth;
  54490. exports.LessEqualStencilFunc = LessEqualStencilFunc;
  54491. exports.LessStencilFunc = LessStencilFunc;
  54492. exports.Light = Light;
  54493. exports.LightProbe = LightProbe;
  54494. exports.Line = Line;
  54495. exports.Line3 = Line3;
  54496. exports.LineBasicMaterial = LineBasicMaterial;
  54497. exports.LineCurve = LineCurve;
  54498. exports.LineCurve3 = LineCurve3;
  54499. exports.LineDashedMaterial = LineDashedMaterial;
  54500. exports.LineLoop = LineLoop;
  54501. exports.LineSegments = LineSegments;
  54502. exports.LinearFilter = LinearFilter;
  54503. exports.LinearInterpolant = LinearInterpolant;
  54504. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  54505. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  54506. exports.LinearMipmapLinearFilter = LinearMipmapLinearFilter;
  54507. exports.LinearMipmapNearestFilter = LinearMipmapNearestFilter;
  54508. exports.LinearSRGBColorSpace = LinearSRGBColorSpace;
  54509. exports.LinearToneMapping = LinearToneMapping;
  54510. exports.LinearTransfer = LinearTransfer;
  54511. exports.Loader = Loader;
  54512. exports.LoaderUtils = LoaderUtils;
  54513. exports.LoadingManager = LoadingManager;
  54514. exports.LoopOnce = LoopOnce;
  54515. exports.LoopPingPong = LoopPingPong;
  54516. exports.LoopRepeat = LoopRepeat;
  54517. exports.MOUSE = MOUSE;
  54518. exports.Material = Material;
  54519. exports.MaterialLoader = MaterialLoader;
  54520. exports.MathUtils = MathUtils;
  54521. exports.Matrix2 = Matrix2;
  54522. exports.Matrix3 = Matrix3;
  54523. exports.Matrix4 = Matrix4;
  54524. exports.MaxEquation = MaxEquation;
  54525. exports.Mesh = Mesh;
  54526. exports.MeshBasicMaterial = MeshBasicMaterial;
  54527. exports.MeshDepthMaterial = MeshDepthMaterial;
  54528. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  54529. exports.MeshLambertMaterial = MeshLambertMaterial;
  54530. exports.MeshMatcapMaterial = MeshMatcapMaterial;
  54531. exports.MeshNormalMaterial = MeshNormalMaterial;
  54532. exports.MeshPhongMaterial = MeshPhongMaterial;
  54533. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  54534. exports.MeshStandardMaterial = MeshStandardMaterial;
  54535. exports.MeshToonMaterial = MeshToonMaterial;
  54536. exports.MinEquation = MinEquation;
  54537. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  54538. exports.MixOperation = MixOperation;
  54539. exports.MultiplyBlending = MultiplyBlending;
  54540. exports.MultiplyOperation = MultiplyOperation;
  54541. exports.NearestFilter = NearestFilter;
  54542. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  54543. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  54544. exports.NearestMipmapLinearFilter = NearestMipmapLinearFilter;
  54545. exports.NearestMipmapNearestFilter = NearestMipmapNearestFilter;
  54546. exports.NeutralToneMapping = NeutralToneMapping;
  54547. exports.NeverCompare = NeverCompare;
  54548. exports.NeverDepth = NeverDepth;
  54549. exports.NeverStencilFunc = NeverStencilFunc;
  54550. exports.NoBlending = NoBlending;
  54551. exports.NoColorSpace = NoColorSpace;
  54552. exports.NoNormalPacking = NoNormalPacking;
  54553. exports.NoToneMapping = NoToneMapping;
  54554. exports.NormalAnimationBlendMode = NormalAnimationBlendMode;
  54555. exports.NormalBlending = NormalBlending;
  54556. exports.NormalGAPacking = NormalGAPacking;
  54557. exports.NormalRGPacking = NormalRGPacking;
  54558. exports.NotEqualCompare = NotEqualCompare;
  54559. exports.NotEqualDepth = NotEqualDepth;
  54560. exports.NotEqualStencilFunc = NotEqualStencilFunc;
  54561. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  54562. exports.Object3D = Object3D;
  54563. exports.ObjectLoader = ObjectLoader;
  54564. exports.ObjectSpaceNormalMap = ObjectSpaceNormalMap;
  54565. exports.OctahedronGeometry = OctahedronGeometry;
  54566. exports.OneFactor = OneFactor;
  54567. exports.OneMinusConstantAlphaFactor = OneMinusConstantAlphaFactor;
  54568. exports.OneMinusConstantColorFactor = OneMinusConstantColorFactor;
  54569. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  54570. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  54571. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  54572. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  54573. exports.OrthographicCamera = OrthographicCamera;
  54574. exports.PCFShadowMap = PCFShadowMap;
  54575. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  54576. exports.PMREMGenerator = PMREMGenerator;
  54577. exports.Path = Path;
  54578. exports.PerspectiveCamera = PerspectiveCamera;
  54579. exports.Plane = Plane;
  54580. exports.PlaneGeometry = PlaneGeometry;
  54581. exports.PlaneHelper = PlaneHelper;
  54582. exports.PointLight = PointLight;
  54583. exports.PointLightHelper = PointLightHelper;
  54584. exports.Points = Points;
  54585. exports.PointsMaterial = PointsMaterial;
  54586. exports.PolarGridHelper = PolarGridHelper;
  54587. exports.PolyhedronGeometry = PolyhedronGeometry;
  54588. exports.PositionalAudio = PositionalAudio;
  54589. exports.PropertyBinding = PropertyBinding;
  54590. exports.PropertyMixer = PropertyMixer;
  54591. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  54592. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  54593. exports.Quaternion = Quaternion;
  54594. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  54595. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  54596. exports.R11_EAC_Format = R11_EAC_Format;
  54597. exports.RED_GREEN_RGTC2_Format = RED_GREEN_RGTC2_Format;
  54598. exports.RED_RGTC1_Format = RED_RGTC1_Format;
  54599. exports.REVISION = REVISION;
  54600. exports.RG11_EAC_Format = RG11_EAC_Format;
  54601. exports.RGBADepthPacking = RGBADepthPacking;
  54602. exports.RGBAFormat = RGBAFormat;
  54603. exports.RGBAIntegerFormat = RGBAIntegerFormat;
  54604. exports.RGBA_ASTC_10x10_Format = RGBA_ASTC_10x10_Format;
  54605. exports.RGBA_ASTC_10x5_Format = RGBA_ASTC_10x5_Format;
  54606. exports.RGBA_ASTC_10x6_Format = RGBA_ASTC_10x6_Format;
  54607. exports.RGBA_ASTC_10x8_Format = RGBA_ASTC_10x8_Format;
  54608. exports.RGBA_ASTC_12x10_Format = RGBA_ASTC_12x10_Format;
  54609. exports.RGBA_ASTC_12x12_Format = RGBA_ASTC_12x12_Format;
  54610. exports.RGBA_ASTC_4x4_Format = RGBA_ASTC_4x4_Format;
  54611. exports.RGBA_ASTC_5x4_Format = RGBA_ASTC_5x4_Format;
  54612. exports.RGBA_ASTC_5x5_Format = RGBA_ASTC_5x5_Format;
  54613. exports.RGBA_ASTC_6x5_Format = RGBA_ASTC_6x5_Format;
  54614. exports.RGBA_ASTC_6x6_Format = RGBA_ASTC_6x6_Format;
  54615. exports.RGBA_ASTC_8x5_Format = RGBA_ASTC_8x5_Format;
  54616. exports.RGBA_ASTC_8x6_Format = RGBA_ASTC_8x6_Format;
  54617. exports.RGBA_ASTC_8x8_Format = RGBA_ASTC_8x8_Format;
  54618. exports.RGBA_BPTC_Format = RGBA_BPTC_Format;
  54619. exports.RGBA_ETC2_EAC_Format = RGBA_ETC2_EAC_Format;
  54620. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  54621. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  54622. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  54623. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  54624. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  54625. exports.RGBDepthPacking = RGBDepthPacking;
  54626. exports.RGBFormat = RGBFormat;
  54627. exports.RGBIntegerFormat = RGBIntegerFormat;
  54628. exports.RGB_BPTC_SIGNED_Format = RGB_BPTC_SIGNED_Format;
  54629. exports.RGB_BPTC_UNSIGNED_Format = RGB_BPTC_UNSIGNED_Format;
  54630. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  54631. exports.RGB_ETC2_Format = RGB_ETC2_Format;
  54632. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  54633. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  54634. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  54635. exports.RGDepthPacking = RGDepthPacking;
  54636. exports.RGFormat = RGFormat;
  54637. exports.RGIntegerFormat = RGIntegerFormat;
  54638. exports.RawShaderMaterial = RawShaderMaterial;
  54639. exports.Ray = Ray;
  54640. exports.Raycaster = Raycaster;
  54641. exports.RectAreaLight = RectAreaLight;
  54642. exports.RedFormat = RedFormat;
  54643. exports.RedIntegerFormat = RedIntegerFormat;
  54644. exports.ReinhardToneMapping = ReinhardToneMapping;
  54645. exports.RenderTarget = RenderTarget;
  54646. exports.RenderTarget3D = RenderTarget3D;
  54647. exports.RepeatWrapping = RepeatWrapping;
  54648. exports.ReplaceStencilOp = ReplaceStencilOp;
  54649. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  54650. exports.RingGeometry = RingGeometry;
  54651. exports.SIGNED_R11_EAC_Format = SIGNED_R11_EAC_Format;
  54652. exports.SIGNED_RED_GREEN_RGTC2_Format = SIGNED_RED_GREEN_RGTC2_Format;
  54653. exports.SIGNED_RED_RGTC1_Format = SIGNED_RED_RGTC1_Format;
  54654. exports.SIGNED_RG11_EAC_Format = SIGNED_RG11_EAC_Format;
  54655. exports.SRGBColorSpace = SRGBColorSpace;
  54656. exports.SRGBTransfer = SRGBTransfer;
  54657. exports.Scene = Scene;
  54658. exports.ShaderChunk = ShaderChunk;
  54659. exports.ShaderLib = ShaderLib;
  54660. exports.ShaderMaterial = ShaderMaterial;
  54661. exports.ShadowMaterial = ShadowMaterial;
  54662. exports.Shape = Shape;
  54663. exports.ShapeGeometry = ShapeGeometry;
  54664. exports.ShapePath = ShapePath;
  54665. exports.ShapeUtils = ShapeUtils;
  54666. exports.ShortType = ShortType;
  54667. exports.Skeleton = Skeleton;
  54668. exports.SkeletonHelper = SkeletonHelper;
  54669. exports.SkinnedMesh = SkinnedMesh;
  54670. exports.Source = Source;
  54671. exports.Sphere = Sphere;
  54672. exports.SphereGeometry = SphereGeometry;
  54673. exports.Spherical = Spherical;
  54674. exports.SphericalHarmonics3 = SphericalHarmonics3;
  54675. exports.SplineCurve = SplineCurve;
  54676. exports.SpotLight = SpotLight;
  54677. exports.SpotLightHelper = SpotLightHelper;
  54678. exports.Sprite = Sprite;
  54679. exports.SpriteMaterial = SpriteMaterial;
  54680. exports.SrcAlphaFactor = SrcAlphaFactor;
  54681. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  54682. exports.SrcColorFactor = SrcColorFactor;
  54683. exports.StaticCopyUsage = StaticCopyUsage;
  54684. exports.StaticDrawUsage = StaticDrawUsage;
  54685. exports.StaticReadUsage = StaticReadUsage;
  54686. exports.StereoCamera = StereoCamera;
  54687. exports.StreamCopyUsage = StreamCopyUsage;
  54688. exports.StreamDrawUsage = StreamDrawUsage;
  54689. exports.StreamReadUsage = StreamReadUsage;
  54690. exports.StringKeyframeTrack = StringKeyframeTrack;
  54691. exports.SubtractEquation = SubtractEquation;
  54692. exports.SubtractiveBlending = SubtractiveBlending;
  54693. exports.TOUCH = TOUCH;
  54694. exports.TangentSpaceNormalMap = TangentSpaceNormalMap;
  54695. exports.TetrahedronGeometry = TetrahedronGeometry;
  54696. exports.Texture = Texture;
  54697. exports.TextureLoader = TextureLoader;
  54698. exports.TextureUtils = TextureUtils;
  54699. exports.Timer = Timer;
  54700. exports.TimestampQuery = TimestampQuery;
  54701. exports.TorusGeometry = TorusGeometry;
  54702. exports.TorusKnotGeometry = TorusKnotGeometry;
  54703. exports.Triangle = Triangle;
  54704. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  54705. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  54706. exports.TrianglesDrawMode = TrianglesDrawMode;
  54707. exports.TubeGeometry = TubeGeometry;
  54708. exports.UVMapping = UVMapping;
  54709. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  54710. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  54711. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  54712. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  54713. exports.Uniform = Uniform;
  54714. exports.UniformsGroup = UniformsGroup;
  54715. exports.UniformsLib = UniformsLib;
  54716. exports.UniformsUtils = UniformsUtils;
  54717. exports.UnsignedByteType = UnsignedByteType;
  54718. exports.UnsignedInt101111Type = UnsignedInt101111Type;
  54719. exports.UnsignedInt248Type = UnsignedInt248Type;
  54720. exports.UnsignedInt5999Type = UnsignedInt5999Type;
  54721. exports.UnsignedIntType = UnsignedIntType;
  54722. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  54723. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  54724. exports.UnsignedShortType = UnsignedShortType;
  54725. exports.VSMShadowMap = VSMShadowMap;
  54726. exports.Vector2 = Vector2;
  54727. exports.Vector3 = Vector3;
  54728. exports.Vector4 = Vector4;
  54729. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  54730. exports.VideoFrameTexture = VideoFrameTexture;
  54731. exports.VideoTexture = VideoTexture;
  54732. exports.WebGL3DRenderTarget = WebGL3DRenderTarget;
  54733. exports.WebGLArrayRenderTarget = WebGLArrayRenderTarget;
  54734. exports.WebGLCoordinateSystem = WebGLCoordinateSystem;
  54735. exports.WebGLCubeRenderTarget = WebGLCubeRenderTarget;
  54736. exports.WebGLRenderTarget = WebGLRenderTarget;
  54737. exports.WebGLRenderer = WebGLRenderer;
  54738. exports.WebGLUtils = WebGLUtils;
  54739. exports.WebGPUCoordinateSystem = WebGPUCoordinateSystem;
  54740. exports.WebXRController = WebXRController;
  54741. exports.WireframeGeometry = WireframeGeometry;
  54742. exports.WrapAroundEnding = WrapAroundEnding;
  54743. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  54744. exports.ZeroFactor = ZeroFactor;
  54745. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  54746. exports.ZeroStencilOp = ZeroStencilOp;
  54747. exports.createCanvasElement = createCanvasElement;
  54748. exports.error = error;
  54749. exports.getConsoleFunction = getConsoleFunction;
  54750. exports.log = log;
  54751. exports.setConsoleFunction = setConsoleFunction;
  54752. exports.warn = warn;
  54753. exports.warnOnce = warnOnce;
粤ICP备19079148号